AttrList.cpp0000644000076500000240000001251511652342063013210 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : AttrList.cpp // Purpose : Class to keep set of key,value pairs // Access methods to get/set using different data types. // All information is stored as strings and converted as required. This will // lead to slow execution for variables being acessed often. This class is // intended for long term storage of attributes. // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #include "AttrList.h" /////////////////////////////////////////////////////////////////////////////////////////////////// // AttrList.cpp: implementation of the CAttrList class. // /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // Construction/Destruction /////////////////////////////////////////////////////////////////////////////////////////////////// LPCSTR CAttrList :: operator[](LPCSTR key) const { CAttrDictIter iter; iter = m.find(key); if (iter == m.end()) return NULL; return (*iter).second.c_str(); } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CAttrList :: Clear() { m.clear(); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CAttrList :: GetInt(LPCSTR key, int _default) { LPCSTR value = m[key].c_str(); if ((value == NULL) || (value == "")) return _default; return atoi(value); } /////////////////////////////////////////////////////////////////////////////////////////////////// DWORD CAttrList :: GetHex(LPCSTR key, DWORD _default) { LPCSTR value = m[key].c_str(); if ((value == NULL) || (value == "")) return _default; return strtol(value, NULL, 0); } /////////////////////////////////////////////////////////////////////////////////////////////////// int CAttrList :: GetBOOL(LPCSTR key, int _default) { LPCSTR value = m[key].c_str(); if ((value == NULL) || (value == "")) return _default; return (atoi(value) != 0); } /////////////////////////////////////////////////////////////////////////////////////////////////// double CAttrList :: GetDouble(LPCSTR key, double _default) { LPCSTR value = m[key].c_str(); if ((value == NULL) || (value == "")) return _default; return atof(value); } /////////////////////////////////////////////////////////////////////////////////////////////////// string CAttrList :: GetString(LPCSTR key, LPCSTR _default) { CAttrDictIter iter; iter = m.find(key); string value; if (iter != m.end()) value = iter->second; else if (_default != NULL) value = _default; return value; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CAttrList :: Add(LPCSTR key, int value) { char buf[64]; sprintf(buf,"%d",value); // itoa(value, buf, 10); m[key] = buf; return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CAttrList :: Add(LPCSTR key, double value) { char buf[64]; sprintf(buf, "%f", value); m[key] = buf; return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CAttrList :: Add(LPCSTR key, LPCSTR value) { m[key] = value; return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CAttrList :: Add(LPCSTR key, string& value) { m[key] = value; return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CAttrList :: AddHex(LPCSTR key, DWORD value) { char buf[64]; sprintf(buf, "0x%08X", value); m[key] = buf; return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CAttrList :: Add(const CAttrList &attrs) { CAttrDictIter iter; for (iter=attrs.m.begin() ; iter != attrs.m.end() ; ++iter) { m[(*iter).first] = (*iter).second; } return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// AttrList.h0000644000076500000240000000506411645204274012661 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : AttrList.h // Purpose : Class to keep set of key,value pairs // Access methods to get/set using different data types. // All information is stored as strings and converted as required. This will // lead to slow execution for variables being acessed often. This class is // intended for long term storage of attributes. // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(__ATTRLIST_H__) #define __ATTRLIST_H__ #include #include #include "Knox_Stddef.h" using namespace std; /////////////////////////////////////////////////////////////////////////////////////////////////// typedef pair CAttrEntry; typedef map CAttrDict; typedef CAttrDict::const_iterator CAttrDictIter; class CAttrList { public: CAttrDict m; LPCSTR operator[](LPCSTR key) const; int GetInt(LPCSTR key, int _default=INT_MAX); DWORD GetHex(LPCSTR key, DWORD _default=INT_MAX); BOOL GetBOOL(LPCSTR key, int _default=-1); double GetDouble(LPCSTR key, double _default=INT_MAX); string GetString(LPCSTR key, LPCSTR _default=""); BOOL Add(LPCSTR key, int value); BOOL Add(LPCSTR key, double value); BOOL Add(LPCSTR key, LPCSTR value); BOOL Add(LPCSTR key, string& value); BOOL AddHex(LPCSTR key, DWORD value); BOOL Add(const CAttrList& list); BOOL Clear(); }; /////////////////////////////////////////////////////////////////////////////////////////////////// #endif Attrs.h0000644000076500000240000001334011645204274012204 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : Attrs.h // Purpose : Predefined attribute names for Phylogenetic Tree Visualization // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(__ATTRS_H__) #define __ATTRS_H__ #define BLACK 0x00000000 #define BLUE 0x00FF0000 #define LTBLUE 0x00FFFF00 #define GRAY 0x00444444 #define DKGRAY 0x00888888 #define GREEN 0x0000FF00 #define DKGREEN 0x00008800 #define YELLOW 0x0000FFFF #define ORANGE 0x000060FF #define RED 0x000000FF #define WHITE 0x00FFFFFF // // Ending character of the attribute name has special meaning. // It is used to identify the type of attribute. // ':' - not editable // '#' - color // '~' - 3 state value (0 - off, 1-on, empty - default) // '!' - font descriptor (font name, size, emph) // '&' - hidden // '@' - // #define DATA_FONT_SELECT '!' #define DATA_COLOR_SELECT '#' #define DATA_BOOL_SELECT '~' #define DATA_XXXX_SELECT ':' #define DATA_HIDDEN_SELECT '&' #define DATA_ADD_ATTRIBUTE '@' #define DATA_SPECIAL_CHARS "!#~:&@" // Attrs that are editable #define ATTR_NAME "NAME" #define ATTR_DISTANCE "Distance" #define ATTR_COMMENT_ON "Comment Show~" #define ATTR_COMMENT "Comment" #define ATTR_COMMENT_INDENT "Comment Indent" #define ATTR_COMMENT_COLOR "Comment Color#" #define ATTR_COMMENT_FONT "Comment Font!" #define ATTR_NODE_MARK1 "Note-1" #define ATTR_TREE_LEGEND_DIST "Legend Value" #define ATTR_TREE_LEGEND_TEXT "Legend Text" #define ATTR_TREE_LEGEND_FONT "Legend Font!" #define ATTR_TREE_LEGEND_COLOR "Legend Color#" #define ATTR_TREE_LEGEND_INDENT "Legend Indent" #define ATTR_TAXALINE_INDENT "Taxa Line Indent" #define ATTR_TAXALINE_COLOR "Taxa Line Color#" #define ATTR_TAXALINE_FONT "Taxa Line Font!" #define ATTR_HIDDEN "Hidden~" #define ATTR_DIFF "Differs" // Leaf Attributes #define ATTR_TAXA_COLOR "Taxa Color#" #define ATTR_TAXA_FONT "Taxa Font!" #define ATTR_TEXT_COLOR ATTR_TAXA_COLOR #define ATTR_TEXT_FONT ATTR_TAXA_FONT // branch attr #define ATTR_BOOTSTRAP_SCALE "Bootstrap Scale" #define ATTR_BOOTSTRAP_FORMAT "Bootstrap Format" #define ATTR_BOOTSTRAP_DATA "Bootstrap Data" #define ATTR_BOOTSTRAP_FONT "Bootstrap Font!" #define ATTR_BOOTSTRAP_COLOR "Bootstrap Color#" #define ATTR_EXPANDED "Expanded~" // Collapsed Branch Attributes #define ATTR_WEDGE_SCALE "Wedge Scale" #define ATTR_WEDGE_COLOR "Wedge Color#" #define ATTR_WEDGE_COUNT_COLOR "Wedge Taxa Count Color#" #define ATTR_WEDGE_COUNT_FONT "Wedge Taxa Count Font!" #define ATTR_WEDGE_COMMENT_SHOW "Wedge Comment Show~" #define ATTR_WEDGE_COMMENT_COLOR "Wedge Comment Color#" #define ATTR_WEDGE_COMMENT_FONT "Wedge Comment Font!" #define ATTR_WEDGE_LABEL_COLOR "Wedge Taxonomy Label Color#" #define ATTR_WEDGE_LABEL_FONT "Wedge Taxonomy Label Font!" #define ATTR_INTERNAL_COLOR "Internal Color#" #define ATTR_INTERNAL_FONT "Internal Font!" // Expanded Branch Attributes #define ATTR_TAXLABEL "Taxonomy Label" #define ATTR_TAXLABEL_COLOR "Taxonomy Label Color#" #define ATTR_TAXLABEL_FONT "Taxonomy Label Font!" #define ATTR_TAXLABEL_SHOW "Taxomomy Label Display~" // TREE ATTR #define ATTR_TREE_SCALE "Display Scale" #define ATTR_TREE_SHOW_BOOT "Bootstrap Show~" #define ATTR_TREE_ROOTED "Rooted" #define ATTR_TREE_SHOW_CLADE_SIZE "Wedge Size Show~" #define ATTR_TREE_SHOW_TAXA_LINE "Taxa Line Show~" #define ATTR_TREE_SHOW_TOPCOMMENT "Top Comment Show~" #define ATTR_TREE_SHOW_LEGEND "Legend Show~" #define ATTR_TREE_SHOW_HIDDEN "Hidden Show~" #define ATTR_TREE_SHOW_COMMENT "Comments Show~" #define ATTR_TOPCOMMENT_SHOW "Top Comment Show~" #define ATTR_TOPCOMMENT_INDENT "Top Comment Indent" #define ATTR_TOPCOMMENT_FONT "Top Comment Font!" #define ATTR_TOPCOMMENT_COLOR "Top Comment Color#" #define ATTR_TOPCOMMENT_TEXT "Top Comment Text" #define ATTR_BOTTOMCOMMENT_SHOW "Bottom Comment Show~" #define ATTR_BOTTOMCOMMENT_TEXT "Bottom Comment Text" #define ATTR_BOTTOMCOMMENT_INDENT "Bottom Comment Indent" #define ATTR_BOTTOMCOMMENT_COLOR "Bottom Comment Color#" #define ATTR_BOTTOMCOMMENT_FONT "Bottom Comment Font!" // Internal Attributes that are not editable, but set/used during processing #define ATTR_DEPTH "--DEPTH--" #define ATTR_LEAF_COUNT "--LEAFS--" #define ATTR_BRANCH_COUNT "--BRANCHES--" #define ATTR_MAX_PATH_DIST "--MAX_DIST--" #define ATTR_MIN_PATH_DIST "--MIN_DIST--" #define ATTR_TREE_PGRID_X "--Print Grid X--" #define ATTR_TREE_PGRID_Y "--Print Grid Y--" #define ATTR_TREE_INTERNAL "__INTERNAL__" #define ATTR_TREE_ZOOM "--ZOOM--" #define ATTR_BRANCH_HIDDEN "--HIDDEN--" #endif GNU_license_agpl.txt0000444000076500000240000010333011645204302014622 0ustar davidknoxstaff GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . Knox_Stddef.cpp0000644000076500000240000001173211645204265013655 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : Knox_Stddef.cpp // Purpose : Set of routines and old habit data types // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #include "Knox_Stddef.h" #include // File open for the application log // File is always current (Flushed after each write) FILE *appLog = NULL; /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // // Application Log: Manages a log file. Display functions will print to // multiple locations (Stdout, Application log) // void OpenAppLog(LPCSTR filename, LPCSTR mode) { if (appLog != NULL) CloseAppLog(); appLog = fopen(filename, mode); } void CloseAppLog() { if (appLog != NULL) fclose(appLog); appLog = NULL; } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // Display functions will write to multiple locations (Stdout, Applog, ...) void DisplayT(LPSTR format, ...) { char msg[64*1024]; va_list args; va_start(args, format); /* Initialize variable arguments. */ vsprintf(msg, format, args); printf("%s", msg); fflush(stdout); //TRACE("%s", msg); va_end(args); /* Reset variable arguments. */ } void Display(LPSTR format, ...) { char msg[64*1024]; va_list args; va_start(args, format); /* Initialize variable arguments. */ vsprintf(msg, format, args); printf("%s", msg); va_end(args); /* Reset variable arguments. */ } void DisplayL(LPSTR format, ...) { char msg[64*1024]; va_list args; va_start(args, format); /* Initialize variable arguments. */ vsprintf(msg, format, args); printf("%s", msg); if (appLog != NULL) { int last = strlen(msg); if (last > 0) --last; fprintf(appLog, "%s%s", msg, (msg[last]!='\n'?"\n":"")); fflush(appLog); } va_end(args); /* Reset variable arguments. */ } /////////////////////////////////////////////////////////////////////////////////////////////////// // Read the next line from a file. Skips empty lines or lines begining // with "//" or "#". Removes the trailing CR/LF/space. // BOOL ReadNextLine(LPSTR line, int len, FILE *f) { while ((f != NULL) && !feof(f) && fgets(line, len-1, f)) { // skip empty lines, commented lines, lines without enough data if (strlen(line) == 0) continue; if ((line[0] == '/') && (line[1] == '/')) continue; if (line[0] == '#') continue; // remove ending CR/LF and spaces for (int i=strlen(line) ; i > 0 ; i--) { if ( (line[i-1] == '\r') || (line[i-1] == '\n') || (isspace(line[i-1]))) line[i-1] = 0; else break; } return TRUE; } return FALSE; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Trim unwanted characters from ends of strings // void Trim(string& s, LPCSTR unwanted) { TrimLeft(s, unwanted); TrimRight(s, unwanted); } void TrimLeft(string& s, LPCSTR unwanted) { int start = s.find_first_not_of(unwanted); s = s.substr(start, s.length()); } void TrimRight(string& s, LPCSTR unwanted) { int end = s.length(); while ((end > 0) && (strchr(unwanted, s[end-1]) != NULL)) --end; s = s.substr(0, end); } /////////////////////////////////////////////////////////////////////////////////////////////////// // // Convert string to all one case // void ToLower(string& s) { for (int i=0 ; i < s.length() ; ++i) s[i] = tolower(s[i]); } void ToUpper(string& s) { for (int i=0 ; i < s.length() ; ++i) s[i] = toupper(s[i]); } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// Knox_Stddef.h0000644000076500000240000000574711652363164013335 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : Knox_Stddef.h // Purpose : Set of routines and old habit data types // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(__KNOX_STDDEF_H__) #define __KNOX_STDDEF_H__ #include #include #include #include #include #include using namespace std; /////////////////////////////////////////////////////////////////////////////////////////////////// typedef vector CStringList; #define PVOID void* #define LPSTR char * #define LPCSTR const char * #define BYTE unsigned char #define WORD unsigned short #define DWORD long unsigned int #define BOOL int #define TRUE 1 #define FALSE 0 #ifndef INT_MAX #define INT_MAX 20000000 #endif #define DEBUG TRUE /////////////////////////////////////////////////////////////////////////////////////////////////// // // Function that will only print if in DEBUG mode #define TRACE if (DEBUG) printf // // Application Log: Manages a log file. Display functions will print to // multiple locations (Stdout, Application log) // File is always current (Flush after each write) // extern FILE *appLog; extern void OpenAppLog(LPCSTR filename, LPCSTR mode="a+"); extern void CloseAppLog(); extern void Display(LPSTR format, ...); extern void DisplayT(LPSTR format, ...); extern void DisplayL(LPSTR format, ...); // Helper Functions // // Read Next Line from file into buffer // extern BOOL ReadNextLine(LPSTR line, int len, FILE *f); // Trim the string, removing unwanted characters from the ends. extern void Trim(string& s, LPCSTR unwanted); extern void TrimLeft(string& s, LPCSTR unwanted); extern void TrimRight(string& s, LPCSTR unwanted); // convert the string to all same case extern void ToLower(string& s); extern void ToUpper(string& s); /////////////////////////////////////////////////////////////////////////////////////////////////// #endif PNode.cpp0000644000076500000240000006057711652363225012465 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : PNode.cpp // Purpose : Phylogenetic Tree Node // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #include "PNode.h" #include "Attrs.h" #include #include #include /////////////////////////////////////////////////////////////////////////////////////////////////// // // Class variables // int CPTree::PRECISION = 5; // number of decimal points to use when printing /////////////////////////////////////////////////////////////////////////////////////////////////// string& MakeCSVQuoted(string &q_str, LPCSTR others=NULL); string& MakeQuoted(string &q_str, LPCSTR others=NULL); /////////////////////////////////////////////////////////////////////////////////////////////////// CPTree :: CPTree() { root = NULL; internal = 0; nodeList.clear(); Progress = NULL; totalProcess = 0; nProcess = 0; bufFile = NULL; } CPTree :: ~CPTree() { CPNodeListIter iter = nodeList.begin(); while (iter != nodeList.end()) { if ((*iter) != NULL) { (*iter)->tree = NULL; delete (*iter); } ++iter; } nodeList.clear(); root = 0; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CPTree :: SetProgressFunction(ProgressFunction callBack) { Progress = callBack; return TRUE; } BOOL CPTree :: ClearProgressFunction() { Progress = NULL; return TRUE; } BOOL CPTree :: ShowProgress(LPCSTR msg, int n, int total, PVOID data) { if (Progress != NULL) return (*Progress)(msg, n, total, data); printf("Progress: (%d of %d) %s\n", n, total, msg); return TRUE; } void CPTree::ShowError(int codeline, LPCSTR msg) { printf("ERROR [CodeLine:%d] %s [Input line:%d, col: %d]\n", codeline, msg, lineCount, colCount); } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CPTree :: WriteNewickTree(LPCSTR filename, CPNode *base, BOOL withComment) { if (filename == NULL) return FALSE; if (base == NULL) return FALSE; FILE *f = fopen(filename, "wb+"); if (f == NULL) return FALSE; base->WriteNode(f, 0, FALSE, withComment); fprintf(f, ";\n"); fclose(f); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL IsAllDigits(LPCSTR s) { while ((*s != 0) && isdigit(*s)) ++s; return (*s == 0); } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPTree :: GetQuotedString(LPCSTR &str, string &v) { // search for ending quote char quote = *str; v += *str; // add beginning quote // read until next matching quote do { ++str; ++nProcess; v += *str; if ((*str) == '\\') { ++str; v += *str; } if ( ((*str) == '\'') && (str[1] == '\'')) { ++str; ++nProcess; v += *str; // skip 2nd quote ++str; ++nProcess; if ((*str) != '\'') { // get the next char after it v += *str; } } } while ( ((*str) != quote) && (*str != 0) ); if (*str == quote) { ++str; // skip ending quote ++nProcess; } } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPTree :: ReadComment(LPCSTR &v, string &comment) { // skip blanks while (*v == ' ') { ++v; ++nProcess; } if (*v == '[') { ++v; // skip opening ++nProcess; while ((*v != 0) && (*v != ']')) { if (*v == '\"') GetQuotedString(v, comment); else { comment += *v; ++v; ++nProcess; } } if (*v != 0) { ++v; // skip ending ++nProcess; } } } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPTree :: ReadToken(LPCSTR &str, string &v) { LPCSTR delim = " ,:[]()"; while ((*str != 0) && (strchr(delim, *str) == NULL) ) { if ((*str == '\'') || (*str == '\"')) { GetQuotedString(str, v); } else { v += *str; ++str; ++nProcess; } } } /////////////////////////////////////////////////////////////////////////////////////////////////// string& CPTree :: QuoteString(string& comment, char quote) { /// comment.Replace("\'", "\'\'"); /// comment.Replace("\"", "\\\""); if (!comment.empty()) { comment.insert(comment.begin(), quote); comment += quote; } return comment; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPTree::Parse(LPCSTR str) { BOOL done = FALSE; // strip initial arb comment while (!done && (*str != 0)) { switch (*str) { default: done = TRUE; case ' ': { ++str; } break; case '[': { while ((*str != ']') && (str != 0)) ++str; } break; } } totalProcess = strlen(str); nProcess = 0; endParseStr = str + totalProcess; root = ParseTree(str); if ((nProcess < totalProcess) && (*str == ',')) // more to process { CPNode *child = root; root = new CPNode(this); int prev_processed = 0; while ((nProcess < totalProcess) && (child != NULL)) { if (*str == ',') ++str; root->AddEdge(child); //DisplayL("Processed %d chars of %d, [%-100.100s]\n", nProcess, totalProcess, str); prev_processed = nProcess; child = ParseTree(str); if (nProcess == prev_processed) { DisplayL("Could not process all the chars in NEWICK file\n"); break; } } } DisplayL("Processed %d chars of %d\n", nProcess, totalProcess); } /////////////////////////////////////////////////////////////////////////////////////////////////// CPNode* CPTree::ParseTree(LPCSTR &str) { while (*str != 0) { //TRACE("[%d] [%s]\n", __LINE__, str); nProcess = totalProcess - (endParseStr - str); // chars processed is total chars - chars left to process switch (*str) { default: { // read next token string v; v.clear(); while ((*str != 0) && (*str != ',') && (*str != ')') && (*str != ';')) { if ((*str == '\'') || (*str == '\"')) { GetQuotedString(str, v); } else { v += *str; ++str; // ++nProcess; } } // TRACE("[%d] Create new node [%08X][%s]\n", __LINE__, this, v.c_str()); return new CPNode(this, v.c_str()); } case ' ': ++str; // ++nProcess; break; case ':': { // TRACE("[%d] [:]\n", __LINE__); // find attrribute data upto ',' or ')' string v; v.clear(); while ((*str != 0) && (*str != ',') && (*str != ')') && (*str != ';')) { if ((*str == '\'') || (*str == '\"')) GetQuotedString(str, v); else { v += *str; ++str; // ++nProcess; } } } break; case ';': { // end of the data // TRACE("[%d] [;]\n", __LINE__); nProcess = totalProcess; str = endParseStr; } break; case '[': { // TRACE("[%d] [\\[]\n", __LINE__); string comment; ReadComment(str, comment); if (comment[0] == '{') { //add attrs to tree ProcessAttrList(comment.c_str(), NULL); } else { // strip quotes around whole comment if ((comment[0] == '\"') && (comment[comment.length()-1] == '\"')) comment = comment.substr(1,comment.length()-2); SetAttr(ATTR_COMMENT, comment.c_str()); } } break; case '(': { // TRACE("[%d] [%s]\n", __LINE__, str); BOOL complete = FALSE; CPNode *R = new CPNode(this); ++str; // ++nProcess; while (!complete) { CPNode *S = ParseTree(str); R->AddEdge(S); if ((*str == ')') || (*str == 0)) complete = TRUE; ++str; // ++nProcess; } // find attrribute data upto ',' or ')' string v; v.clear(); while ((*str != 0) && (*str != ',') && (*str != ')') && (*str != ';')) { if ((*str == '\'') || (*str == '\"')) GetQuotedString(str, v); else { v += *str; ++str; // ++nProcess; } } // TRACE("[%d] ATTRS[%s]\n", __LINE__, v.c_str()); R->AddAttrs(v.c_str()); return R; } case ')': { // This is for the root // TRACE("[%d] Close[%s]\n", __LINE__, str); ++str; // find attrribute data upto ',' or ')' string v; v.clear(); while ((*str != 0) && (*str != ',') && (*str != ')') && (*str != ';')) { if ((*str == '\'') || (*str == '\"')) GetQuotedString(str, v); else { v += *str; ++str; // ++nProcess; } } // TRACE("[%d] CLOSE ATTRS[%s]\n", __LINE__, v.c_str()); root->AddAttrs(v.c_str()); } } } return NULL; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPTree :: SetAttr(LPCSTR k, LPCSTR v) { attrs.m[k] = v; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPTree :: ProcessAttrList(LPCSTR str, CPNode *node) { int pos; while (*str != '\0') { switch (*str) { case '{': { // add new attribute pos = strcspn(++str, "=}"); // ++nProcess; string key(str, pos); str += pos; // skip to next char // nProcess += pos; pos = strcspn(++str, "}"); // ++nProcess; string value(str, pos); str += pos; // skip to next char // nProcess += pos; ++str; // skip closing brace // ++nProcess; //TRACE("[%s] %s = %s\n", title, key, value); if (node == NULL) SetAttr(key.c_str(), value.c_str()); else node->SetAttr(key.c_str(), value.c_str()); } break; default: ++str; // ++nProcess; break; } } } ////////////////////////////////////////////////////////////////////// CPNode* CPTree :: Find(LPCSTR v) { CPNodeListIter iter = nodeList.begin(); while (iter != nodeList.end()) { //CPNode *n = *iter; if ((*iter)->title.compare(v) == 0) return *iter; ++iter; } return NULL; } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// CPNode :: CPNode(CPTree *ptree, LPCSTR v) { char str[2048]; tree = ptree; if (tree->internal%100 == 0) { string partial = v; partial = partial.substr(0, 100); /// char msg[2048]; /// sprintf(msg,"Adding node %d {%s}\n", tree->internal, partial); /// tree->ShowProgress(msg, tree->nProcess, tree->totalProcess, NULL); } if ((v == NULL) || (strlen(v) == 0)) { id = ++(tree->internal); sprintf(str, "%s_%04d", "I", id); title = str; } else { id = ++(tree->internal); // copy upto the ':' or '[' string name; name.clear(); while ((*v != 0) && (*v != ':') && (*v != '[')) { if ((*v == '\'') || (*v == '\"')) tree->GetQuotedString(v, name); else { name += *v; ++v; } } AddAttrs(v); if (!name.empty() && (name[0] == '\'')) { // this is from ARB. Strip the quotes, use chars upto first ',' as name string realName; string comment; int first = name.find_first_not_of("\' "); int last = name.find_last_not_of("\' "); name = name.substr(first, last-first+1); int n = name.find(","); realName = name.substr(0,n); comment = name.substr(n+1); name = realName; if (!comment.empty()) { // strip quotes around whole comment if ((comment[0] == '\"') && (comment[comment.length()-1] == '\"')) comment = comment.substr(1,comment.length()-2); attrs.Add(ATTR_COMMENT, comment); } } int first = name.find_first_not_of(" "); int last = name.find_last_not_of(" "); name = name.substr(first, last-first+1); attrs.Add(ATTR_NAME, name); if (name.empty()) { sprintf(str, "%s_%04d", "I", ++(tree->internal)); title = str; } else title = name; } parent = NULL; tree->nodeList.push_back(this); } CPNode :: ~CPNode() { // find position in tree's node list and remove it if (tree != NULL) { CPNodeList::iterator iter = tree->nodeList.begin(); while ((iter != tree->nodeList.end()) && (*iter != this)) ++iter; if (iter != tree->nodeList.end()) tree->nodeList.erase(iter); } id = -1; parent = NULL; attrs.Clear(); edges.clear(); title = "DELETED"; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPNode :: AddEdge(CPNode *other) { edges.push_back(other); other->parent = this; // TRACE("Edge from [%s] to [%s]\n", title, other->title); } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPNode :: InvertEdges(BOOL recurse) { // invert the edge list CPNodeList orig; orig.insert(orig.begin(), edges.begin(), edges.end()); edges.clear(); for (CPNodeListIter iter=orig.end() ; iter != orig.begin() ; --iter) edges.push_back(*iter); if (recurse) { for (CPNodeListIter iter=edges.begin() ; iter != edges.end() ; ++iter) (*iter)->InvertEdges(TRUE); } } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPNode :: ResetParent(CPNode *p) { // traverse the tree setting parent to correct items // used by tree inversion parent = p; for (CPNodeListIter iter=edges.begin() ; iter != edges.end() ; ++iter) (*iter)->ResetParent(this); } /////////////////////////////////////////////////////////////////////////////////////////////////// string& CPNode :: CleanString(string& s, BOOL searchForBootstrap) { if (s.empty()) return s; // strip quotes, convert escaped chars int pos; do { pos = s.find("\\\""); if (pos != -1) s.replace(pos, 2, "\""); // backslash double quote to double quote } while (pos >= 0); do { pos = s.find("\\\\"); if (pos != -1) s.replace(pos, 2, "\\"); // double backslash to single backslash } while (pos >= 0); do { pos = s.find("\'\'"); if (pos != -1) s.replace(pos, 2, ""); // two single quotes to nothing } while (pos >= 0); do { pos = s.find("\\\'"); if (pos != -1) s.replace(pos, 2, ""); // backslash single quote to nothing } while (pos >= 0); // Remove beginning and ending double quotes if (s[0] == '\"') s = s.substr(1); if (s[s.length()-1] == '\"') s = s.substr(0, s.length()-1); // Remove beginning and ending single quotes if (s[0] == '\'') s = s.substr(1); if (s[s.length()-1] == '\'') s = s.substr(0, s.length()-1); if (searchForBootstrap) { int pos = s.find_first_not_of("0123456789:", 0); string boot = s.substr(0,pos); int n = boot.find(":"); if (s.length() == boot.length()) n = s.length(); // only digits, no colon if (n > 1) { // bootstrap data on leading edge boot = boot.substr(0,n); attrs.Add(ATTR_BOOTSTRAP_DATA, boot); if (s.length() == n) s.clear(); else s = s.substr(n+1); } } return s; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPNode :: SetAttr(LPCSTR k, LPCSTR v) { attrs.Add(k,v); } void CPNode :: SetAttr(LPCSTR k, string& v) { attrs.Add(k,v); } /////////////////////////////////////////////////////////////////////////////////////////////////// void CPNode :: AddAttrs(LPCSTR v) { while (*v != 0) { if (*v == ':') { ++v; // consume the ':' int i = strcspn(v, "["); string dist(v, i); v += i; Trim(dist, " \n\r\t"); attrs.Add(ATTR_DISTANCE, dist); } else if (*v == '[') { ++v; // skip '[' int i = strcspn(v, "]"); string comment(v,i); v += i; if (*v == ']') ++v; if (comment.length() > 0) { // strip quotes around whole comment if ((comment[0] == '\"') && (comment[comment.length()-1] == '\"')) comment = comment.substr(1,comment.length()-2); if ((comment[0] == '{') && (comment[comment.length()-1] == '}')) tree->ProcessAttrList(comment.c_str(), this); else if (IsBranchNode()) { attrs.Add(ATTR_TAXLABEL, CleanString(comment, TRUE)); } else attrs.Add(ATTR_COMMENT, CleanString(comment)); } } else if ((*v == '\'') || (*v == '\"')) { string comment; tree->GetQuotedString(v, comment); // strip quotes around whole comment if ((comment[0] == '\"') && (comment[comment.length()-1] == '\"')) comment = comment.substr(1,comment.length()-2); if (comment.length() > 0) { // strip quotes around whole comment if ((comment[0] == '\"') && (comment[comment.length()-1] == '\"')) comment = comment.substr(1,comment.length()-2); if ((comment[0] == '{') && (comment[comment.length()-1] == '}')) tree->ProcessAttrList(comment.c_str(), this); else if (IsBranchNode()) attrs.Add(ATTR_TAXLABEL, CleanString(comment, TRUE)); else attrs.Add(ATTR_COMMENT, CleanString(comment)); } } else if (IsBranchNode()) { // read title of this item while (isspace(*v)) ++v; // skip white space int i = strcspn(v, "[;:),\'\""); string iname(v, i); v += i; if ((iname.length() > 1) && (iname[0] == 'I') && (iname[1] == '_')) title = iname; else if (iname.length() > 0) attrs.Add(ATTR_TAXLABEL, CleanString(iname, TRUE)); } else ++v; // consume the chars up to [: } } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CPNode :: WriteAttrs(FILE *f) { // for each attr // add key,value to file // for each edge // edge->ReadAttrs(filename); fprintf(f, "[%s]\n", title.c_str()); CAttrDictIter iter; for (iter=attrs.m.begin() ; iter != attrs.m.end() ; ++iter) { if (((*iter).first.length() > 2) && ((*iter).first[0] == '-') && ((*iter).first[1] == '-')) continue; if ((*iter).second.length() > 0) fprintf(f, "%s=\"%s\"\n", (*iter).first.c_str(), (*iter).second.c_str()); } for (CPNodeListIter iter=edges.begin() ; iter != edges.end() ; ++iter) (*iter)->WriteAttrs(f); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CPNode :: WriteNode(FILE *f, int indent, BOOL includeAttrs, BOOL withComment) { char str[2048]; if (f == NULL) return FALSE; if (IsBranchNode()) { fprintf(f, "("); indent += 1; fprintf(f, "\n%*s", indent, ""); for (CPNodeListIter iter=edges.begin() ; iter != edges.end() ; ++iter) { if (iter != edges.begin()) { fprintf(f, ","); fprintf(f, "\n%*s", indent, ""); } (*iter)->WriteNode(f, indent, includeAttrs, withComment); } indent -= 1; fprintf(f, "\n%*s", indent, ""); fprintf(f, ")"); } string name = attrs.GetString(ATTR_NAME,""); if (includeAttrs) { string boot = attrs.GetString(ATTR_BOOTSTRAP_DATA); if (IsBranchNode()) { name = attrs.GetString(ATTR_TAXLABEL); if (!boot.empty()) { // prepend the boot to the name, place in quotes if (name.empty()) name = boot; else { sprintf(str, "\'%s:%s\'", boot.c_str(), name.c_str()); name = str; } } fprintf(f, "%s", name.c_str()); } else { fprintf(f, "%s", name.c_str()); if (!boot.empty()) fprintf(f, "[%s]", boot.c_str()); } string comment; GetComment(ATTR_COMMENT, comment); tree->QuoteString(comment); if (!comment.empty()) fprintf(f, " [%s]", comment.c_str()); string key; string value; string attrStr; CAttrDictIter iter; for (iter=attrs.m.begin() ; iter != attrs.m.end() ; ++iter) { key = (*iter).first; value = (*iter).second; if ((key.length() > 2) && (key[0] == '-') && (key[1] == '-')) continue; //ignore attributes printed elsewhere if (key.compare(ATTR_NAME) == 0) continue; if (key.compare(ATTR_DISTANCE) == 0) continue; if (key.compare(ATTR_TAXLABEL) == 0) continue; if (key.compare(ATTR_COMMENT) == 0) continue; if (key.compare(ATTR_BOOTSTRAP_DATA) == 0) continue; if (attrStr.empty()) attrStr += '['; sprintf(str, "{%s=%s}", key.c_str(), value.c_str()); attrStr += str; } if (!attrStr.empty()) { attrStr += ']'; } } else if (withComment) { string comment; GetComment(ATTR_COMMENT, comment); if (!comment.empty()) { name += ", "; name += comment; tree->QuoteString(name, '\''); } fprintf(f, "%s", name.c_str()); } else fprintf(f, "%s", name.c_str()); double dist = attrs.GetDouble(ATTR_DISTANCE, 0); fprintf(f, ":%.*f", CPTree::PRECISION, dist); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CPNode :: GetComment(LPCSTR attr, string &str, LPCSTR _default) { str = attrs.GetString(attr, _default); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CPNode :: GetAncestors(CPNodeList &list, BOOL fromBottom) { // return the names of the ancestors list.clear(); int n = 0; CPNode *p = parent; while (p != NULL) { if (fromBottom) list.push_back(p); else list.insert(list.begin(), p); p = p->parent; ++n; } return n; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CPNode :: GetDecendants(CPNodeList &list, BOOL leafOnly) { // return the names of the decendants // for each edge // add edge name // add all decendants of edge for (CPNodeListIter iter=edges.begin() ; iter != edges.end() ; ++iter) { CPNode *node = (*iter); if (node->IsBranchNode()) { if (!leafOnly) list.push_back(node); node->GetDecendants(list, leafOnly); } else list.push_back(node); } return list.size(); } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// string& MakeCSVQuoted(string &q_str, LPCSTR others) { // Escape the following chars // " double quote string local = q_str; LPCSTR s = local.data(); q_str = "\""; while (*s != 0) { if (*s == '\"') q_str += "\"\""; else { // if (others && (strchr(others, *s) != NULL)) // q_str += "\\"; // escape the char q_str += *s; } ++s; } q_str += "\""; return q_str; } /////////////////////////////////////////////////////////////////////////////////////////////////// string& MakeQuoted(string &q_str, LPCSTR others) { // Escape the following chars // / backslash // " double quote // < open // > close string local = q_str; LPCSTR s = local.data(); q_str = "\""; while (*s != 0) { if (*s == '\\') q_str += "\\\\"; else if (*s == '\"') q_str += "\\\""; else if (*s == '<') q_str += "\\<"; else if (*s == '>') q_str += "\\>"; else { if (others && (strchr(others, *s) != NULL)) q_str += "\\"; // escape the char q_str += *s; } ++s; } q_str += "\""; return q_str; } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// PNode.h0000644000076500000240000001357011652363057012124 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : PNode.h // Purpose : Phylogenetic Tree Node // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(__PNODE_H__) #define __PNODE_H__ #include "Knox_Stddef.h" #include "AttrList.h" #include "ParsimonySet.h" #include #include #include using namespace std; extern LPCSTR globalAttrs[]; extern LPCSTR treeAttrs[]; extern LPCSTR branchAttrs[]; extern LPCSTR branchAttrs2[]; extern LPCSTR applyAttrs[]; /////////////////////////////////////////////////////////////////////////////////////////////////// extern BOOL ValidRegEx(LPCSTR expr); extern BOOL MatchRegEx(LPCSTR expr, LPCSTR text); /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// class CPNode; class CPTree; typedef vector CPNodeList; typedef vector::iterator CPNodeListIter; class CPNode { public: string title; // name of the node int id; // internal id CPTree *tree; // tree the node belongs to CPNode *parent; // parent node of this node CPNodeList edges; // children CAttrList attrs; // list of attributes assigned to this node public: CPNode(CPTree *ptree, LPCSTR v=""); ~CPNode(); void AddEdge(CPNode *other); CPNode* FindEdgeNode(int e); void InvertEdges(BOOL recurse=FALSE); // invert the edge list inline BOOL IsBranchNode() {return (edges.size() > 0); } BOOL GetComment(LPCSTR attr, string& str, LPCSTR _default=NULL); void SetAttr(LPCSTR k, string& v); void SetAttr(LPCSTR k, LPCSTR v); void AddAttrs(LPCSTR v); BOOL ReadAttrs(LPCSTR filename); BOOL WriteAttrs(FILE *f); BOOL Display(LPCSTR key); BOOL WriteNode(FILE *f, int indent=0, BOOL includeAttrs=FALSE, BOOL withComment=FALSE); string& CleanString(string& s, BOOL searchForBootstrap=FALSE); void ResetParent(CPNode *p); // traverse the tree setting parent to correct items // used by tree inversion int GetAncestors(CPNodeList &list, BOOL fromBottom=TRUE); // return the ancestors in an ordered list // fromBottom - if TRUE, inserts each parent at end of list int GetDecendants(CPNodeList &list, BOOL leafOnly=TRUE); // return the nodes the decendants // leafOnly - if TRUE, only add the leaf id's to list }; /////////////////////////////////////////////////////////////////////////////// typedef BOOL (* ProgressFunction)(LPCSTR msg, int curInProcess, int totalToProcess, PVOID data); class CPTree { public: string filename; // file tree read from or wriiten to CPNode *root; // root node of the tree CAttrList attrs; // list of attributes for tree int internal; // internal id number for last created node CPNodeList nodeList; // list of nodes in the tree /// map nameTable; // lookup table for node names // // Variables for parsing // LPCSTR buffer; // points to current location in the buffer to get chars FILE *bufFile; // file to read from int lineCount; // current position in lines of the file int colCount; // Current column within the line char errorReason[2048]; // Status reporting ProgressFunction Progress; int totalProcess; int nProcess; LPCSTR endParseStr; // str position when parsing complete // // Class variables // static int PRECISION; // number of decimal points to use when printing public: CPTree(); ~CPTree(); void ShowError(int codeline, LPCSTR msg); BOOL WriteNewickTree(LPCSTR filename, CPNode *base, BOOL withComment=FALSE); CPNode * Decode(LPCSTR &str); // Decode encoded node description void Parse(LPCSTR str); CPNode* ParseTree(LPCSTR &str); void ReadComment(LPCSTR &v, string &s); static string& QuoteString(string& comment, char quote='\"'); void GetQuotedString(LPCSTR &str, string &v); void ReadToken(LPCSTR &str, string &v); BOOL ReadTreeAttrs(); BOOL ReadNodeAttrs(); BOOL WriteAttrs(); void SetAttr(LPCSTR k, LPCSTR v); BOOL RemoveAttribute(LPCSTR attr, BOOL all); // Remove the given attribute. // all - if TRUE, remove from all nodes, // otherwise from only from global TREE attrs void ProcessAttrList(LPCSTR str, CPNode *node); CPNode* Find(LPCSTR v); CPNode* FindCommonAncestor(CPNode *n1, CPNode *n2); // returns the nearest common ancestor to given nodes // Progress Functions Access BOOL SetProgressFunction(ProgressFunction callBack); BOOL ClearProgressFunction(); BOOL ShowProgress(LPCSTR msg, int n, int total, PVOID data); }; #endif ParsInsert.cpp0000644000076500000240000030320611652363704013541 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : ParsInsert.cpp // Purpose : Parsimonious Insertion of unclassified seqeunces into Phylogenetic Tree // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// // // Sample command for parsimonious insertion: // -x rdp.taxonomy -t core_set.tree -s core_set_aligned.fasta unclassified_seq.fasta // // /////////////////////////////////////////////////////////////////////////////////////////////////// #include "Knox_Stddef.h" #include "ParsInsert.h" #include "PNode.h" #include "SeqList.h" #include "Taxonomy.h" #include "Attrs.h" #include #include #include #include #include #include #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////////////////////////////// #define APPNAME "ParsInsert" #define VERSION APPNAME " Version 1.04 " __DATE__ " " __TIME__ #define COPYRIGHT \ "ParsInsert: Parsimonious Insertion of unclassified sequences into phylogenetic tree\n"\ " Copyright (C) 2007-2011 David Knox\n"\ " This program comes with ABSOLUTELY NO WARRANTY\n"\ " This is free software, and you are welcome to redistribute under certain conditions - see license." #define USAGE "Application:%s\n\n%s [options] \n" \ " Parsimonious Insertion of Sequences into Given Tree \n\n" \ " -m - read mask from this file \n" \ " -s - read core tree sequences from this file \n" \ " (default: PI_Tree.fasta) \n" \ " -t - read core tree from this file \n" \ " (default: PI_Tree.tree) \n" \ " -x - read core tree taxomony from this file \n" \ " -o - output taxonomy for each insert sequence to this file\n" \ " (default: PI_Results.log) \n" \ " -l[-|] - create log file (default is ParsInsert.log)\n" \ " -n# - number of best matches to display \n" \ " -c# - percent threshold cutoff \n" \ " -p - print node comments in newick file \n" \ " -D# - print branch lengths using # decimal places\n" \ "\n" // " -p - read parsimony values from this file \n" /////////////////////////////////////////////////////////////////////////////////////////////////// FILE *newseqs = NULL; // sequence file of unclassified insertions BOOL createLog = TRUE; int fast = 0; int nCalcCost = 0; // counters for cost calc stats int nCalcCostFull = 0; // counters for cost calc stats BOOL useCalcCost = 4; // calculation method to be used char *statsName = "PI_Results.log"; char *logFilename = "ParsInsert.log"; char *treeFilename = "PI_Tree.tree"; char *seqFilename = "PI_Tree.fasta"; char *fullTreeName = NULL; char *files[64] = {64*0}; int nfiles = 0; BOOL precision = FALSE; int scoreThresh = 80; // default to 80% or better to add item /////////////////////////////////////////////////////////////////////////////////////////////////// FILE *stats = NULL; time_t start = 0; long long allocatedMemory = 0; CSequenceFile *treeSeqfile = NULL; CSequenceFile *insertSeqfile = NULL; CPTree *fullTree = NULL; // Variables used during the parsimony calculation // volatile int nSeqRemaining = 0; // used to show progress during parsimony calculation CParsimonyList parsimonyList; // parsimonious sequence for common ancestors CParsimonyList unionList; // union of all possible nucleotides at each position CSequenceFile *taxonomy = NULL; CPTree *tree = NULL; char *taxName = NULL; char *maskName = NULL; char *parsName = NULL; map coreNames; CInsertPosArray inserts; char mask[MAX_SEQ_SIZE]; bool useMask = FALSE; int testing = 1; BOOL fitch = TRUE; BOOL jukes_cantor = TRUE; BOOL withComments = FALSE; /////////////////////////////////////////////////////////////////////////////////////////////////// enum {RANK_DOMAIN, RANK_PHYLUM, RANK_CLASS, RANK_ORDER, RANK_FAMILY, RANK_GENUS, RANK_SPECIES, RANK_N}; int rankCounts[RANK_N][4]; LPCSTR rankNames[] = { "Domain", "Phylum", "Class", "Order", "Family", "Genus", "Species", NULL}; class CRankCounts { public: int rankCounts[RANK_N][4]; }; typedef map CMapRankCounts; CMapRankCounts phylumRankCounts; /////////////////////////////////////////////////////////////////////////////////////////////////// typedef vector CTreeInsertList; typedef map CTreeInserts; /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceFile* ReadSequenceFile(LPCSTR filename); CSequenceFile* ReadTaxonomyFile(LPCSTR filename); LPCSTR GetTaxonomy(LPCSTR name, CPNode *node=NULL); CPTree* ReadNewickTree(LPCSTR filename); int LoadParsimonyIndex(); // loads a parsimony index int LoadSequenceIndex(); // loads a sequence index int BuildSequenceIndex(); // build seq index from sequence file BOOL RemoveUnwantedNodes(CPNode *node, CSequenceFile *seqfile); BOOL SetInternalTaxonomy(CPTree *tree); BOOL SetMyTaxonomy(CPNode *node); BOOL CheckLeafTaxonomy(CPTree *tree); int CheckTreeSequences(CPTree *tree, CSequenceFile *treeSeqfile); int ParsimonyInsertion(); int CreateParsimonySets(LPCSTR parsName, CPTree *tree); int CalcAncestorParsimony(CPTree *tree); // Build parsimony values (write to file) int CalcNodeParsimony(CPNode *node); int ForceNodeParsimony(CPNode *node); int WriteParsimonySet(CPNode *node, CSequenceFile *parsimony); void FindInsertLocations(CSequenceFile *insertSeqfile); void FindInsertLocations(CSequenceFile *treeSeqfile, CPTree *tree, CSequenceFile *insertSeqfile, LPCSTR seqname); void FindInsertLocations(CSequenceFile *treeSeqfile, CPTree *tree, CSequenceFile *insertSeqfile, CInsertPosArray &inserts); void FindInsertLocations_Serial(CSequenceFile *treeSeqfile, CPTree *tree, CSequenceFile *insertSeqfile, CInsertPosArray &inserts); int CalcCost(CParsimonySet &next_pars, CParsimonySet &node_pars, int &diffs, int &partials, int &indel, int thresh=INT_MAX); int CalcCost_NEW4(CParsimonySet &next_pars, CParsimonySet &node_pars, int &diffs, int &partials, int &indel, int thresh=INT_MAX); int CalcCost_ORIG(CParsimonySet &next_pars, CParsimonySet &node_pars, int &diffs, int &partials, int &indel, int thresh=INT_MAX); void BuildScoreMatrix(); void DisplayInsertLocations(CInsertPosArray &inserts, BOOL all); void DisplayBestInsertLocations(CInsertPos *item, BOOL all); void OutputInsertLocations(CInsertPosArray &inserts, BOOL all); void DisplayRankCounts(LPCSTR header, int counts[][4]); void ReleaseInserts(CInsertPosArray &inserts); CParsimonySet* GetParsimonySet(CPNode *node, BOOL create=FALSE); int GetTaxonomyMatch(string &taxA, string &taxB, string &marker, int counts[][4]); void GetRankFromTax(int rank, string &tax, string &rankStr, BOOL only=TRUE); CTreeInserts* BuildTreeInsertLists(CInsertPosArray &inserts); BOOL BuildInsertTree(CTreeInserts* insertLists, CPTree *tree); CPNode* AddChild(CPTree *tree, CPNode *node, CInsertPos *in); double CalcDist(CPNode *parent, CInsertPos* in, int &diffs, int &parts, int &indel); BOOL BuildInsertTree(CInsertPosArray &inserts, CPTree *tree); BOOL AddTaxonomyToTree(CPTree *tree, CSequenceFile *taxonomy); BOOL ReadMask(LPCSTR filename); void CompareTaxonomy(LPCSTR tax1, LPCSTR tax2); void TestInsertPositions(); BOOL FullTree_Initialization(); double ComparePosition(LPCSTR name, CPNode *parent, CPTree *fullTree, CPTree *coreTree); /////////////////////////////////////////////////////////////////////////////////////////////////// inline LPCSTR GetNodeName(CPNode *node) { string name = node->attrs.GetString(ATTR_NAME,""); if (name.empty()) name = node->title; return name.c_str(); } /////////////////////////////////////////////////////////////////////////////////////////////////// // The one and only application object int main(int argc, char* argv[]) { int nRetCode = 0; memset(rankCounts, 0, sizeof(rankCounts)); DisplayL("%s\n", COPYRIGHT); int i = 1; while (i < argc) { if (argv[i][0] == '-') { // Process argument switch (argv[i][1]) { case 'c': // cutoff threshold percent { int v; if (argv[i][2] != 0) v = atoi(&argv[i][2]); else if (i < argc) v = atoi(argv[++i]); scoreThresh = v; } break; case 'd': // distance calc method { int v; if (argv[i][2] != 0) v = atoi(&argv[i][2]); else if (i < argc) v = atoi(argv[++i]); useCalcCost = v; } break; case 'D': // distance calc method { int v; if (argv[i][2] != 0) v = atoi(&argv[i][2]); else if (i < argc) v = atoi(argv[++i]); if (v >= 0) { DisplayL("Setting Tree Floating Point Precision to %d\n", v); CPTree::PRECISION = v; } } break; case 'f': { int v = atoi(&argv[i][2]); fast = v; } break; case 'F': { fitch = (argv[i][2] != '-'); } break; case 'j': { jukes_cantor = (argv[i][2] != '-'); } break; case 'l': createLog = (argv[i][2] != '-'); if (argv[i][2] != 0) logFilename = &argv[i][2]; else if ((i < argc) && (argv[i][2] != '-')) logFilename = argv[++i]; break; case 'n': // number of matches to display { int v = atoi(&argv[i][2]); if (v > 0) CBestLocation::default_len = v; } break; case 'm': // mask input file { if (argv[i][2] != 0) maskName = &argv[i][2]; else if (i < argc) maskName = argv[++i]; } break; case 'o': // output file { if (argv[i][2] != 0) statsName = &argv[i][2]; else if (i < argc) statsName = argv[++i]; } break; case 'p': { withComments = (argv[i][2] != '-'); } break; case 'P': { precision = (argv[i][2] != '-'); } break; case 's': // tree sequence file { if (argv[i][2] != 0) seqFilename = &argv[i][2]; else if (i < argc) seqFilename = argv[++i]; } break; case 't': // tree file { if (argv[i][2] != 0) treeFilename = &argv[i][2]; else if (i < argc) treeFilename = argv[++i]; } break; case 'x': // taxonomy input file { if (argv[i][2] != 0) taxName = &argv[i][2]; else if (i < argc) taxName = argv[++i]; } break; default: DisplayL("invalid command option '%c'\n", argv[i][1]); nRetCode = RC_ERROR_OPTIONS; break; } } else { files[nfiles++] = argv[i]; } i++; } if (createLog) OpenAppLog(logFilename, "a+"); // Write out our version and the command line string cmd; for (int k=0 ; k < argc ; ++k) { if (!cmd.empty()) cmd += " "; cmd += argv[k]; } DisplayL("%s\nCommand Line:[%s]\n", VERSION, cmd.c_str()); if (nfiles < 1) { DisplayL("ERROR - missing files to process\n"); DisplayT(USAGE, VERSION, APPNAME); nRetCode = RC_ERROR_CMDLINE; } start = time(NULL); if (treeFilename != NULL) { DisplayL(" tree file: %s\n", treeFilename); } if (seqFilename != NULL) { DisplayL(" tree sequence file: %s\n", seqFilename); } if (maskName != NULL) { DisplayL(" mask file: %s\n", maskName); if (!ReadMask(maskName)) { DisplayT("Cannot open mask file [%s]", maskName); nRetCode = RC_ERROR_MASKFILE; } useMask = TRUE; } if (taxName != NULL) { DisplayL(" taxomony index file: %s\n", taxName); taxonomy = ReadTaxonomyFile(taxName); if (taxonomy->f == NULL) { DisplayT("Cannot open taxomony index FASTA file [%s]", taxName); nRetCode = RC_ERROR_TAXFILE; } else DisplayL(" taxomony index file: %d taxa\n", taxonomy->GetCount()); } BuildScoreMatrix(); if (nRetCode == 0) { nRetCode = ParsimonyInsertion(); } // release the data if (treeSeqfile != NULL) delete treeSeqfile; if (insertSeqfile != NULL) delete insertSeqfile; if (tree != NULL) delete tree; if (stats != NULL) fclose(stats); if (taxonomy != NULL) delete taxonomy; /// ReleaseInserts(inserts); DisplayL("Process Completed: %d sec\n", time(NULL)-start); CloseAppLog(); return nRetCode; } /////////////////////////////////////////////////////////////////////////////////////////////////// int ParsimonyInsertion() { int ret = 0; time_t stage; // Algorithm /* 1. If sequence index available load sequence index else create sequence index from sequence FASTA file 2. Read Tree file 3. If parsimony index available load parsimony index else if parsimony FASTA file availble create parsimony index from parsimony FASTA file else Create parsimony FASTA file and index file 4. If new sequence index available Load new sequence index else Create new sequence index from new sequence FASTA file 5. for each group of new sequences that fit into memory for each node in tree for each seq in group calc score to convert node into seq Add score,node pair to best for seq Keep top K scores for each seq in group write top scoring positions and Taxonomy */ stats = fopen(statsName, "w"); // Read Tree File DisplayL("Reading Newick Tree: [%s]\n", treeFilename); stage = time(NULL); tree = ReadNewickTree(treeFilename); if (tree == NULL) { DisplayL("Error accessing Newick Tree file [%s]\n", treeFilename); return RC_ERROR_TREEFILE; } else DisplayL("Newick Tree Read Completed: %d taxa, %d sec\n", (tree->nodeList.size()+1)/2, time(NULL)-stage); // Build list of core leaf names CPNodeList &coreNodes = tree->nodeList; for (CPNodeListIter iter=coreNodes.begin() ; iter != coreNodes.end() ; ++iter) { CPNode *node = *iter; string name = GetNodeName(node); if (!node->IsBranchNode()) { if (coreNames.find(name) != coreNames.end()) DisplayL("Found duplicate name: [%s]/n", name.c_str()); coreNames[name] = node; } } // Read Sequence File DisplayL("Tree Sequence Reading: [%s]\n", seqFilename); stage = time(NULL); treeSeqfile = ReadSequenceFile(seqFilename); ret = CheckTreeSequences(tree, treeSeqfile); if (ret != 0) return ret; DisplayL("Tree Sequence Read Completed: %d sequences, %d sec\n", treeSeqfile->seqlist.size(), time(NULL)-stage); // read sequences to be inserted DisplayL("Reading sequences for insertion: [%s]\n", files[0]); stage = time(NULL); insertSeqfile = new CSequenceFile(files[0], 0); insertSeqfile->ReadSequenceFile(1); if (insertSeqfile->GetCount() == 0) { DisplayL("No insertion sequences found\n"); return RC_ERROR_NO_INSERT_SEQ; } DisplayL("Insert Sequecne Read Completed: %d sequences, %d sec\n", insertSeqfile->GetCount(), time(NULL)-stage); /// Only calc the ones actually needed DisplayL("Checking Taxa Taxonomy\n"); CheckLeafTaxonomy(tree); DisplayL("Setting Internal Taxonomy\n"); stage = time(NULL); SetInternalTaxonomy(tree); DisplayL("Internal Taxonomy Completed: %d sec\n", time(NULL)-stage); // Set parsimony either from file or building from sequences DisplayL("Setting internal parsimony sequences ...\n"); stage = time(NULL); CreateParsimonySets(parsName, tree); DisplayL("Parsimony Calculation Completed: %d sec\n", time(NULL)-stage); if (fullTreeName != NULL) FullTree_Initialization(); DisplayL("[%d sec elapsed] Searching for insertion points:\n", time(NULL)-start); //DisplayL("[%d fast]\n", fast); if (useCalcCost == 4) { CPNodeList &nodes = tree->nodeList; for (CPNodeListIter iter=nodes.begin() ; iter != nodes.end() ; ++iter) { CPNode *node = *iter; CParsimonySet *node_pars = GetParsimonySet(node); if (node_pars->segCounts == NULL) node_pars->BuildSegCounts((useMask ? mask : NULL)); } } stage = time(NULL); switch (fast) { case 0: { FindInsertLocations_Serial(treeSeqfile, tree, insertSeqfile, inserts); } break; default: { FindInsertLocations(treeSeqfile, tree, insertSeqfile, inserts); } break; } DisplayL("[%d sec elapsed] Insert Locations Completed: %d sec\n", time(NULL)-start, time(NULL)-stage); time_t insertTime = time(NULL)-stage; /// DisplayInsertLocations(inserts, TRUE); memset(rankCounts, 0, sizeof(rankCounts)); OutputInsertLocations(inserts, FALSE); // Place inserts into tree AddTaxonomyToTree(tree, taxonomy); //tree->WriteNewickTree("AfterAddTax.tree", tree->root, TRUE); CTreeInserts *insertmap = BuildTreeInsertLists(inserts); BuildInsertTree(insertmap, tree); string treename = insertSeqfile->fname; int n = treename.find_last_of('.'); if (n > 0) treename = treename.substr(0, n) + ".tree"; DisplayL("Writing Newick tree file: [%s]\n", treename.c_str()); tree->WriteNewickTree(treename.c_str(), tree->root, withComments); DisplayRankCounts("Rank Matches:", rankCounts); if (testing > 2) DisplayL("CalcCost calls[%d] = %d / %d (%d)\n", useCalcCost, nCalcCostFull, nCalcCost,nCalcCost-nCalcCostFull); if (insertTime > 0) DisplayL("Insert Time = %d, %d per hour\n", insertTime, 3600 * inserts.size() / insertTime ); if (testing > 2) { // display the rank counts for each phylum CMapRankCounts::iterator iter; for (iter=phylumRankCounts.begin() ; iter != phylumRankCounts.end() ; ++iter) { string phy = iter->first; DisplayRankCounts(phy.c_str(), (iter->second)->rankCounts); } } return ret; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CheckTreeSequences(CPTree *tree, CSequenceFile *treeSeqfile) { // Check to see that we have a sequence for each leaf of the tree int ret = 0; if (treeSeqfile->seqlist.size() == 0) { DisplayL("Error accessing Tree Sequencefile [%s]\n", treeSeqfile->fname.c_str()); ret = RC_ERROR_TREESEQ; } CPNodeList &nodes = tree->nodeList; for (CPNodeListIter iter=nodes.begin() ; iter != nodes.end() ; ++iter) { CPNode *node = *iter; if (node == NULL) continue; if (node->IsBranchNode()) continue; // look up the sequence name in the sequence file string name = GetNodeName(node); // get sequence from the sequence file CSequenceItem *seq = treeSeqfile->GetSeq(name.c_str()); if ((seq == NULL) || (seq->len == 0)) { DisplayL("ERROR - tree member sequence is not available [%s]\n", name.c_str()); ret = RC_ERROR_TREESEQ_MISSING; } } return ret; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CreateParsimonySets(LPCSTR parsName, CPTree *tree) { // Create parsimony sets from FASTA file // if (parsName != NULL) { CSequenceFile *parsimony = NULL; DisplayL(" parsimony index file: %s\n", parsName); parsimony = ReadSequenceFile(parsName); if (parsimony->f == NULL) { DisplayT("Cannot open parsimony index FASTA file [%s]", parsName); return -10; } DisplayL(" parsimony file: %d internal nodes\n", parsimony->GetCount()); // loop creating the parsimony sets for each node (leaf and internal) parsimony->ResetSeqIterator(); CSequenceItem *seq = parsimony->GetNextSeq(); while (seq != NULL) { seq->ReadSeqData(parsimony->f); CParsimonySet *node_pars = NULL; node_pars = (CParsimonySet*)parsimonyList[seq->name]; if (node_pars == NULL) { // does not exist, create new entry // DisplayL("Create new CParsimonySet for %s\n", name.c_str()); node_pars = new CParsimonySet(); node_pars->Convert(seq->data); char str[100*1024]; node_pars->BuildSets(str,sizeof(str)); node_pars->Trace(seq->name.c_str(), str); parsimonyList[seq->name] = node_pars; } else node_pars->Convert(seq->data); seq->ReleaseSeqData(); seq = parsimony->GetNextSeq(); } if (parsimony != NULL) delete parsimony; } else { // create parsimony for tree from leaf sequences DisplayL("Calculating internal parsimony sequences ...\n"); CalcAncestorParsimony(tree); } return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceFile* ReadTaxonomyFile(LPCSTR filename) { CSequenceFile *seqfile = new CSequenceFile(); string fname = filename; if (fname.substr(fname.length()-4) == ".idx") { // read this index file seqfile->ReadSequenceIndexFile(filename); fname = fname.substr(0, fname.length()-4); seqfile->Open(fname.c_str(), "r"); } else { // read the file and create index seqfile->Open(filename); seqfile->ReadTaxonomyFile(); } return seqfile; } /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceFile* ReadSequenceFile(LPCSTR filename) { CSequenceFile *seqfile = new CSequenceFile(); string fname = filename; if (fname.substr(fname.length()-4) == ".idx") { // read this index file seqfile->ReadSequenceIndexFile(filename); fname = fname.substr(0, fname.length()-4); seqfile->Open(fname.c_str(), "r"); } else { // read the file and create index seqfile->Open(filename); seqfile->ReadSequenceFile(1); } return seqfile; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL ReadMask(LPCSTR filename) { if (filename == NULL) return FALSE; FILE *f = fopen(filename, "r"); if (f == NULL) return FALSE; memset(mask, 0, sizeof(mask)); int m = 0; char buffer[MAX_SEQ_SIZE]; while (ReadNextLine(buffer, sizeof(buffer), f)) { for (int i=0 ; (i < strlen(buffer)) && (m < sizeof(mask)) ; ++i) { switch (buffer[i]) { case '0': case '1': mask[m] = buffer[i] - '0'; break; case '.': case '-': mask[m] = 0; break; default: mask[m] = 1; break; } ++m; } } return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// CPTree* ReadNewickTree(LPCSTR filename) { TRACE("opening source file: [%s]\n", filename); FILE *f = fopen(filename, "r"); if (f == NULL) { Display("Could not open source file: [%s]\n", filename); return NULL; } static char newick[50*1024*1024]; // should get the file size for the buffer int len=0; CPTree *newickTree = new CPTree(); DisplayT("Opening file: %s\t...", filename); if (f != NULL) { char buffer[32*1024]; newickTree->filename = filename; //newickTree->ReadTreeAttrs(); // get defaults memset(newick, 0, sizeof(newick)); int maxlinelen = 0; int linecount = 0; while (ReadNextLine(buffer, sizeof(buffer), f) > 0) { if (buffer[0] == '#') continue; int blen = strlen(buffer); // strip the leading whitespace int skip; for (skip=0 ; (skip < blen) && isspace(buffer[skip]) ; ++skip) ; // skip whitespace LPCSTR buf = buffer + skip; memcpy(&newick[len], buf, blen-skip); len += blen-skip; //ASSERT(len < 50*1024*1024); maxlinelen = max(maxlinelen, blen); } if (++linecount%100 == 0) Display("Opening file: %s\tLines:%d", filename, linecount); fclose(f); } DisplayT("Parsing Newick file: %s\t...", filename); newickTree->Parse(newick); return newickTree; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CheckLeafTaxonomy(CPTree *tree) { // calc the taxonomy of the tree if (taxonomy == NULL) return FALSE; CPNodeList missing; int n = 0; CPNodeList &nodes = tree->nodeList; for (CPNodeListIter iter=nodes.begin() ; iter != nodes.end() ; ++iter) { CPNode *node = *iter; string tax; if (node == NULL) continue; if (node->IsBranchNode()) continue; // check for taxonomy CSequenceItem *seq = taxonomy->GetSequence(node->title.c_str()); if (seq != NULL) { tax = seq->hdr; Trim(tax, "\n\r\t "); // find first \t rest of line is taxonomy int pos = tax.find_first_of('\t'); if (pos >= 0) tax = tax.substr(pos+1,tax.length()); seq->ReleaseSeqData(); } if (tax.empty()) { //DisplayL("\tNO TAXONOMY for [%s]\n", node->title.c_str()); missing.push_back(node); ++n; } } if (n != 0) { DisplayL("%d of %d nodes are missing taxonomy\n\t", n, nodes.size()); int count = 0; for (CPNodeListIter iter=missing.begin() ; iter != missing.end() ; ++iter) { CPNode *node = *iter; DisplayL(" %-12.12s%s", node->title.c_str(), (++count%8 == 0 ? "\n\t" :"")); } DisplayL("\n"); } return (n == 0); } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL SetInternalTaxonomy(CPTree *tree) { // calc the taxonomy of the tree if (taxonomy == NULL) return FALSE; CTaxEntry taxEntries("Tree Taxonomy"); // keeps track of diversity seen in taxonomy of tree sequences nSeqRemaining = tree->nodeList.size()/2; CPNodeList &nodes = tree->nodeList; for (CPNodeListIter iter=nodes.begin() ; iter != nodes.end() ; ++iter) { CPNode *node = *iter; if (node == NULL) continue; if (!node->IsBranchNode()) { CSequenceItem *seq = taxonomy->GetSequence(node->title.c_str()); if (seq != NULL) { string tax = seq->hdr; Trim(tax, "\n\r\t "); // find first \t rest of line is taxonomy int pos = tax.find_first_of('\t'); if (pos >= 0) tax = tax.substr(pos+1,tax.length()); seq->ReleaseSeqData(); taxEntries.Add(tax.c_str()); // update diversity } continue; } CPNodeList descent; node->GetDecendants(descent, TRUE); map commonTax; map::iterator cIter; string common; string tax; int nDescent = 0; // DisplayL("Taxonomy for [%s]\n", node->title.c_str()); for (CPNodeListIter diter=descent.begin() ; diter != descent.end() ; ++diter) { CPNode *des = *diter; if (des == NULL) continue; tax.clear(); CSequenceItem *seq = taxonomy->GetSequence(des->title.c_str()); if (seq != NULL) { tax = seq->hdr; Trim(tax, "\n\r\t "); // find first \t rest of line is taxonomy int pos = tax.find_first_of('\t'); if (pos >= 0) tax = tax.substr(pos+1,tax.length()); seq->ReleaseSeqData(); } // add each part of the taxonomy to the common list int p; string entry; entry = tax; p = commonTax[entry]; commonTax[entry] = p+1; for (int i=0 ; i < tax.length() ; ++i) { string entry = tax; if ((tax[i] == ';') || (tax[i] == '/')) { entry = tax.substr(0, i); p = commonTax[entry]; commonTax[entry] = p+1; } } if (!tax.empty()) ++nDescent; } // find the longest, most trusted value int commonThresh = 50 * nDescent / 100; // 60% of set descendents are required to select value int commonBest = 0; // best value seen common = ""; for (cIter=commonTax.begin() ; cIter != commonTax.end() ; ++cIter) { string key = (*cIter).first; int v = (*cIter).second; if ((v >= commonThresh) && (v > commonBest*90/100) && (common.length() < key.length())) { common = key; commonBest = v; } } // DEBUGGING code for assignment of taxonomy for internal branch // DisplayL("\tAssigning: [%s]\n\n", common.c_str()); // if (common.empty()) // { // DisplayL("Taxonomy for [%s]\n", node->title.c_str()); // for (CPNodeListIter diter=descent.begin() ; diter != descent.end() ; ++diter) // { // CPNode *des = *diter; // if (des == NULL) continue; // // CSequenceItem *seq = taxonomy->GetSequence(des->title.c_str()); // if (seq != NULL) // { // tax = seq->hdr; // Trim(tax, "\n\r\t "); // // find first \t rest of line is taxonomy // int pos = tax.find_first_of('\t'); // if (pos >= 0) // tax = tax.substr(pos+1,tax.length()); // seq->ReleaseSeqData(); // } // DisplayL("\t[%s]\t[%s]\n", des->title.c_str(), tax.c_str()); // } // } node->attrs.Add(ATTR_TAXLABEL, common); // DisplayL("Setting Internal Taxonomy: %s [%s]\n", node->title.c_str(), common.c_str()); if (--nSeqRemaining%1000 == 0) DisplayT("\rSetting Internal Taxonomy %d nodes remaining ", nSeqRemaining); LPSTR data = (LPSTR)malloc(common.length()+1); strcpy(data, common.c_str()); CSequenceItem *seq = new CSequenceItem(node->title.c_str(), -1, common.length(), data); taxonomy->seqlist[seq->name] = seq; } DisplayT("\n"); taxEntries.Display(" ", 3); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// void FindInsertLocations_Serial(CSequenceFile *treeSeqfile, CPTree *tree, CSequenceFile *insertSeqfile, CInsertPosArray &inserts) { // for each node in the tree // for each seq for insertion // calc cost time_t start = time(NULL); // build insertion list insertSeqfile->ResetSeqIterator(); CSequenceItem *seq = insertSeqfile->GetNextSeq(); while (seq != NULL) { CSequenceItem *iseq = insertSeqfile->GetSequence(seq->name.c_str()); // Check to see if this leaf is in the core tree if (coreNames.find(seq->name.c_str()) != coreNames.end()) { DisplayL("**** Sequence is already in core tree: %s\n", seq->name.c_str()); seq = insertSeqfile->GetNextSeq(); // get next sequence continue; } if (iseq == NULL) { DisplayL("**** Cannot find sequence for %s\n", seq->name.c_str()); seq = insertSeqfile->GetNextSeq(); // get next sequence continue; } // check that we have the taxonomy string tax; if (taxonomy != NULL) tax = GetTaxonomy(seq->name.c_str()); CInsertPos *item = new CInsertPos(); item->seq = iseq; item->pars.Convert(iseq->GetSeqData()); for (int i=0 ; i < item->pars.len ; ++i) { if (item->pars.data[i] != 0) { if (useMask && (mask[i] != 0)) ++item->nSites; else if (!useMask) ++item->nSites; item->pars.end = i; if (item->pars.start == -1) item->pars.start = i; } } item->pars.BuildSegCounts((useMask ? mask : NULL)); if (item->nSites < 1000) TRACE("SHORT"); DisplayL("Insert [%20s](len=%d) [%5d sites] (%d - %d) [%s]\n", item->seq->name.c_str(), seq->len, item->nSites, item->pars.start, item->pars.end, tax.c_str()); inserts.push_back(item); seq = insertSeqfile->GetNextSeq(); // get next sequence } // For each node in the tree // for each seq in insertion list // score the seq to the node // keep the best scores int diffs; int parts; int indel; CPNodeList &nodes = tree->nodeList; int count = 0; DisplayL("Searching for position to insert %d sequences in tree of %d nodes. {Setup: %d sec}\n", inserts.size(), tree->nodeList.size(), time(NULL)-start+1); for (CPNodeListIter iter=nodes.begin() ; iter != nodes.end() ; ++iter) { CPNode *node = *iter; if (++count%1000 == 0) DisplayL("[%10d/%d] {%d sec} [%s]\n", count, tree->nodeList.size(), time(NULL)-start+1, node->title.c_str()); CParsimonySet *node_pars = GetParsimonySet(node); if (node_pars == NULL) continue; // check match to each of the insert seq for (int i=0 ; i < inserts.size() ; ++i) { CInsertPos *insert = inserts[i]; // if (insert->nSites < 100) continue; int thresh = insert->best.WorstScore(); int nodecost = CalcCost(insert->pars, *node_pars, diffs, parts, indel, thresh); //TRACE("[%10s] %d\n", node->title, nodecost); if (nodecost != INT_MAX) { // get taxonomy string t = GetNodeName(node); string tax = GetTaxonomy(t.c_str(), node); insert->best.Add(nodecost, node, tax.c_str()); } } } time_t finish = time(NULL); DisplayL("Insertion of %d sequences in [%d sec]\n", inserts.size(), finish-start+1); } /////////////////////////////////////////////////////////////////////////////////////////////////// // // fast insertion that only processes nodes that have a chance of getting a good score // void FindInsertLocations(CSequenceFile *treeSeqfile, CPNode *node, CSequenceItem *seq, CInsertPos *item) { int nodecost = INT_MAX; int diffs = INT_MAX; int parts; int indel; BOOL recurse = FALSE; --nSeqRemaining; CParsimonySet *node_pars = GetParsimonySet(node); if (node_pars == NULL) { DisplayL("**** Error: could not generate Parsimony Set\n"); return; } nodecost = CalcCost(item->pars, *node_pars, diffs, parts, indel, INT_MAX); //int per = (item->nSites-(diffs+indel))* 100 / item->nSites; //TRACE("[%10s] %d\n", node->title, nodecost); if (nodecost < item->best.WorstScore()) // found atleast a partial match { // add to best match list string name = GetNodeName(node); string tax = GetTaxonomy(name.c_str(), node); item->best.Add(nodecost, node, tax.c_str()); } LPCSTR items = "9"; if (node->IsBranchNode()) { char c = node->title[node->title.length()-1]; if (strchr(items, c) == NULL) recurse = TRUE; else { // DisplayL("Checking '%c'\n", c); int thresh = item->best.WorstScore(); // if (thresh < INT_MAX) // thresh = thresh * 120 / 100; thresh = min(thresh, item->nSites*fast/100); // get the max value for matching any other node in subtree CParsimonySet *union_pars = unionList[node->title]; CalcCost(item->pars, *union_pars, diffs, parts, indel, thresh); int best = diffs + indel; // DisplayL("[min(%8d,%8d) > %8d (%8d,%8d)[%s]\n", item->best.WorstScore(), item->nSites*fast/100, diffs,parts,indel, node->title.c_str()); recurse = (best <= thresh); // if (!recurse) // DisplayL("skipping descendents of [%s]\n", GetNodeName(node)); } } // Only propogate along this subtree if we can possibly obtain better scores if ((fast == 0) || recurse) { // Now try all the children of this node CPNodeList &children = node->edges; for (CPNodeListIter iter=children.begin() ; iter != children.end() ; ++iter) { CPNode *child = *iter; FindInsertLocations(treeSeqfile, child, seq, item); } } } /////////////////////////////////////////////////////////////////////////////////////////////////// // // fast insertion that only processes nodes that have a chance of getting a good score // void FindInsertLocations(CSequenceFile *treeSeqfile, CPTree *tree, CSequenceFile *insertSeqfile, CInsertPosArray &inserts) { // for each seq for insertion // insert in the tree - starting at root CPNode *root = tree->root; int count = 0; time_t start = time(NULL); // build insertion list insertSeqfile->ResetSeqIterator(); CSequenceItem *seq = insertSeqfile->GetNextSeq(); while (seq != NULL) { CSequenceItem *iseq = insertSeqfile->GetSequence(seq->name.c_str()); // Check to see if this leaf is in the core tree if (coreNames.find(seq->name.c_str()) != coreNames.end()) { DisplayL("**** Sequence is already in core tree: %s\n", seq->name.c_str()); seq = insertSeqfile->GetNextSeq(); // get next sequence continue; } if (iseq == NULL) { DisplayL("**** Cannot find sequence for %s\n", seq->name.c_str()); seq = insertSeqfile->GetNextSeq(); // get next sequence continue; } // check that we have the taxonomy string tax; if (taxonomy != NULL) tax = GetTaxonomy(seq->name.c_str()); if (tax.empty() && testing) { DisplayL("**** Cannot find sequence taxonomy for %s\n", seq->name.c_str()); seq = insertSeqfile->GetNextSeq(); // get next sequence //continue; } CInsertPos *item = new CInsertPos(); item->seq = iseq; item->pars.Convert(iseq->GetSeqData()); for (int i=0 ; i < item->pars.len ; ++i) { if (item->pars.data[i] != 0) { if (useMask && (mask[i] != 0)) ++item->nSites; else if (!useMask) ++item->nSites; item->pars.end = i; if (item->pars.start == -1) item->pars.start = i; } } if (++count%100 == 0) DisplayL("[%10d/%d] {%d sec} [%s]\n", count, insertSeqfile->seqCount, time(NULL)-start+1, seq->name.c_str()); if (item->nSites < 800) TRACE("SHORT"); nSeqRemaining = tree->nodeList.size(); time_t start_item = time(NULL); DisplayL("Insert [%20s](len=%d) [%5d sites] (%d - %d) [%s]", item->seq->name.c_str(), item->seq->len, item->nSites, item->pars.start, item->pars.end, tax.c_str()); inserts.push_back(item); /// DisplayL("Searching for position to insert %d sequences in tree of %d nodes. {Setup: %d sec}\n", inserts.size(), tree->nodeList.size(), time(NULL)-start+1); FindInsertLocations(treeSeqfile, root, seq, item); if (nSeqRemaining > 0) DisplayL("(%d sec) [%5d skipped]\n", time(NULL)-start_item, nSeqRemaining); else DisplayL("(%d sec)\n", time(NULL)-start_item); /// DisplayBestInsertLocations(item, TRUE); seq = insertSeqfile->GetNextSeq(); // get next sequence } time_t finish = time(NULL); DisplayL("Insertion of %d sequences in [%d sec]\n", inserts.size(), finish-start+1); } /////////////////////////////////////////////////////////////////////////////////////////////////// WORD *scoreMatrix = NULL; void BuildScoreMatrix() { if (scoreMatrix != NULL) free(scoreMatrix); scoreMatrix = (WORD*)calloc(2, 4096*4096); for (int i=0 ; i < 4*1024 ; ++i) for (int j=0 ; j < 4*1024 ; ++j) { int key = ((i << 12) | j); int diffs = 0; int indel = 0; int parts = 0; // count number of diffs, indel, partial for (int k=0 ; k < 3 ; ++k) { BYTE v1 = (i >> (k*4)) & 0x0F; // shifts by 0, 4, 8 BYTE v2 = (j >> (k*4)) & 0x0F; if (v1 != v2) { if ((v1 & v2) != 0) parts += 1; else if ((v1 != 0) && (v2 != 0)) diffs += 1; else indel += 1; } } if ((diffs > 3) || (indel > 3) || (parts > 3) || ((diffs+indel+parts) > 3)) DisplayL("BAD BAD COMPUTER"); scoreMatrix[key] = (diffs << 0) | (indel << 3) | (parts << 6); } } /////////////////////////////////////////////////////////////////////////////////////////////////// int CalcCost_NEW1(CParsimonySet &next_pars, CParsimonySet &node_pars, int &diffs, int &partials, int &indel, int thresh) { // calc delta to insert next_pars int len = min(next_pars.len, node_pars.len); register LPCSTR m = mask; register BYTE *p1 = next_pars.data; register BYTE *p2 = node_pars.data; register DWORD key; ++nCalcCost; diffs = 0; partials = 0; indel = 0; for (int i=0 ; (i < len) ; i+=3) { key = 0; for (int j=0 ; j < 3 ; ++j) { key = key << 4; if ((!useMask || *m++) && ((i+j >= next_pars.start) && (i+j <= next_pars.end))) { key |= ((DWORD)(*p1) << 12) | (*p2&0x0F); } ++p1; ++p2; } // look up score for all three values register WORD value = scoreMatrix[key]; if (value == 0) continue; diffs += value & 0x07; indel += (value >> 3) & 0x07; partials += (value >> 6) & 0x07; thresh -= (value & 0x07) + ((value >> 3) & 0x07) + ((value >> 6) & 0x07); if (thresh < 0) return INT_MAX; } ++nCalcCostFull; return diffs + indel + partials/4; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CalcCost_NEW4(CParsimonySet &next_pars, CParsimonySet &node_pars, int &diffs, int &partials, int &indel, int thresh) { // calc delta to insert next_pars int len = min(next_pars.len, node_pars.len); LPCSTR m = mask; ++nCalcCost; if ((next_pars.segCounts != NULL) && (node_pars.segCounts != NULL)) { // compare the counts, looking for known error int count = next_pars.CompareSegments(&node_pars); // if error is over threshold, skip if (count > thresh) return INT_MAX; } ++nCalcCostFull; diffs = 0; partials = 0; indel = 0; BYTE *p1 = next_pars.data; BYTE *p2 = node_pars.data; for (int i=0 ; i < len ; ++i) { if (!useMask || *(m++)) { char s1 = *p1; char s2 = *p2; if (s1 != s2) { // there is a difference, is is partial, diff, or indel if ((s1 & s2) != 0) ++partials; else if ((s1 != 0) && (s2 != 0)) ++diffs; else if ((i >= next_pars.start) && (i <= next_pars.end)) // only count indel if within next_pars area ++indel; if ((diffs+indel+partials/4) > thresh) return INT_MAX; } } ++p1; ++p2; } return diffs + indel + partials/4; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CalcCost_ORIG(CParsimonySet &next_pars, CParsimonySet &node_pars, int &diffs, int &partials, int &indel, int thresh) { // calc delta to insert next_pars int len = min(next_pars.len, node_pars.len); register LPCSTR m = mask; ++nCalcCost; diffs = 0; partials = 0; indel = 0; register BYTE *p1 = next_pars.data; register BYTE *p2 = node_pars.data; for (int i=0 ; i < len ; ++i) { if ((!useMask || *m++) && ((i >= next_pars.start) && (i <= next_pars.end))) // only count(indel) if within next_pars area { register char s1 = *p1; register char s2 = *p2; if (s1 != s2) { // there is a difference, is is partial, diff, or indel if ((s1 & s2) != 0) ++partials; else if ((s1 != 0) && (s2 != 0)) ++diffs; else ++indel; if ((diffs+indel+partials/4) > thresh) return INT_MAX; } } ++p1; ++p2; } ++nCalcCostFull; return diffs + indel + partials/4; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CalcCost(CParsimonySet &next_pars, CParsimonySet &node_pars, int &diffs, int &partials, int &indel, int thresh) { switch (useCalcCost) { case 1: return CalcCost_NEW1(next_pars, node_pars, diffs, partials, indel, thresh); case 4: return CalcCost_NEW4(next_pars, node_pars, diffs, partials, indel, thresh); default: return CalcCost_ORIG(next_pars, node_pars, diffs, partials, indel, thresh); } } /////////////////////////////////////////////////////////////////////////////////////////////////// CParsimonySet* GetParsimonySet(CPNode *node, BOOL create) { CParsimonySet *node_pars = NULL; string name = GetNodeName(node); node_pars = (CParsimonySet*)parsimonyList[name]; if ((node_pars == NULL) && create) { // does not exist, create new entry // DisplayL("Create new CParsimonySet for %s\n", name.c_str()); node_pars = new CParsimonySet(); // get sequence from the sequence file CSequenceItem *seq = treeSeqfile->GetSeq(name.c_str()); if ((seq != NULL) && (seq->len > 0)) { node_pars->Convert(seq->data); seq->ReleaseSeqData(); } parsimonyList[name] = node_pars; // if (parsimonyList.size() % 100 == 0) // DisplayL("Created %d parsimony sets\n", parsimonyList.size()); } return node_pars; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CalcAncestorParsimony(CPTree *tree) { DisplayT("Calculating Parsimony ..."); if (treeSeqfile == NULL) { DisplayT("*** Cannot calc parsimony, no sequence file loaded"); return 0; } time_t start = time(NULL); int cost = 0; nSeqRemaining = tree->nodeList.size(); cost = CalcNodeParsimony(tree->root); if (fitch) { DisplayL("Applying parsimonious selections back down the tree.\n"); int changes = ForceNodeParsimony(tree->root); DisplayL("%d nodes were modified\n", changes); } /*** // Save the calculated parsimony for quicker startup // DisplayT("Writing Parsimony ..."); CSequenceFile parsimony; if (!parsimony.Open("Parsimony.FASTA", "w+")) { DisplayT("*** Cannot open parsimony file"); return 0; } // for each branch in the tree // write sequence to file nSeqRemaining = (tree->nodeList.size() + 1) / 2; WriteParsimonySet(tree->root, &parsimony); parsimony.Close(); ***/ time_t delta = time(NULL) - start + 1; double npersec = tree->nodeList.size() * 1. / delta; DisplayT("\nProcessed %d nodes in %d seconds, %.0f nodes per sec\n", tree->nodeList.size(), delta, npersec); return cost; } /////////////////////////////////////////////////////////////////////////////////////////////////// int ForceNodeParsimony(CPNode *node) { // force specific parsimony from parent onto the children if (node == NULL) return 0; if (!node->IsBranchNode()) return 0; CParsimonySet *node_pars = GetParsimonySet(node, FALSE); if (node_pars == NULL) return 0; //DisplayL("Update node [%s]\n", node->title.c_str()); int count = 0; for (CPNodeListIter iter=node->edges.begin() ; iter != node->edges.end() ; ++iter) { CPNode *child = (*iter); if (child == NULL) { DisplayL("***** Child not found [%s]\n", node->title.c_str()); continue; } CParsimonySet *childParsSet = GetParsimonySet(child, FALSE); if (childParsSet == NULL) continue; if (childParsSet->Force(node_pars) > 0) ++count; count += ForceNodeParsimony(child); } return count; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CalcNodeParsimony(CPNode *node) { // calc parsimony of the tree int cost = 0; string alignment; if (node == NULL) return INT_MAX; CParsimonySet *node_pars = GetParsimonySet(node, TRUE); if (node->IsBranchNode()) { CParsimonySet unionSeq; CParsimonySet interSeq; int count = 0; for (CPNodeListIter iter=node->edges.begin() ; iter != node->edges.end() ; ++iter) { CPNode *child = (*iter); if (child == NULL) { DisplayL("***** Child not found [%s]\n", node->title.c_str()); continue; } CParsimonySet *childParsSet = GetParsimonySet(child, FALSE); if ((childParsSet == NULL) || (childParsSet->len == 0)) { cost += CalcNodeParsimony(child); childParsSet = GetParsimonySet(child); } unionSeq.Union(childParsSet); interSeq.Intersect(childParsSet); if (childParsSet->len > 0) count++; } // unionSeq.Display("UNION"); // interSeq.Display("INTER"); cost += node_pars->Set(&unionSeq, &interSeq); // save the union information for scoring subtree string name = node->title; CParsimonySet *union_pars = new CParsimonySet(); union_pars->Union(&unionSeq); unionList[name] = union_pars; } else { // taxa node if (node_pars->len == 0) { // read the sequence from tree sequence file // create the parsimony set from sequence string name = GetNodeName(node); CSequenceItem *seq = treeSeqfile->GetSequence(name.c_str()); if (seq != NULL) { node_pars->Convert(seq->GetSeqData()); seq->ReleaseSeqData(); } } } //string t = node->attrs.GetString(ATTR_NAME); //if (t.empty()) t = node->title; //TRACE("Setting [%s], Cost = %d\n", t.c_str(), cost); node->attrs.Add("PARSIMONY_COST", cost); if (--nSeqRemaining%1000 == 0) DisplayT("\rCalcParsimony %d nodes remaining ", nSeqRemaining); return cost; } /////////////////////////////////////////////////////////////////////////////////////////////////// int WriteParsimonySet(CPNode *node, CSequenceFile *parsimony) { // Write the node's parsimony value to sequence file if (!node->IsBranchNode()) return 0; // calc the parsimony output string CParsimonySet *node_pars = GetParsimonySet(node, TRUE); char *pars = NULL; node_pars->BuildString(pars, -1); string name = GetNodeName(node); // add new sequence to the parsSequences CSequenceItem *seq = new CSequenceItem(name.c_str(), -1, strlen(pars), pars); parsimony->seqlist[name] = seq; parsimony->WriteSequence(seq); /// DisplayL("Parsimony for [%s] from %d decendants: %d,[%100.100s]\n", node->title.c_str(), count, strlen(pars), pars); free(pars); if (--nSeqRemaining%1000 == 0) DisplayT("\r %d nodes remaining to be written ", nSeqRemaining); return 1; } /////////////////////////////////////////////////////////////////////////////////////////////////// LPCSTR GetTaxonomy(LPCSTR name, CPNode *node) { static string tax; tax.clear(); if (taxonomy != NULL) { CSequenceItem *seq = taxonomy->GetSequenceHeader(name); if ((seq != NULL) && (seq->hdr != NULL)) { tax = seq->hdr; TrimRight(tax, "\n\r\t "); int k = tax.find_first_of("\t "); if (k > 0) tax = tax.substr(k+1, tax.length()); Trim(tax, "\n\r\t "); } } return tax.c_str(); } /////////////////////////////////////////////////////////////////////////////////////////////////// void DisplayInsertLocations(CInsertPosArray &inserts, BOOL all) { // show best for each insert int diffs; int parts; int indel; // int nerror = 0; // int exact = 0; // int partial_seq = 0; // int partial_tree = 0; // int partials[10] = {10*0}; for (int i=0 ; i < inserts.size() ; ++i) { string name = inserts[i]->seq->name; string tax = GetTaxonomy(name.c_str()); DisplayL("======================================================================\n"); if (all) DisplayL("\nInsertion of [%s][%5d sites] [%d matches] Taxonomy[%s]:\n", inserts[i]->seq->name.c_str(), inserts[i]->nSites, inserts[i]->best.list.size(), tax.c_str()); string taxFirst; string taxBest; CBestList::iterator iterB = inserts[i]->best.list.begin(); int count = 0; if (inserts[i]->best.list.size() == 0) DisplayL("\tNO MATCHES found\n"); for (iterB=inserts[i]->best.list.begin() ; iterB != inserts[i]->best.list.end() ; ++iterB) { ++count; if ((iterB->score > inserts[i]->nSites/5) && (count > 3)) break; // TRACE("Getting taxonomy for [%s]", iterB->node->title); ///?? SetMyTaxonomy(iterB->node); if (iterB->tax.empty()) { iterB->node->GetComment(ATTR_TAXLABEL, taxBest, ""); if (taxBest.empty() && (taxonomy != NULL)) { string t = GetNodeName(iterB->node); taxBest = GetTaxonomy(t.c_str(), iterB->node); } iterB->tax = taxBest; } // TRACE("[%s]\n", iterB->tax); taxBest = iterB->tax; if (taxFirst.empty()) taxFirst = taxBest; CParsimonySet *node_pars = GetParsimonySet(iterB->node); char marker; if (node_pars != NULL) { int cost = CalcCost(inserts[i]->pars, *node_pars, diffs, parts, indel); /// ASSERT(cost==iterB->score); int per = -1; if (inserts[i]->nSites > 0) per = (inserts[i]->nSites-(diffs+indel))* 100 / inserts[i]->nSites; marker = ' '; if (cost <= inserts[i]->nSites*3/100) marker = '*'; else if (cost <= inserts[i]->nSites*6/100) marker = '+'; if (all) { DisplayL("%c(%3d%%) %6d (%4d diffs, %4d partials, %4d indels) [%12s][%s]\n", marker, per, iterB->score, diffs, parts, indel, iterB->node->title.c_str(), taxBest.c_str()); if (stats) { string match; GetTaxonomyMatch(tax, taxBest, match, rankCounts); string name = ""; if (iterB == inserts[i]->best.list.begin()) name = inserts[i]->seq->name; fprintf(stats, "%15s\t%s\t%3d%%\t%4d\t%4d\t%4d\t%s\t%s\t%s\n", name.c_str(), iterB->node->title.c_str(), per, diffs, indel, parts, match.c_str(), taxBest.c_str(), tax.c_str()); } } } } iterB = inserts[i]->best.list.begin(); if (iterB != inserts[i]->best.list.end()) { taxBest = iterB->tax; string marker = ""; string t = (taxBest.empty() ? taxFirst : taxBest); GetTaxonomyMatch(tax, t, marker, rankCounts); CParsimonySet *node_pars = GetParsimonySet(iterB->node); int cost = CalcCost(inserts[i]->pars, *node_pars, diffs, parts, indel); DisplayL("\nInsertion [%5d sites] [%20.20s] %6d (%4d diffs, %4d partials, %4d indels)\n", inserts[i]->nSites, inserts[i]->seq->name.c_str(), cost, diffs, parts, indel, 0); string diff; int i; for (i=0 ; (i < tax.length()) && (i < taxBest.length()) ; ++i) diff += (tax[i] == taxBest[i] ? ' ' : 'X'); for ( ; i < tax.length() ; ++i) diff += 'X'; for ( ; i < taxBest.length() ; ++i) diff += 'X'; DisplayL("%12.12s\t Seq[%s]\n", marker.c_str(), tax.c_str()); DisplayL("%12.12s\t [%s]\n", "", diff.c_str()); DisplayL("%12.12s\t Best[%s]\n", "", taxBest.c_str()); if (taxBest != taxFirst) DisplayL("\tFirst[%s]\n", taxFirst.c_str()); } } } /////////////////////////////////////////////////////////////////////////////////////////////////// void DisplayBestInsertLocations(CInsertPos *item, BOOL all) { // show best for each insert int diffs; int parts; int indel; string name = item->seq->name; string tax = GetTaxonomy(name.c_str()); DisplayL("======================================================================\n"); if (all) DisplayL("\nInsertion of [%s][%5d sites] [%d matches] Taxonomy[%s]:\n", item->seq->name.c_str(), item->nSites, item->best.list.size(), tax.c_str()); string taxFirst; string taxBest; CBestList::iterator iterB = item->best.list.begin(); int count = 0; if (item->best.list.size() == 0) DisplayL("\tNO MATCHES found\n"); for (iterB=item->best.list.begin() ; iterB != item->best.list.end() ; ++iterB) { ++count; if ((iterB->score > item->nSites/5) && (count > 3)) break; // TRACE("Getting taxonomy for [%s]", iterB->node->title); ///?? SetMyTaxonomy(iterB->node); if (iterB->tax.empty()) { iterB->node->GetComment(ATTR_TAXLABEL, taxBest, ""); if (taxBest.empty() && (taxonomy != NULL)) { string t = GetNodeName(iterB->node); taxBest = GetTaxonomy(t.c_str(), iterB->node); } iterB->tax = taxBest; } //TRACE("[%s]\n", iterB->tax); taxBest = iterB->tax; if (taxFirst.empty()) taxFirst = taxBest; CParsimonySet *node_pars = GetParsimonySet(iterB->node); char marker; if (node_pars != NULL) { int cost = CalcCost(item->pars, *node_pars, diffs, parts, indel); /// ASSERT(cost==iterB->score); int per = -1; if (item->nSites > 0) per = (item->nSites-(diffs+indel))* 100 / item->nSites; marker = ' '; if (cost <= item->nSites*3/100) marker = '*'; else if (cost <= item->nSites*6/100) marker = '+'; if (all) { DisplayL("%c(%3d%%) %6d (%4d diffs, %4d partials, %4d indels) [%12s][%s]\n", marker, per, iterB->score, diffs, parts, indel, iterB->node->title.c_str(), taxBest.c_str()); if (stats) { string match; GetTaxonomyMatch(tax, taxBest, match, rankCounts); string name = ""; if (iterB == item->best.list.begin()) name = item->seq->name; fprintf(stats, "%15s\t%s\t%3d%%\t%4d\t%4d\t%4d\t%s\t%s\t%s\n", name.c_str(), iterB->node->title.c_str(), per, diffs, indel, parts, match.c_str(), taxBest.c_str(), tax.c_str()); } } } } iterB = item->best.list.begin(); if (iterB != item->best.list.end()) { taxBest = iterB->tax; string marker = ""; string t = (taxBest.empty() ? taxFirst : taxBest); GetTaxonomyMatch(tax, t, marker, rankCounts); CParsimonySet *node_pars = GetParsimonySet(iterB->node); int cost = CalcCost(item->pars, *node_pars, diffs, parts, indel); DisplayL("\nInsertion [%5d sites] [%20.20s] %6d (%4d diffs, %4d partials, %4d indels)\n", item->nSites, item->seq->name.c_str(), cost, diffs, parts, indel, 0); string diff; int i; for (i=0 ; (i < tax.length()) && (i < taxBest.length()) ; ++i) diff += (tax[i] == taxBest[i] ? ' ' : 'X'); for ( ; i < tax.length() ; ++i) diff += 'X'; for ( ; i < taxBest.length() ; ++i) diff += 'X'; DisplayL("%12.12s\t Seq[%s]\n", marker.c_str(), tax.c_str()); DisplayL("%12.12s\t [%s]\n", "", diff.c_str()); DisplayL("%12.12s\t Best[%s]\n", "", taxBest.c_str()); if (taxBest != taxFirst) DisplayL("\tFirst[%s]\n", taxFirst.c_str()); } } /////////////////////////////////////////////////////////////////////////////////////////////////// void DisplayRankCounts(LPCSTR header, int counts[][4]) { if (!testing) return; if (counts[0][0] == 0) return; DisplayL("\n%s\n _________Precision________ __________Recall__________\n", header); for (int r=0 ; r < RANK_N ; ++r) { if (counts[r][0] == 0) continue; double per = 100. * counts[r][1] / counts[r][0]; double per2 = 100. * counts[r][3] / counts[r][2]; DisplayL("\t%10.10s: %8d %8d (%6.2f%%) %8d %8d (%6.2f%%)\n", rankNames[r], counts[r][0], counts[r][1], per, counts[r][3], counts[r][2], per2); } } /////////////////////////////////////////////////////////////////////////////////////////////////// // STATS FORMAT: name, insert position title, percentage match, diffs, indel, partials, conf level, best taxonomy [, correct taxonomy] #define TSTATS_HEADER "#Insertion Name\tSite \tMatch:%\tdiff\tindel\tpartial\tconf\ttaxonomy | correct taxonomy\n" #define TSTATS_FORMAT "%15s\t%s\t%3d%%\t%4d\t%4d\t%4d\t%1d\t%s\t|\t%s\n" #define STATS_HEADER "#Insertion Name\tMatch:%\ttaxonomy\n" #define STATS_FORMAT "%15s\t%3d%%\t%s\n" #define STATS_FORMAT2 "%15s\t \t%s\n" int LOWER_SCORE = 0; int UPPER_SCORE = 100; int LOWER_PER = 90; int UPPER_PER = 101; void OutputInsertLocations(CInsertPosArray &inserts, BOOL all) { // show best for each insert int diffs; int parts; int indel; CTaxEntry taxEntries("root"); // keeps track of diversity seen in taxonomy of inserted sequences if (stats) fprintf(stats, "%s\n", STATS_HEADER); for (int i=0 ; i < inserts.size() ; ++i) { string name = inserts[i]->seq->name; string taxCorrect = GetTaxonomy(name.c_str()); string taxFirst; string taxBest; CBestList::iterator iterB = inserts[i]->best.list.begin(); int count = 0; CTaxEntry taxVotes("Votes:"); // keep track of all high scoring taxonomies for single sequence DisplayL("======================================================================\n"); DisplayL("\nInsertion: [%20.20s] [%5d sites]\n", name.c_str(), inserts[i]->nSites); if (inserts[i]->best.list.size() == 0) { DisplayL("\tNO MATCHES found\n"); if (stats) { char buf[1024]; sprintf(buf, "NO MATCHES found (%d sites in sequence)", inserts[i]->nSites); fprintf(stats, STATS_FORMAT, name.c_str(), 0, buf); if (!taxCorrect.empty()) fprintf(stats, STATS_FORMAT2, "",taxCorrect.c_str()); fprintf(stats, "\n"); } continue; } int bestScore = inserts[i]->best.list.begin()->score; int threshScore = bestScore + (bestScore >= 100 ? 50 : (bestScore > 50 ? 20 : 10)); for (iterB=inserts[i]->best.list.begin() ; iterB != inserts[i]->best.list.end() ; ++iterB) { ++count; if ((iterB->score > inserts[i]->nSites/5) && (count > 3)) // score too low for processing, process at least 3 break; string t = GetNodeName(iterB->node); // find the taxonomy for this insertion point if (iterB->tax.empty()) { iterB->node->GetComment(ATTR_TAXLABEL, taxBest, ""); if (taxBest.empty() && (taxonomy != NULL)) { SetMyTaxonomy(iterB->node); // set taxonomy at insertion point taxBest = GetTaxonomy(t.c_str(), iterB->node); } iterB->tax = taxBest; } // find distance from position in full tree double dist = -1; if (fullTree) { dist = ComparePosition(t.c_str(), iterB->node, fullTree, tree); DisplayL("\t\t%5d [%5f] [%s][%s]\n", iterB->score, dist, iterB->node->title.c_str(), iterB->tax.c_str()); } if (iterB->score < threshScore) { int votes = ((threshScore-iterB->score)*100/threshScore); // most votes for best scores taxVotes.Add(iterB->tax.c_str(), votes); } taxBest = iterB->tax; if (taxFirst.empty()) taxFirst = taxBest; CParsimonySet *node_pars = GetParsimonySet(iterB->node); int conf; if (node_pars != NULL) { int cost = CalcCost(inserts[i]->pars, *node_pars, diffs, parts, indel); //ASSERT(cost==iterB->score); int per = -2; if (inserts[i]->nSites > 0) per = (inserts[i]->nSites-(diffs+indel))* 100 / inserts[i]->nSites; conf = 0; if (cost <= inserts[i]->nSites*3/100) conf = 9; else if (cost <= inserts[i]->nSites*6/100) conf = 5; DisplayL("\t\t%5d [%3d%%] [%s][%s]\n", iterB->score, per, iterB->node->title.c_str(), iterB->tax.c_str()); if (all) { DisplayL("%1d (%3d%%) %6d (%4d diffs, %4d partials, %4d indels) [%12s]%c[%s]\n", conf, per, iterB->score, diffs, parts, indel, iterB->node->title.c_str(),(iterB->node->IsBranchNode()?'^':' '), taxBest.c_str()); if (stats) { string name = ""; if (iterB == inserts[i]->best.list.begin()) name = inserts[i]->seq->name; fprintf(stats, TSTATS_FORMAT, name.c_str(), iterB->node->title.c_str(), per, diffs, indel, parts, conf, taxBest.c_str(), taxCorrect.c_str()); } } } } iterB = inserts[i]->best.list.begin(); if (iterB != inserts[i]->best.list.end()) { taxBest = iterB->tax; string marker = ""; string t = (taxBest.empty() ? taxFirst : taxBest); if (t.empty()) { // try to find taxonomy from ancestory CPNode *node = iterB->node->parent; while ((node != NULL) && t.empty()) { t = node->attrs.GetString(ATTR_TAXLABEL); // DisplayL("\t using ancestor (%s) taxonomy: [%s] \n", GetNodeName(node), t.c_str()); node = node->parent; } taxBest = t; } CParsimonySet *node_pars = GetParsimonySet(iterB->node); int cost = CalcCost(inserts[i]->pars, *node_pars, diffs, parts, indel); DisplayL("\t %6d (%4d diffs, %4d partials, %4d indels) [%s] \n", cost, diffs, parts, indel, taxBest.c_str()); int per = -1; if (inserts[i]->nSites > 0) per = (inserts[i]->nSites-cost)* 100 / inserts[i]->nSites; if (per >= scoreThresh) { if (testing > 2) taxVotes.Display(""); CStringList taxVoteList; taxVotes.FindBest(60, taxVoteList); string leader = "Assigned Taxonomy:"; if (taxVoteList.size() > 0) { for (int knox=0; knox < taxVoteList.size() ; ++knox) { DisplayL("%18s[%s]\n", leader.c_str(), taxVoteList[knox].c_str()); leader = ""; } if ((taxVoteList.size() > 0) && !taxVoteList[0].empty()) taxBest = taxVoteList[0]; } else DisplayL("%18s[%s]\n", leader.c_str(), taxBest.c_str()); taxEntries.Add(taxBest.c_str()); // update diversity if (!taxCorrect.empty()) { GetTaxonomyMatch(taxCorrect, (taxBest.empty()? taxFirst : taxBest), marker, rankCounts); string phylum; GetRankFromTax(RANK_PHYLUM, taxCorrect, phylum, FALSE); if (phylumRankCounts.find(phylum.c_str()) == phylumRankCounts.end()) { // create ranks phylumRankCounts[phylum.c_str()] = new CRankCounts(); } CRankCounts *counts = phylumRankCounts[phylum.c_str()]; GetTaxonomyMatch(taxCorrect, (taxBest.empty()? taxFirst : taxBest), marker, counts->rankCounts); } } else { taxBest.clear(); DisplayL("no assignment (%d%% < %d%%)", per, scoreThresh); } int conf = 0; if (cost <= inserts[i]->nSites*3/100) conf = 9; else if (cost <= inserts[i]->nSites*6/100) conf = 5; if ( !taxCorrect.empty() && testing ) DisplayL(" Correct Taxonomy:[%s]\n", taxCorrect.c_str()); if (stats) { size_t n; while ((n=taxBest.find(' ')) != string::npos) taxBest.erase(n,1); while ((n=taxCorrect.find(' ')) != string::npos) taxCorrect.erase(n,1); if (taxBest.empty()) taxBest = "No assignment could be made!"; fprintf(stats, STATS_FORMAT, name.c_str(), per, taxBest.c_str()); if (!taxCorrect.empty()) { fprintf(stats, STATS_FORMAT2, "",taxCorrect.c_str()); // find first position of difference string diffs; int i = 0; while ((i < taxBest.length()) && (i < taxCorrect.length()) && (taxBest[i] == taxCorrect[i])) { ++i; diffs += " "; } while ((i < taxBest.length()) && (i < taxCorrect.length())) { ++i; if (i < taxBest.length()) diffs += "x"; else diffs += "o"; } //if (diffs.find('x') < diffs.length()) fprintf(stats, STATS_FORMAT2, "",diffs.c_str()); } fprintf(stats, "\n"); fflush(stats); } } } DisplayL("Taxonomies List:\n"); taxEntries.Display(" "); } /////////////////////////////////////////////////////////////////////////////////////////////////// int ParseTaxonomy(string t, CStringList &taxList) { // find next separator, add to string tax = t; ToLower(tax); while (!tax.empty()) { // find separator int sep = 0; while ((sep < tax.length()) && (tax[sep] != ';') && (tax[sep] != '/')) ++sep; string entry = tax.substr(0, sep); LPCSTR unclassified = "unclass"; string lower = entry.substr(0, strlen(unclassified)); for (int i=0 ; i < sizeof(unclassified) ; ++i) lower[i] = tolower(lower[i]); if ((entry.size() > 0) && (strncmp(lower.c_str(), unclassified, strlen(unclassified)) != 0)) // does NOT begin with "Unclassified" taxList.push_back(entry); if (sep < tax.length()) tax = tax.substr(sep+1); else tax.clear(); } return taxList.size(); } /////////////////////////////////////////////////////////////////////////////////////////////////// void GetRankFromTax(int rank, string &tax, string &rankStr, BOOL only) { CStringList taxList; ParseTaxonomy(tax, taxList); char sep = tax.find(';') >= 0 ? ';' : '/'; rankStr.clear(); for (int i=0 ; (i <= rank) && (i < taxList.size()) ; ++i) { if (!only) { if (!rankStr.empty()) rankStr += sep; } if (!only || (i == rank)) rankStr += taxList[i]; } } /////////////////////////////////////////////////////////////////////////////////////////////////// int GetTaxonomyMatch(string &taxA, string &taxB, string &marker, int counts[][4]) { // taxA is the correct solution // taxB is our assigned solution // int levels = 0; BOOL matching = TRUE; // TRUE if still matching marker = ""; // parse the entries from each taxonomy CStringList taxListA; CStringList taxListB; ParseTaxonomy(taxA, taxListA); ParseTaxonomy(taxB, taxListB); for (int k=0 ; (k < taxListA.size()) && (k < taxListB.size()) && (k < RANK_N) ; ++k) { counts[k][0] += 1; // saw another rank at this level if (matching && (k < taxListB.size())) { LPCSTR tA = taxListA[k].c_str(); LPCSTR tB = taxListB[k].c_str(); if (strcmp(tA,tB) == 0) { // matched at this level counts[k][1] += 1; // saw another match at this level ++levels; } else if (precision) // count all mistakes? matching = FALSE; } } matching = TRUE; for (int k=0 ; (k < taxListA.size()) && (k < RANK_N) ; ++k) { counts[k][2] += 1; // saw another rank at this level if (matching && (k < taxListB.size())) { LPCSTR tA = taxListA[k].c_str(); LPCSTR tB = taxListB[k].c_str(); if (strcmp(tA,tB) == 0) { // matched at this level counts[k][3] += 1; // saw another match at this level } else matching = FALSE; } } // Create marker for display if ((levels < taxListA.size()) && (levels < taxListB.size())) { // check to see how close we are if (levels >= 4) { marker = ">>>"; } else { marker = "XXX"; } } else if (levels < taxListA.size()) { marker = "> "; } else if (levels < taxListB.size()) { marker = "< "; } for (int r=levels ; r > 0 ; --r) marker += rankNames[r-1][0]; return levels; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL AddTaxonomyToTree(CPTree *tree, CSequenceFile *taxonomy) { if (tree == NULL) return FALSE; if (taxonomy == NULL) return FALSE; CPNodeList &nodes = tree->nodeList; for (CPNodeListIter iter=nodes.begin() ; iter != nodes.end() ; ++iter) { string tax; CPNode *node = *iter; if (node == NULL) continue; CSequenceItem *seq = taxonomy->GetSequence(node->title.c_str()); if (seq != NULL) { if (seq->data) tax = seq->data; else if (seq->hdr) tax = seq->hdr; } int pos = tax.find_first_of('\t'); if (pos < 20) tax = tax.substr(pos+1); TrimRight(tax, "\n\r\t "); if (!node->IsBranchNode()) tax = "CORE: " + tax; node->attrs.Add(ATTR_COMMENT, tax); } return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Builds a map of tree node names that have list of new sequences to be inserted as children CTreeInserts* BuildTreeInsertLists(CInsertPosArray &inserts) { if (inserts.size() == 0) return NULL; CTreeInserts* treeInserts = new CTreeInserts(); for (int i=0 ; i < inserts.size() ; ++i) { CInsertPos *in = inserts[i]; if (in->best.list.size() == 0) continue; if (in->seq == NULL) continue; CPNode *node = in->best.list[0].node; if (!node->IsBranchNode()) node = node->parent; CTreeInsertList *iList = (*treeInserts)[node]; if (iList == NULL) { iList = new CTreeInsertList(); (*treeInserts)[node] = iList; } iList->push_back(in); } return treeInserts; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL BuildInsertTree(CTreeInserts* insertLists, CPTree *tree) { if (tree == NULL) return FALSE; if (insertLists == NULL) return FALSE; if (insertLists->size() == 0) return FALSE; // for each item in the map for (CTreeInserts::iterator iter=insertLists->begin() ; iter != insertLists->end() ; ++iter) { CPNode *node = (*iter).first; CTreeInsertList *inserts = (*iter).second; CPNode *child = NULL; if (inserts->size() == 0) continue; CInsertPos *in = (*inserts)[0]; int score = in->best.list[0].score * 100 / in->nSites; if (score > 100-scoreThresh) { DisplayL("[%s] at %d%% does not meet threshold (%d%%)\n", in->seq->name.c_str(), score, 100-scoreThresh); continue; } if (inserts->size() == 1) { // insert as child of the node CInsertPos *in = (*inserts)[0]; child = AddChild(tree, node, in); node->AddEdge(child); } else { // Creaate new branch node // for each item in the list // add as child of the new branch double shortest = 1000000.; CPNode *branch = new CPNode(tree); node->AddEdge(branch); for (int i=0 ; i < inserts->size() ; ++i) { CInsertPos *in = (*inserts)[i]; child = AddChild(tree, node, in); double dist = child->attrs.GetDouble(ATTR_DISTANCE); if (dist < shortest) shortest = dist; branch->AddEdge(child); } if (shortest > 0) { // double dist = branch->attrs.GetDouble(ATTR_DISTANCE); // DisplayL("Shortest distance %f\n", shortest); shortest /= 2; branch->attrs.Add(ATTR_DISTANCE, shortest); // subtract shortest from each of the children for (CPNodeListIter iter=branch->edges.begin() ; iter != branch->edges.end() ; ++iter) { CPNode *child = (*iter); double dist = child->attrs.GetDouble(ATTR_DISTANCE); dist -= shortest; child->attrs.Add(ATTR_DISTANCE, dist); } } } } return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// CPNode* AddChild(CPTree *tree, CPNode *node, CInsertPos *in) { int diffs; int parts; int indel; CPNode *inserted = new CPNode(tree); inserted->attrs.Add(ATTR_NAME, in->seq->name); double dist = CalcDist(node, in, diffs, parts, indel); if (jukes_cantor) { // distance = -3/4 * ln(1 - 4/3*p) // where p is the proportion of sites with different nucleotides. double p = (diffs + indel) * 1. / in->nSites; dist = -3./4. * log(1. - (4./3.*p)); } inserted->attrs.Add(ATTR_DISTANCE, dist); // Take parent taxonomy as node's taxonomy string tax = in->best.list[0].tax; while (tax.empty() && (node != NULL)) { tax = node->attrs.GetString(ATTR_TAXLABEL); // DisplayL("\t\ttrying ancestor [%s]\n", GetNodeName(node)); node = node->parent; } int per = -1; if (in->nSites > 0) per = (in->nSites-(diffs+indel))* 100 / in->nSites; char comment[2*1024]; sprintf(comment,"Sites:%d, %d%% diffs[%d,%d,%d], Score:%d, [%s]", in->nSites, per, diffs, parts, indel, in->best.list[0].score, tax.c_str()); inserted->attrs.Add(ATTR_COMMENT, comment); return inserted; } /////////////////////////////////////////////////////////////////////////////////////////////////// double CalcDist(CPNode *parent, CInsertPos* in, int &diffs, int &parts, int &indel) { // calc the distance for tree branch edge double dist = 0.1; CParsimonySet *node_pars = GetParsimonySet(parent); if (node_pars != NULL) { CParsimonySet pars(&in->pars); CalcCost(pars, *node_pars, diffs, parts, indel); // just need the details if (in->nSites > 0) dist = (diffs+indel)*1. / in->nSites; } return dist; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL SetMyTaxonomy(CPNode *node) { // calc the taxonomy of this node if (taxonomy == NULL) return FALSE; if (node == NULL) return FALSE; if (!node->IsBranchNode()) return FALSE; string common; string tax; LPCSTR def = "not set"; common = node->attrs.GetString(ATTR_TAXLABEL, def); if (common != def) return TRUE; common.clear(); for (CPNodeListIter iter=node->edges.begin() ; iter != node->edges.end() ; ++iter) { CPNode *child = *iter; if (node->IsBranchNode()) { SetMyTaxonomy(child); } CSequenceItem *seq = taxonomy->GetSequence(child->title.c_str()); if (seq != NULL) { tax = seq->hdr; int pos = tax.find_first_of('\t'); if (pos < 20) tax = tax.substr(pos+1,tax.length()); TrimRight(tax, "\n\r\t "); if (tax.empty()) { string name = GetNodeName(child); DisplayL("No Taxnomy for [%s][%s]\n", name.c_str(), child->title.c_str()); } } else if ((seq->hdr == NULL) || (seq->hdr)) { string name = GetNodeName(child); DisplayL("No Taxnomy for [%s][%s]\n", name.c_str(), child->title.c_str()); } if (common.empty()) common = tax; else if (!tax.empty()) { // calc how much is the same between two list int i; for (i=0 ; (i < common.length()) && (i < tax.length()) ; ++i) { if (common[i] != tax[i]) break; } if (i > 0) common = common.substr(0,i); else common.clear(); } } if (tax.empty()) { string name = GetNodeName(node); DisplayL("No Taxnomy for [%s][%s]\n", name.c_str(), node->title.c_str()); } node->attrs.Add(ATTR_TAXLABEL, common); CSequenceItem *seq = new CSequenceItem(node->title.c_str(), -1, 0); //, common.GetLength(), common); seq->AllocateSeqHeader(common.length()+1); strcpy(seq->hdr, common.c_str()); CSequenceListIter iter = taxonomy->seqlist.find(seq->name); if (iter != taxonomy->seqlist.end()) { delete (*iter).second; } taxonomy->seqlist[seq->name] = seq; return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// #define CORE_NAME1 "CORE_NAME1" #define CORE_NAME2 "CORE_NAME2" // routine to mark the branch nodes with multiple subtrees with core node int CalcCoreBranches(CPNode *node, CSequenceFile *core_seq) { int count = 0; if (node == NULL) return count; if (node->IsBranchNode()) { // for each child // check to see if it has a core sequence string core1; string core2; CPNodeList &children = node->edges; for (CPNodeListIter iter=children.begin() ; iter != children.end() ; ++iter) { CPNode *child = *iter; if (CalcCoreBranches(child, core_seq) > 0) { ++count; string name = child->attrs.GetString(CORE_NAME1); if (core1.empty()) core1 = name; else core2 = name; } } node->SetAttr(CORE_NAME1, core1.c_str()); node->SetAttr(CORE_NAME2, core2.c_str()); } else { // check to see if the node is in the core sequences string name = GetNodeName(node); if (core_seq->GetSeq(name.c_str()) != NULL) { ++count; // found in core sequence list node->SetAttr(CORE_NAME1, name); } } return count; } // routine to find closest ancestor marked with core multiple core branches // routine to find branch node containing two given core nodes CPNode *FindBranchContaining(CPTree *tree, LPCSTR one, LPCSTR two) { if ((one == NULL) || (two == NULL)) return NULL; // find the node for each name given CPNode *node_one = tree->Find(one); if (node_one == NULL) return NULL; CPNode *node_two = tree->Find(two); if (node_two == NULL) return NULL; // Create list of ancestors for each node CPNodeList ancestors1; CPNodeList ancestors2; node_one->GetAncestors(ancestors1, FALSE); // ordered from root to direct parent node_two->GetAncestors(ancestors2, FALSE); // ordered from root to direct parent // Find the last (lowest in tree) common ancestor int i = 0; while ((i < ancestors1.size()) && (i < ancestors2.size()) && (ancestors1[i] == ancestors2[i])) ++i; // ith position is first difference if (i == 0) return NULL; return ancestors1[i-1]; } /////////////////////////////////////////////////////////////////////////////////////////////////// // routine to calc the distance between two given branch nodes double DistanceBetween(CPNode *one, CPNode *two) { double dist = 0; if ((one == NULL) || (two == NULL)) return INT_MAX; // Create list of ancestors for each node CPNodeList ancestors1; CPNodeList ancestors2; one->GetAncestors(ancestors1, FALSE); // ordered from root to direct parent two->GetAncestors(ancestors2, FALSE); // ordered from root to direct parent // Find the last (lowest in tree) common ancestor int i = 0; while ((i < ancestors1.size()) && (i < ancestors2.size()) && (ancestors1[i] == ancestors2[i])) ++i; // ith position is first difference // Distance is the number of branches from each node to common ancestor // dist += (ancestors1.size() - i); // distance to common ancestor from node one // dist += (ancestors2.size() - i); // distance to common ancestor from node two while ((i < ancestors1.size()) || (i < ancestors2.size())) { if (i < ancestors1.size()) dist += ancestors1[i]->attrs.GetDouble(ATTR_DISTANCE); if (i < ancestors2.size()) dist += ancestors2[i]->attrs.GetDouble(ATTR_DISTANCE); ++i; } return dist; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Compare the position of insertion to the original position in a full tree // name - name of inserted node // parent - node in coreTree where "name" node has been inserted // origTree - original full tree containing correct position for "name" node // coreTree - core tree in which parent is a member // Returns the distance from current position (parent) to correct position // double ComparePosition(LPCSTR name, CPNode *parent, CPTree *origTree, CPTree *coreTree) { double dist = -1; // Find the position in the original tree CPNode *orig = origTree->Find(name); // Find the first parent with at least 2 branchs with core sequences string core2; while (core2.empty() && (orig != NULL)) { orig = orig->parent; if (orig != NULL) core2 = orig->attrs.GetString(CORE_NAME2); } if (orig == NULL) { //DisplayL("Could not find original position for [%s]\n", name); return -3; // did not find original position } // Find the two core names associated with core ancestor string core1 = orig->attrs.GetString(CORE_NAME1); // Find same core ancestor in core tree CPNode *core = FindBranchContaining(coreTree, core1.c_str(), core2.c_str()); if (core == NULL) { DisplayL("Could not find core position for [%s][%s]\n", core1.c_str(), core2.c_str()); return -2; // did not find core position } // if parent is not a branch node, get parent's parent if (!parent->IsBranchNode()) parent = parent->parent; // Calc distance between core ancestor and insertion point dist = DistanceBetween(parent, core); //DisplayL("Distance error [%20.20s] = %d\n", name, dist); return dist; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Compare the position of insertions to the original position in a full tree void ComparePositions(CInsertPosArray &inserts, CPTree *origTree, CPTree *coreTree) { for (int i=0 ; i < inserts.size() ; ++i) { string name = inserts[i]->seq->name; DisplayL("======================================================================\n"); DisplayL("\nDistance to Insertion: [%20.20s] [%5d sites]\n", name.c_str(), inserts[i]->best.list.size()); if (inserts[i]->best.list.size() == 0) { DisplayL("\tNO MATCHES found for [%s]\n", name.c_str()); continue; } CBestList::iterator iterB = inserts[i]->best.list.begin(); for (iterB=inserts[i]->best.list.begin() ; iterB != inserts[i]->best.list.end() ; ++iterB) { CPNode *parent = iterB->node; string pname = GetNodeName(parent); int dist = ComparePosition(name.c_str(), parent, origTree, coreTree); DisplayL("\tDistance error from [%20.20s] = %d\n", pname.c_str(), dist); } } } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL FullTree_Initialization() { if (tree == NULL) return FALSE; if (treeSeqfile == NULL) return FALSE; if (fullTreeName == NULL) return FALSE; // Read in original tree DisplayL("Reading Newick Tree: [%s]\n", fullTreeName); fullTree = ReadNewickTree(fullTreeName); if (fullTree == NULL) { DisplayL("Error accessing Newick Tree file [%s]\n", fullTreeName); return FALSE; } DisplayL("Newick Tree Read Completed: %d taxa\n", (fullTree->nodeList.size()+1)/2); // Set the core names into ancestors CalcCoreBranches(fullTree->root, treeSeqfile); return TRUE; } void TestInsertPositions() { if (inserts.size() == 0) return; if (fullTree == NULL) { if (!FullTree_Initialization()) return; } ComparePositions(inserts, fullTree , tree); } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// ParsInsert.h0000644000076500000240000000547211645204274013210 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : ParsInsert.h // Purpose : Parsimonious Insertion of unclassified seqeunces into Phylogenetic Tree // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef PARS_INSERT_H #include "SeqList.h" #include "ParsimonySet.h" #define RC_ERROR_OPTIONS -1000 // Error in the command line options #define RC_ERROR_CMDLINE -1001 // Error not enough parameters supplied #define RC_ERROR_MASKFILE -1002 // Error accessing mask file #define RC_ERROR_TAXFILE -1003 // Error accessing taxonomy file #define RC_ERROR_TREEFILE -1004 // Error accessing newick tree file #define RC_ERROR_TREESEQ -1005 // Error accessing tree seq for tree #define RC_ERROR_TREESEQ_MISSING -1006 // Error could not find tree leaf in sequences #define RC_ERROR_NO_INSERT_SEQ -1007 // Error no insertion sequences to process #define RC_ERROR_ #define RC_ERROR_ #define RC_ERROR_ /////////////////////////////////////////////////////////////////////////////////////////////////// class CInsertPos // class stores a possible seqeunce insertion location into a tree { public: CSequenceItem *seq; // sequence being inserted int nSites; // number of active sites being scored CParsimonySet pars; // parsimony sequence for insertion CBestLocation best; // location with best match public: CInsertPos() { seq = NULL; nSites = 0; } ~CInsertPos() { seq = NULL; best.list.clear(); } }; typedef vector CInsertPosArray; /////////////////////////////////////////////////////////////////////////////////////////////////// #endif //PARS_INSERT_H ParsimonySet.h0000644000076500000240000002561011645204274013547 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : ParsimonySet.h // Purpose : Handles the parsimony functions for ParsInsert // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(__PARS_SET_H__) #define __PARS_SET_H__ #include "Knox_Stddef.h" #include #include #include using namespace std; /////////////////////////////////////////////////////////////////////////////////////////////////// class CParsimonySet { public: BYTE *data; int len; int start; int end; int nSeg; BYTE *segCounts; public: CParsimonySet() { data = NULL; len = 0; start = -1; end = -1; nSeg = 0; segCounts = NULL; } CParsimonySet(const CParsimonySet *other) { data = NULL; len = other->len; start = other->start; end = other->end; nSeg = 0; segCounts = NULL; Allocate(len); memcpy(data, other->data, len); } ~CParsimonySet() { Release(); len = 0; } void Release() { if (data != NULL) delete [] data; data = NULL; if (segCounts != NULL) delete [] segCounts; segCounts = NULL; } BOOL Allocate(int _len) { if (data != NULL) Release(); len = _len; data = new BYTE[len]; memset(data, 0, sizeof(BYTE)*len); return TRUE; } BOOL Convert(LPCSTR seq) { if (seq == NULL) return FALSE; Allocate(strlen(seq)); // check to see if this is bits or nucleotides int span = 0; for (LPCSTR s=seq ; *s != 0 ; ++s) if (isxdigit(*s)) ++span; BOOL bits = (span > len/2); for (int i=0 ; *seq != 0 ; ++seq,++i) { BYTE val = 0; if (bits) { switch (toupper(*seq)) { case '1': val = 1; break; case '2': val = 2; break; case '3': val = 3; break; case '4': val = 4; break; case '5': val = 5; break; case '6': val = 6; break; case '7': val = 7; break; case '8': val = 8; break; case '9': val = 9; break; case 'A': val = 10; break; case 'B': val = 11; break; case 'C': val = 12; break; case 'D': val = 13; break; case 'E': val = 14; break; case 'F': val = 15; break; } } else { /* A Adenosine C Cytosine G Guanine T Thymidine U Uracil R G A (puRine) Y T C (pYrimidine) K G T (Ketone) M A C (aMino group) S G C (Strong interaction) W A T (Weak interaction) B G T C (not A) (B comes after A) D G A T (not C) (D comes after C) H A C T (not G) (H comes after G) V G C A (not T, not U) (V comes after U) N A G C T (aNy) X masked - gap of indeterminate length */ #define rA 0x01 #define rC 0x02 #define rG 0x04 #define rT 0x08 switch (toupper(*seq)) { case 'A': val = rA; break; case 'C': val = rC; break; case 'G': val = rG; break; case 'T': val = rT; break; case 'U': val = rT; break; case 'R': val = rA | rG; break; case 'Y': val = rC | rT; break; case 'K': val = rG | rT; break; case 'M': val = rA | rC; break; case 'S': val = rG | rC; break; case 'W': val = rA | rT; break; case 'B': val = rG | rC | rT; break; case 'D': val = rA | rG | rT; break; case 'H': val = rA | rC | rT; break; case 'V': val = rA | rC | rG; break; case 'N': val = rA | rC | rG | rT; break; case 'X': val = 0; break; case '.': break; case '-': break; default: if (DEBUG) printf("%c", toupper(*seq)); } } data[i] = val; } SetEnds(); return TRUE; } BOOL Union(CParsimonySet *other) { if (other == NULL) return FALSE; if (other->len == 0) return FALSE; if (data == NULL) Allocate(other->len); for (int i=0 ; (i < len) && (i < other->len) ; ++i) { data[i] |= other->data[i]; } return TRUE; } BOOL Intersect(CParsimonySet *other) { if (other == NULL) return FALSE; if (data == NULL) { Allocate(other->len); memcpy(data, other->data, other->len); } else for (int i=0 ; (i < len) && (i < other->len) ; ++i) { data[i] &= other->data[i]; } return TRUE; } int Set(CParsimonySet *unionSet, CParsimonySet *intersectSet) { int cost = 0; if (unionSet == NULL) return cost; if (intersectSet == NULL) return cost; if (data == NULL) Allocate(unionSet->len); for (int i=0 ; (i < len) && (i < unionSet->len) && (i < intersectSet->len) ; ++i) { data[i] = intersectSet->data[i]; if (data[i] == 0) { if (unionSet->data[i] != 0) // check for both being gaps { cost += 1; data[i] = unionSet->data[i]; } } } SetEnds(); return cost; } int Force(CParsimonySet *parentSet) { if (parentSet == NULL) return 0; if (data == NULL) return 0; // LPSTR str; // parentSet->BuildString(str, -1); // DisplayL("Parent: [%200.200s]\n", str); // BuildString(str, -1); // DisplayL("Child: [%200.200s]\n", str); int count = 0; for (int i=0 ; (i < len) && (i < parentSet->len) && (i < len) ; ++i) { BYTE orig = data[i]; // BYTE p = parentSet->data[i]; // if ((p != orig) && p) // ++count; BYTE d = parentSet->data[i] & data[i]; if (d != 0) data[i] = d; if (data[i] != orig) ++count; } // DisplayL("Updated:[%200.200s]\n\n", str); // free(str); return count; } void SetEnds() { start = -1; end = len; if (data == NULL) return; for (int i=0 ; i < len ; ++i) { if (data[i] != 0) { if (start < 0) start = i; end = i; } } } LPSTR BuildString(LPSTR &str, int str_len) { if ((str == NULL) || (str_len < 1)) { str_len = len + 1; str = (LPSTR)calloc(str_len,1); } str[0] = 0; for (int i=0 ; i < len ; ++i) { char x[10]; sprintf(x,"%X", data[i]); strcat(str, x); } return str; } void BuildSets(LPSTR str, int str_len) { char x[10]; str[0] = 0; strcat(str, "["); for (int i=0 ; i < len ; ++i) { x[0] = 0; if (data[i]&1) strcat(x, "A"); if (data[i]&2) strcat(x, "C"); if (data[i]&4) strcat(x, "G"); if (data[i]&8) strcat(x, "T"); if (data[i] == 0) strcat(x, "."); if (strlen(x) > 1) { strcat(str, "{"); strcat(str, x); strcat(str, "}"); } else strcat(str, x); } strcat(str, "]"); } // SEGMENT_SIZE must be 256 or less to use BYTE counts #define SEGMENT_SIZE 16 int BuildSegCounts(char *mask=NULL) { if (segCounts != NULL) { delete [] segCounts; segCounts = NULL; nSeg = 0; } if (data == NULL) return -1; nSeg = (len + SEGMENT_SIZE-1) / SEGMENT_SIZE; segCounts = new BYTE[nSeg]; memset(segCounts, 0, sizeof(BYTE)*nSeg); int seg = 0; for (int j=0 ; (j < len) ; j+=SEGMENT_SIZE) { // count items in segment int n = 0; for (int k=0 ; (k < SEGMENT_SIZE) && (k+j < len) ; ++k) { if ((mask == NULL) || (mask[j+k] != 0)) if (data[j+k] != 0) ++n; } if (n > 255) n = 255; segCounts[seg++] = n; } return nSeg; } int CompareSegments(CParsimonySet *other) { // compare the counts, looking for known error int s = (start + SEGMENT_SIZE-1) / SEGMENT_SIZE; int e = (end + 1) / SEGMENT_SIZE; // BYTE *p1 = &segCounts[s]; // BYTE *p2 = &other->segCounts[s]; int indel = 0; for (int k=s ; (k < nSeg) && (k < e) ; ++k) { indel += abs(segCounts[k] - other->segCounts[k]); // indel += abs(*p1-*p2); // ++p1; // ++p2; } return indel; } void TraceSegments(LPCSTR label) { if (segCounts == NULL) return; DisplayL("%s [", label); for (int k=0 ; k < nSeg ; ++k) DisplayL(" %3d", segCounts[k]); DisplayL("]\n"); } void Trace(LPCSTR label, LPCSTR str) { if (DEBUG) { printf("%s", label); while (strlen(str) > 500) { printf("%.500s", str); str += 500; } printf("%s\n", str); } } }; /////////////////////////////////////////////////////////////////////////////////////////////////// typedef map CParsimonyList; typedef CParsimonyList::iterator CParsimonyListIter; /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// #endif README.txt0000644000076500000240000001116711652364627012450 0ustar davidknoxstaff############################################################################### # # ParsInsert # # ParsInsert efficiently produces both a phylogenetic tree and taxonomic # classification for sequences for microbial community sequence analysis. # ############################################################################### Summary: ParsInsert is a C++ implementation of Parsimonious Insertion. The algorithm exploits the knowledge provided by publicly available curated phylogenetic trees to efficiently insert new sequences and infer their taxonomic classification. The ParsInsert placement of new sequences in the tree is deterministic which allows for distributed processing to quickly handle millions of reads. Availability: ParsInsert source code and documentation are available at: http://parsinsert.sourceforge.net Contact: david.knox@colorado.edu ############################################################################### ## ## Developer : David Knox (david.knox@colorado.edu) Jan 2011 ## Copyright : Copyright (C) 2007-2011 David Knox ## ## Web site : http://parsinsert.sourceforge.net/ ## ############################################################################### ## This file is part of ParsInsert. ## ## ParsInsert is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## ParsInsert is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with ParsInsert. If not, see . ############################################################################### ########################## Installation Instructions: ########################## 1. Download and unzip the distribution file to a directory of your choice. 2. Compile the application using the following commands from the installation directory: make this will compile the application using the 'gcc' compiler. 3. Test the application. There is a testing data set in the TestData directory. make TEST will run the application on the test data and compare the results to preiously run test and results are reported. ############################## Sample command for ParsInsert: ############################## ParsInsert -x rdp.taxonomy -t core_set.tree -s core_set_aligned.fasta unclassified_seq.fasta ######## Support: ######## Please send any comments, bug reports or questions to david.knox@colorado.edu ################################### The directory contains these files: ################################### AttrList.cpp - Source to manage sets of key,value pairs AttrList.h Attrs.h - Predefined attribute names for Phylogenetic Trees GNU_license_agpl.txt - License Agreement (GNU AFFERO GENERAL PUBLIC LICENSE) Knox_Stddef.cpp - Set of routines and old habit data types Knox_Stddef.h makefile - rules for making application and performing tests ParsimonySet.h - Handles the parsimony functions ParsInsert.cpp - Source for main algorithm and application ParsInsert.h PNode.cpp - Source to manage Phylogenetic Tree Node PNode.h ReleaseNotes.txt - Release Notes for each release SeqList.cpp - Source to manage sequence file functions SeqList.h Taxonomy.cpp - Source to manage heirarchy of taxonomic classifications Taxonomy.h TestData - Data used for testing the application installation core_rdp.fasta - sequences for taxa in core tree core_rdp.ntree - core tree lanemask.txt - Lane Mask for important positions in the aligned sequences rdp.taxonomy - taxonomy of taxa in core tree set100.fasta - small test set set1000.fasta - larger test set set1000.results - results from ParsInsert on larger test set short1000_NAST.fasta - sample set of short reads aligned short1000_unaligned.fasta - sample set of short reads unaligned TaxonomyCounts.txt - List of the taxonomys in the core tree ################################### ################################### ReleaseNotes.txt0000644000076500000240000000545511652364243014101 0ustar davidknoxstaff############################################################################### # # ParsInsert # # ParsInsert efficiently produces both a phylogenetic tree and taxonomic # classification for sequences for microbial community sequence analysis. # ############################################################################### Summary: ParsInsert is a C++ implementation of Parsimonious Insertion. The algorithm exploits the knowledge provided by publicly available curated phylogenetic trees to efficiently insert new sequences and infer their taxonomic classification. The ParsInsert placement of new sequences in the tree is deterministic which allows for distributed processing to quickly handle millions of reads. Availability: ParsInsert source code and documentation are available at: http://parsinsert.sourceforge.net Contact: david.knox@colorado.edu ############################################################################### ## ## Developer : David Knox (david.knox@colorado.edu) Jan 2011 ## Copyright : Copyright (C) 2007-2011 David Knox ## ## Web site : http://parsinsert.sourceforge.net/ ## ############################################################################### ## This file is part of ParsInsert. ## ## ParsInsert is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## ParsInsert is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with ParsInsert. If not, see . ############################################################################### ########################## Release Notes: ########################## Version: 1.01 Inital Release ########################## Version: 1.02 10/11/11 - Added '-p' option to print comment in each leaf node (default is off) - Fixed bug: 0 execution time causing divide by zero ########################## Version: 1.03 10/17/11 - Added hack code to parse attributes for root node ########################## Version: 1.04 10/27/11 - Bug Fix. Building new branch in insertion tree, corrected branch lengths to new nodes. - Added -D param to set tree branch length precision, Default to 5. - Added Branch lengths written to given precision. ########################## ########################## SeqList.cpp0000644000076500000240000003557711645204265013046 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : SeqList.cpp // Purpose : Handles the sequence file functions for ParsInsert // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #include "SeqList.h" #include "PNode.h" #include #include using namespace std; /////////////////////////////////////////////////////////////////////////////////////////////////// bool operator<(const CBestLocationEntry& x, const CBestLocationEntry& y) { // sort by score first if (x.score != y.score) return x.score < y.score; // check type of object if (x.node->IsBranchNode() && !y.node->IsBranchNode()) return false; if (!x.node->IsBranchNode() && y.node->IsBranchNode()) return true; // whoever's taxonomy is longer is first in list if (x.tax.empty() && !y.tax.empty()) return false; if (!x.tax.empty() && y.tax.empty()) return true; return x.levels > y.levels; } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// int CBestLocation::default_len = 10; /////////////////////////////////////////////////////////////////////////////////////////////////// int CBestLocation :: WorstScore() { // return the current worst score if (list.size() < len) return INT_MAX; else return (list.end()-1)->score; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CBestLocation :: Add(int score, CPNode *node, LPCSTR taxonomy) { list.push_back(CBestLocationEntry(score, node, taxonomy)); sort(list.begin(), list.end()); if (list.size() > len) list.pop_back(); } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceItem :: CSequenceItem() { name.clear(); offset = -1; len = -1; data = NULL; hdr = NULL; } /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceItem :: CSequenceItem(LPCSTR _name, long _offset, int _len, LPCSTR _data) { name = _name; offset = _offset; len = _len; data = NULL; hdr = NULL; if (_data != NULL) { if (strlen(_data) > len) len = strlen(_data); if (len > 0) { AllocateSeqData(); strcpy(data, _data); } } } /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceItem :: ~CSequenceItem() { if (data != NULL) ReleaseSeqData(); if (hdr != NULL) ReleaseSeqHeader(); } /////////////////////////////////////////////////////////////////////////////////////////////////// LPCSTR CSequenceItem :: GetSeqData() { return data; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CSequenceItem :: AllocateSeqData() { if (data != NULL) ReleaseSeqData(); if (len > 0) { data = new char[len+1]; memset(data, 0, len+1); } return (data != NULL); } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CSequenceItem :: ReleaseSeqData() { if (data != NULL) { delete [] data; data = NULL; } return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CSequenceItem :: AllocateSeqHeader(int size) { if (hdr != NULL) ReleaseSeqHeader(); hdr = new char[size]; hdr[0] = 0; return (hdr != NULL); } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CSequenceItem :: ReleaseSeqHeader() { if (hdr != NULL) { delete [] hdr; hdr = NULL; } return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// LPCSTR CSequenceItem :: ReadSeqHeader(FILE *f) { if (f == NULL) return NULL; fseek(f, offset, SEEK_SET); if (ftell(f) != offset) return NULL; // assuming FASTA file format // skip the first line, seq description char buffer[96*1024]; fgets(buffer, sizeof(buffer)-1, f); // if (buffer[0] != '>') return NULL; if (strlen(buffer) > 0) { AllocateSeqHeader(strlen(buffer)+1); if (hdr != NULL) strcpy(hdr, buffer); } //TRACE("READ %d chars",strlen(data)); return hdr; } /////////////////////////////////////////////////////////////////////////////////////////////////// LPCSTR CSequenceItem :: ReadSeqData(FILE *f) { if (f == NULL) return NULL; fseek(f, offset, SEEK_SET); if (ftell(f) != offset) return NULL; // assuming FASTA file format // skip the first line, seq description char buffer[MAX_SEQ_SIZE]; fgets(buffer, sizeof(buffer)-1, f); // if (buffer[0] != '>') return NULL; if (strlen(buffer) > 0) { AllocateSeqHeader(strlen(buffer)+1); if (hdr != NULL) strcpy(hdr, buffer); } if (len > 0) { AllocateSeqData(); // while (we have not found the next entry) // add new data to sequence while ((fgets(buffer, sizeof(buffer)-1, f) != NULL) && (buffer[0] != '>')) { //TRACE("===%s", buffer); // add alignment data to sequence string int i; int j; for (i=0 ; (i < sizeof(buffer)) && isspace(buffer[i]) && (buffer[i] != 0) ; ++i) ; /* find first non-whitespace */ for (j=i ; (j < sizeof(buffer)) && !isspace(buffer[j]) && (buffer[j] != 0) ; ++j) ; /* find next whitespace */ buffer[j] = 0; if (strlen(data)+strlen(&buffer[i]) <= len) strcat(data, &buffer[i]); } } //TRACE("READ %d chars",strlen(data)); return data; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CSequenceItem :: WriteSeqData(FILE *f) { if (f == NULL) return FALSE; if (data == NULL) return FALSE; offset = ftell(f); fprintf(f, ">%s" , name.c_str()); for (int i=0 ; i < len ; i+=50) { if (i%50 == 0) fprintf(f, "\n "); int count = min(len-i, 50); fwrite(&data[i], 1, count, f); } fprintf(f, "\n"); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// int CSequenceFile::progressCount = 20000; int CSequenceFile::verbose = 0; /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceFile :: CSequenceFile(LPCSTR _fname, int size, int hashsize) { seqCount = 0; f = NULL; seqArray = NULL; seqN = size; if (seqN > 0) { int nbytes = seqN * sizeof(CSequenceItem*); seqArray = (CSequenceItem**)malloc(nbytes); memset(seqArray, 0, nbytes); } //seqlist.InitHashTable(hashsize); if (_fname != NULL) { Open(_fname); } } /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceFile :: ~CSequenceFile() { if (f != NULL) fclose(f); f = NULL; // delete all the seqs for (int i=0 ; i < seqN ; ++i) if (seqArray[i] != NULL) delete seqArray[i]; if (seqArray != NULL) { delete seqArray; seqArray = NULL; } //// memset(seqArray, 0, sizeof(seqArray)); for (CSequenceListIter iter=seqlist.begin() ; iter != seqlist.end() ; ++iter) { delete ((*iter).second); } seqlist.clear(); } /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceItem * CSequenceFile :: GetSequenceHeader(LPCSTR name) { CSequenceItem *seq = this->GetSeq(name); if ((seq != NULL) && (seq->hdr == NULL)) seq->ReadSeqHeader(f); return seq; } /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceItem * CSequenceFile :: GetSequence(LPCSTR name) { CSequenceItem *seq = this->GetSeq(name); if ((seq != NULL) && (seq->data == NULL)) seq->ReadSeqData(f); return seq; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CSequenceFile :: Open(LPCSTR _fname, LPCSTR mode) { if (f != NULL) Close(); fname = _fname; f = fopen(fname.c_str(), mode); return (f != NULL); } /////////////////////////////////////////////////////////////////////////////////////////////////// void CSequenceFile :: Close() { if (f != NULL) fclose(f); f = NULL; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CSequenceFile :: ResetSeqIterator() { seqIter = seqlist.begin(); posArray = 0; } /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceItem* CSequenceFile :: GetNextSeq() { if (seqIter != seqlist.end()) { CSequenceItem *item = (*seqIter).second; ++seqIter; return item; } while (posArray < seqN) { CSequenceItem *seq = seqArray[posArray]; ++posArray; if (seq != NULL) return seq; } return NULL; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CSequenceFile :: ReadSequenceIndexFile(LPCSTR filename) { FILE *f = fopen(filename, "r"); if (f == NULL) return 0; // Index file format // offset len name char buffer[MAX_SEQ_SIZE]; //int seqlen = 0; CSequenceItem *seq = NULL; int count = 0; while (fgets(buffer, sizeof(buffer)-1, f) != NULL) { char *sep = strchr(buffer, '\t'); if (sep == NULL) continue; *sep = 0; ++sep; long offset = atol(buffer); int len = atoi(sep); sep = strchr(sep, '\t'); if (sep == NULL) continue; *sep = 0; ++sep; char *name = sep; sep = strchr(sep, '\n'); if (sep == NULL) continue; *sep = 0; sep = strchr(name, '\r'); if (sep != NULL) *sep = 0; seq = new CSequenceItem(name, offset, len); if (isdigit(buffer[0])) { int id = atoi(name); if ((id > 0) && (id < sizeof(seqArray)/sizeof(CSequenceItem*))) { if (seqArray[id] != NULL) { delete seqArray[id]; --seqCount; // TRACE(" *** Replaced %d with new location\n", id); } seqArray[id] = seq; ++seqCount; } else seqlist[seq->name] = seq; } else { seqlist[seq->name] = seq; } ++count; if (count%progressCount == 0) { if (verbose) DisplayT("Loading sequence %d [%s]\n", count, name); else DisplayT("Loading sequence %d\n", count); } } DisplayT("Loaded %d sequences from [%s]\n", count, filename); fclose(f); return count; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CSequenceFile :: ReadTaxonomyFile() { if (f == NULL) return 0; fseek(f, 0, SEEK_SET); // rewind char buffer[MAX_SEQ_SIZE]; int offset = ftell(f); CSequenceItem *seq = NULL; seqCount = 0; while (fgets(buffer, sizeof(buffer)-1, f) != NULL) { int j; for (j=1 ; (j < sizeof(buffer)) && !isspace(buffer[j]) && (buffer[j] != 0) ; ++j) ; /* find next whitespace */ buffer[j] = 0; seq = new CSequenceItem(buffer, offset, 0); seqlist[seq->name] = seq; if (++seqCount%progressCount == 0) if (verbose) DisplayT("Loading sequence %d [%s]\n", seqCount, seq->name.c_str()); else DisplayT("Loading sequence %d\n", seqCount); offset = ftell(f); } return seqCount; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CSequenceFile :: ReadSequenceFile(int type) { if (f == NULL) return 0; fseek(f, 0, SEEK_SET); // rewind char buffer[MAX_SEQ_SIZE]; int seqlen = 0; int offset = ftell(f); CSequenceItem *seq = NULL; //seqCount = 0; while (fgets(buffer, sizeof(buffer)-1, f) != NULL) { if (buffer[0] == '>') { // found a new entry // update last entry if (seq != NULL) { seq->len = seqlen; if (seqCount%progressCount == 0) DisplayT("Loading sequence %d [%s]\n", seqCount, seq->name.c_str()); } // extract taxa name // find first whitespace int i; int j; for (i=1 ; (i < sizeof(buffer)) && (isspace(buffer[i])||((buffer[i] == '>'))) && (buffer[i] != 0) ; ++i) ; /* find first non-whitespace */ for (j=i ; (j < sizeof(buffer)) && !isspace(buffer[j]) && (buffer[j] != 0) ; ++j) ; /* find next whitespace */ buffer[j] = 0; seq = new CSequenceItem(&buffer[i], offset, 0); if (seqlist.find(seq->name) != seqlist.end()) DisplayL("Duplicate sequence found [%s]\n", seq->name.c_str()); else ++seqCount; seqlist[seq->name] = seq; seqlen = 0; } else { // update the sequence length int i; int j; for (i=0 ; (i < sizeof(buffer)) && isspace(buffer[i]) && (buffer[i] != 0) ; ++i) ; /* find first non-whitespace */ for (j=i ; (j < sizeof(buffer)) && !isspace(buffer[j]) && (buffer[j] != 0) ; ++j) ; /* find next whitespace */ seqlen += (j - i + 1); } offset = ftell(f); } if (seq != NULL) { seq->len = seqlen; DisplayT("Loading sequence %d [%s]\n", seqCount, seq->name.c_str()); } return seqCount; } /////////////////////////////////////////////////////////////////////////////////////////////////// CSequenceItem* CSequenceFile :: GetSeq(LPCSTR name) { int id = atoi(name); CSequenceItem *seq = NULL; if ((id > 0) && (id < sizeof(seqArray)/sizeof(CSequenceItem*))) seq = seqArray[id]; if (seq == NULL) seq = (CSequenceItem*)seqlist[name]; return seq; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CSequenceFile :: WriteSequence(CSequenceItem *seq) { if (f == NULL) return FALSE; if (seq == NULL) return FALSE; fseek(f, 0, SEEK_END); seq->WriteSeqData(f); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// SeqList.h0000644000076500000240000001156711645204274012504 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : SeqList.h // Purpose : Handles the sequence file functions for ParsInsert // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(__SEQLIST_H__) #define __SEQLIST_H__ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Knox_Stddef.h" #include #include #include using namespace std; #define MAX_SEQ_SIZE (64*1024) class CPNode; /////////////////////////////////////////////////////////////////////////////////////////////////// class CBestLocationEntry { public: CPNode *node; // pointer to node with best match int score; // score of match at this position string tax; // taxonomy assignd to this position int levels; // number of ranks in taxonomy public: CBestLocationEntry(int s, CPNode *n, LPCSTR t) { score = s; node = n; tax = t; levels = 0; if (!tax.empty()) { for (int i=0; i < tax.length() ; ++i) if (tax[i] == ';') ++levels; } } }; typedef vector CBestList; /////////////////////////////////////////////////////////////////////////////////////////////////// class CBestLocation { public: static int default_len; CBestList list; // list of best matches int len; // number of matches to keep public: CBestLocation(int _len=-1) { if (_len > 0) len = _len; else len = default_len; } void Add(int score, CPNode *node, LPCSTR t); int WorstScore(); }; /////////////////////////////////////////////////////////////////////////////////////////////////// class CSequenceItem { public: long offset; // offset in sequence file where sequence entry begins string name; // id from the fasta file int len; // length of the sequence data (sequence only) LPSTR data; // sequence string LPSTR hdr; // header line from fasta file public: CSequenceItem(); CSequenceItem(LPCSTR _name, long _offset, int _len, LPCSTR _data=NULL); ~CSequenceItem(); LPCSTR GetSeqData(); BOOL AllocateSeqData(); BOOL ReleaseSeqData(); BOOL AllocateSeqHeader(int size); BOOL ReleaseSeqHeader(); LPCSTR ReadSeqHeader(FILE *f); LPCSTR ReadSeqData(FILE *f); BOOL WriteSeqData(FILE *f); }; typedef map CSequenceList; typedef CSequenceList::iterator CSequenceListIter; /////////////////////////////////////////////////////////////////////////////////////////////////// class CSequenceFile { public: FILE *f; // file to read data string fname; // name of file opened int seqCount; // number of sequences used in array int seqN; // number of items allocated in array CSequenceItem* *seqArray; // array of sequence numbers CSequenceList seqlist; // map of name to sequence CSequenceListIter seqIter; // iterator to step thru map int posArray; // iterator position in array static int progressCount; // number of sequences between progress reports static int verbose; public: CSequenceFile(LPCSTR _fname=NULL, int size=MAX_SEQ_SIZE, int hashsize=10*1024); ~CSequenceFile(); CSequenceItem * GetSequence(LPCSTR name); CSequenceItem * GetSequenceHeader(LPCSTR name); BOOL Open(LPCSTR _fname, LPCSTR mode="r"); void Close(); int GetCount() { return seqCount; } int ReadSequenceIndexFile(LPCSTR filename); int ReadSequenceFile(int type); CSequenceItem *GetSeq(LPCSTR name); BOOL WriteSequence(CSequenceItem *seq); void ResetSeqIterator(); CSequenceItem *GetNextSeq(); int ReadTaxonomyFile(); }; #endif // __SEQLIST_H__ Taxonomy.cpp0000644000076500000240000001210511645204265013256 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : Taxonomy.cpp // Purpose : Handles the taxonomy functions for ParsInsert // // CTaxEntry: Class to manage heirarchy of taxonomic classifications // Count of number of occurances of given name at given rank // Keeps list of all entries that were defined to lower ranks // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #include "Taxonomy.h" /////////////////////////////////////////////////////////////////////////////////////////////////// CTaxEntry :: CTaxEntry(LPCSTR _name) { name = _name; count = 0; entries.clear(); } /////////////////////////////////////////////////////////////////////////////////////////////////// CTaxEntry :: ~CTaxEntry() { // release all the subentries for (CTaxEntryList::iterator iter=entries.begin() ; iter != entries.end() ; ++iter) { delete (*iter).second; } entries.clear(); } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CTaxEntry :: Add(LPCSTR tax, int votes) { // Add the first name in the taxonomy to this entry count += votes; if (strlen(tax) == 0) return TRUE; // strip next rank off string string subentry = tax; // assume whole string is this name string rest = ""; int len = strcspn(tax, ";/"); if (len < subentry.length()) { rest = subentry.substr(len+1); subentry = subentry.substr(0, len); } Trim(subentry, " \r\n\t"); // lookup in table to get entry CTaxEntry *ptr = entries[subentry]; if (ptr == NULL) { ptr = new CTaxEntry(subentry.c_str()); entries[subentry] = ptr; } // add rest to that entry ptr->Add(rest.c_str(), votes); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CTaxEntry :: Display(LPCSTR leader, int levels) { if (levels <= 0) return FALSE; --levels; if (leader != NULL) DisplayL("%s[%s] %d\n", leader, name.c_str(), count); string indent = leader; indent += " "; // display all the subentries for (CTaxEntryList::iterator iter=entries.begin() ; iter != entries.end() ; ++iter) { string key = (*iter).first; CTaxEntry *ptr = (*iter).second; ptr->Display(indent.c_str(), levels); } return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// int CTaxEntry :: FindBest(int threshPercent, CStringList& taxList) { // Find the best taxonomy with at least thresh count taxList.clear(); int thresh = count * threshPercent / 100; for (CTaxEntryList::iterator iter=entries.begin() ; iter != entries.end() ; ++iter) { string key = (*iter).first; CTaxEntry *ptr = (*iter).second; ptr->FindBestSubentry(thresh, "", taxList); } return taxList.size(); } /////////////////////////////////////////////////////////////////////////////////////////////////// void CTaxEntry :: FindBestSubentry(int thresh, LPCSTR lineage, CStringList& taxList) { // Find the best taxonomy with at least thresh count int ntax = 0; string myLineage = lineage; if (!myLineage.empty()) myLineage += ";"; myLineage += name; for (CTaxEntryList::iterator iter=entries.begin() ; iter != entries.end() ; ++iter) { string key = (*iter).first; CTaxEntry *ptr = (*iter).second; if (ptr->count < thresh) continue; ++ntax; ptr->FindBestSubentry(thresh, myLineage.c_str(), taxList); } if (ntax == 0) taxList.push_back(myLineage); // if no other lineage added, add my lineage } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// Taxonomy.h0000644000076500000240000000550711645204274012733 0ustar davidknoxstaff/////////////////////////////////////////////////////////////////////////////////////////////////// // File : Taxonomy.h // Purpose : Handles the taxonomy functions for ParsInsert // // CTaxEntry: Class to manage heirarchy of taxonomic classifications // Count of number of occurances of given name at given rank // Keeps list of all entries that were defined to lower ranks // // Developer : David Knox (david.knox@colorado.edu) Jan 2011 // Copyright : Copyright (C) 2007-2011 David Knox // // Web site : http://parsinsert.sourceforge.net/ // /////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of ParsInsert. // // ParsInsert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ParsInsert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ParsInsert. If not, see . /////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(__TAXONOMY_H__) #define __TAXONOMY_H__ #include "Knox_Stddef.h" #include using namespace std; /////////////////////////////////////////////////////////////////////////////////////////////////// class CTaxEntry; typedef map CTaxEntryList; class CTaxEntry // Class to manage heirarchy of taxonomic classifications { public: string name; // name of this item int count; // number of times this item seen CTaxEntryList entries; // list of entries for each sub-type public: CTaxEntry(LPCSTR _name); ~CTaxEntry(); BOOL Add(LPCSTR tax, int votes=1); // Add the first name in the taxonomy to this entry int FindBest(int threshPrecent, vector& taxList); // Find the best taxonomy with at least threshold count BOOL Display(LPCSTR leader, int levels=100); // Show entries in hierarical list protected: void FindBestSubentry(int thresh, LPCSTR lineage, CStringList& taxList); // Find the best taxonomy with at least thresh count // Recursive internal use // thresh is a raw count }; /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// #endif makefile0000644000076500000240000000321211652364753012442 0ustar davidknoxstaff# # Makefie for ParsInsert # # ParsInsert efficiently produces both a phylogenetic tree and taxonomic classification # for sequences for microbial community sequence analysis. # # This is a C++ implementation of the Parsimonious Insertion algorithm. # PROGRAM = ParsInsert OBJECTS = AttrList.o Knox_Stddef.o PNode.o SeqList.o Taxonomy.o ParsInsert.o CFLAGS = -g -O3 CC = g++ INCLUDES = LIBS = -lm -lc .SUFFIXES: .o .cpp .cpp.o: $(CC) $(CFLAGS) -c -o $@ $< all: $(PROGRAM) clean: rm -f $(PROGRAM) $(OBJECTS) *.fasta *.log *.results *.tree TEST_OBJECTS = PNode.o AttrList.o Knox_Stddef.o Test.o test: $(TEST_OBJECTS) $(CC) $(CFLAG) -o Test $(TEST_OBJECTS) $(LIBS) Knox_Stddef.o: Knox_Stddef.cpp Knox_Stddef.h $(PROGRAM): $(OBJECTS) $(CC) $(CFLAG) -o $(PROGRAM) $(OBJECTS) $(LIBS) TEST_DIR = ./TestData test_short = short1000_NAST test_set = set1000 TAXONOMY = $(TEST_DIR)/rdp.taxonomy TREE = $(TEST_DIR)/core_rdp.ntree TREE_SEQ = $(TEST_DIR)/core_rdp.fasta # create compressed version of the release RELEASE_VER = 1.04 RELEASE: tar -czf ../ParsInsert.$(RELEASE_VER).tgz * # use simple scoring function (-d0), threshold cutoff at 80% (-c80), only display best location (-n1) test_options = -d0 -c80 -n1 TEST: $(PROGRAM) rm -f $(test_set).fasta cp TestData/$(test_set).fasta . ./$(PROGRAM) $(test_options) \ -m $(TEST_DIR)/lanemask.txt\ -x $(TAXONOMY) \ -l $(test_set).log \ -o $(test_set).results \ -t $(TREE) \ -s $(TREE_SEQ) \ $(test_set).fasta diff $(test_set).results TestData/$(test_set).results echo Differences: diff $(test_set).results TestData/$(test_set).results | wc -l