packages feed

too-many-cells (empty) → 0.1.0.0

raw patch · 25 files changed

+4606/−0 lines, 25 filesdep +SVGFontsdep +aesondep +basesetup-changed

Dependencies added: SVGFonts, aeson, base, birch-beer, bytestring, cassava, colour, containers, deepseq, diagrams, diagrams-cairo, diagrams-graphviz, diagrams-lib, differential, directory, diversity, fgl, filepath, find-clumpiness, foldl, graphviz, hierarchical-clustering, hierarchical-spectral-clustering, hmatrix, inline-r, lens, managed, matrix-market-attoparsec, mltool, modularity, mtl, optparse-generic, palette, parallel, plots, safe, scientific, sparse-linear-algebra, spectral-clustering, split, statistics, streaming, streaming-bytestring, streaming-cassava, streaming-utils, streaming-with, terminal-progress-bar, text, text-show, too-many-cells, transformers, vector, vector-algorithms

Files

+ LICENSE view
@@ -0,0 +1,674 @@+                    GNU GENERAL PUBLIC LICENSE+                       Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++                            Preamble++  The GNU General Public License is a free, copyleft license for+software and other kinds of works.++  The licenses for most software and other practical works are designed+to take away your freedom to share and change the works.  By contrast,+the GNU General Public License is 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.  We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors.  You can apply it to+your programs, too.++  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.++  To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights.  Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++  For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received.  You must make sure that they, too, receive+or can get the source code.  And you must show them these terms so they+know their rights.++  Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++  For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software.  For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++  Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so.  This is fundamentally incompatible with the aim of+protecting users' freedom to change the software.  The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable.  Therefore, we+have designed this version of the GPL to prohibit the practice for those+products.  If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++  Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary.  To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++  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 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. Use with the GNU Affero General Public License.++  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 Affero 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 special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++  14. Revised Versions of this License.++  The Free Software Foundation may publish revised and/or new versions of+the GNU 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 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 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 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.++    {one line to give the program's name and a brief idea of what it does.}+    Copyright (C) {year}  {name of author}++    This program is free software: you can 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.++    This program is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program.  If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++  If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++    {project}  Copyright (C) {year}  {fullname}+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+    This is free software, and you are welcome to redistribute it+    under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License.  Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++  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 GPL, see+<http://www.gnu.org/licenses/>.++  The GNU General Public License does not permit incorporating your program+into proprietary programs.  If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library.  If this is what you want to do, use the GNU Lesser General+Public License instead of this License.  But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ app/Main.hs view
@@ -0,0 +1,965 @@+{- too-many-cells+Gregory W. Schwartz++Clusters single cell data.+-}++{-# LANGUAGE QuasiQuotes       #-}+{-# LANGUAGE BangPatterns      #-}+{-# LANGUAGE DataKinds         #-}+{-# LANGUAGE DeriveGeneric     #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports    #-}+{-# LANGUAGE TypeOperators     #-}+{-# LANGUAGE TupleSections     #-}++module Main where++-- Remote+import BirchBeer.ColorMap+import BirchBeer.Interactive+import BirchBeer.Load+import BirchBeer.MainDiagram+import BirchBeer.Plot+import BirchBeer.Types+import BirchBeer.Utility+import Control.Monad (when, unless, join)+import Control.Monad.Trans (liftIO)+import Control.Monad.Trans.Maybe (MaybeT (..))+import Data.Bool (bool)+import Data.Colour.SRGB (sRGB24read)+import Data.Matrix.MatrixMarket (readMatrix, writeMatrix)+import Data.Maybe (fromMaybe, isJust, isNothing)+import Data.Monoid ((<>))+import Data.Tree (Tree (..))+import Language.R as R+import Language.R.QQ (r)+import Math.Clustering.Hierarchical.Spectral.Types (getClusterItemsDend, EigenGroup (..))+import Math.Clustering.Spectral.Sparse (b1ToB2, B1 (..), B2 (..))+import Options.Generic+import System.IO (hPutStrLn, stderr)+import Text.Read (readMaybe)+import TextShow (showt)+import qualified "find-clumpiness" Types as Clump+import qualified Control.Lens as L+import qualified Data.Aeson as A+import qualified Data.ByteString.Lazy.Char8 as B+import qualified Data.Colour.Palette.BrewerSet as D+import qualified Data.Colour.Palette.Harmony as D+import qualified Data.Csv as CSV+import qualified Data.GraphViz as G+import qualified Data.Set as Set+import qualified Data.Text as T+import qualified Data.Text.Lazy.IO as T+import qualified Data.Vector as V+import qualified Diagrams.Backend.Cairo as D+import qualified Diagrams.Prelude as D+import qualified H.Prelude as H+import qualified Plots as D+import qualified System.Directory as FP+import qualified System.FilePath as FP+import qualified System.ProgressBar as Progress++-- Local+import TooManyCells.Differential.Differential+import TooManyCells.Differential.Types+import TooManyCells.Diversity.Diversity+import TooManyCells.Diversity.Load+import TooManyCells.Diversity.Plot+import TooManyCells.Diversity.Types+import TooManyCells.File.Types+import TooManyCells.MakeTree.Clumpiness+import TooManyCells.MakeTree.Cluster+import TooManyCells.MakeTree.Load+import TooManyCells.MakeTree.Plot+import TooManyCells.MakeTree.Print+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Load+import TooManyCells.Matrix.Preprocess+import TooManyCells.Matrix.Types+import TooManyCells.Matrix.Utility+import TooManyCells.Paths.Distance+import TooManyCells.Paths.Plot+import TooManyCells.Paths.Types++-- | Command line arguments+data Options+    = MakeTree { matrixPath :: [String] <?> "(PATH) The path to the input directory containing the matrix output of cellranger (matrix.mtx, genes.tsv, and barcodes.tsv) or, if genes-file and cells-file are not specified, or an input csv file containing gene row names and cell column names. If given as a list (--matrixPath input1 --matrixPath input2 etc.) then will join all matrices together. Assumes the same number and order of genes in each matrix, so only cells are added."+               , projectionFile :: Maybe String <?> "([Nothing] | FILE) The input file containing positions of each cell for plotting. Format is \"barcode,x,y\" and matches column order in the matrix file. Useful for 10x where a TNSE projection is generated in \"projection.csv\". Cells without projections will not be plotted. If not supplied, no plot will be made."+               , cellWhitelistFile :: Maybe String <?> "([Nothing] | FILE) The input file containing the cells to include. No header, line separated list of barcodes."+               , labelsFile :: Maybe String <?> "([Nothing] | FILE) The input file containing the label for each cell barcode, with \"item,label\" header."+               , delimiter :: Maybe Char <?> "([,] | CHAR) The delimiter for the csv file if using a normal csv rather than cellranger output and for --labels-file."+               , normalization :: Maybe String <?> "([TfIdfNorm] | UQNorm | MedNorm | TotalMedNorm | BothNorm | NoneNorm) Type of normalization before clustering. TfIdfNorm normalizes based on the prevalence of each feature. UQNorm normalizes each observation by the upper quartile non-zero counts of that observation. MedNorm normalizes each observation by the median non-zero counts of that observation. TotalMedNorm normalized first each observation by total count then by median of non-zero counts across features. BothNorm uses both normalizations (first TotalMedNorm for all analysis then additionally TfIdfNorm during clustering). NoneNorm does not normalize. Default is TfIdfNorm for clustering and NoneNorm for differential (which instead uses the recommended edgeR single cell preprocessing including normalization and filtering, any normalization provided here will result in edgeR preprocessing on top). Cannot use TfIdfNorm for any other process as NoneNorm will become the default."+               , eigenGroup :: Maybe String <?> "([SignGroup] | KMeansGroup) Whether to group the eigenvector using the sign or kmeans while clustering. While the default is sign, kmeans may be more accurate (but starting points are arbitrary)."+               , numEigen :: Maybe Int <?> "([1] | INT) Number of eigenvectors to use while clustering with kmeans. Takes from the second to last eigenvector. Recommended to start at 1 and work up from there if needed. May help offset the possible instability and inaccuracy of SVDLIBC."+               , minSize :: Maybe Int <?> "([1] | INT) The minimum size of a cluster. Defaults to 1."+               , maxStep :: Maybe Int <?> "([Nothing] | INT) Only keep clusters that are INT steps from the root. Defaults to all steps."+               , maxProportion :: Maybe Double <?> "([Nothing] | DOUBLE) Stopping criteria to stop at the node immediate after a node with DOUBLE proportion split. So a node N with L and R children will stop with this criteria at 0.5 if |L| / |R| < 0.5 or > 2 (absolute log2 transformed), that is, if one child has over twice as many items as the other child. Includes L and R in the final result."+               , minDistance :: Maybe Double <?> "([Nothing] | DOUBLE) Stopping criteria to stop at the node immediate after a node with DOUBLE distance. So a node N with L and R children will stop with this criteria the distance at N to L and R is < DOUBLE. Includes L and R in the final result."+               , smartCutoff :: Maybe Double <?> "([Nothing] | DOUBLE) Whether to set the cutoffs for --min-size, --max-proportion, and --min-distance based off of the distributions (median + (DOUBLE * MAD)) of all nodes. To use smart cutoffs, use this argument and then set one of the three arguments to an arbitrary number, whichever cutoff type you want to use. --min-size distribution is log2 transformed."+               , dendrogramOutput :: Maybe String <?> "([dendrogram.svg] | FILE) The filename for the dendrogram. Supported formats are PNG, PS, PDF, and SVG."+               , matrixOutput :: Maybe String <?> "([Nothing] | FOLDER) Output the filtered and normalized (not including TfIdfNorm) matrix in this folder."+               , drawLeaf :: Maybe String <?> "([DrawText] | DrawItem DrawItemType) How to draw leaves in the dendrogram. DrawText is the number of items in that leaf. DrawItem is the collection of items represented by circles, consisting of: DrawItem DrawLabel, where each item is colored by its label, DrawItem (DrawContinuous FEATURE), where each item is colored by the expression of FEATURE (corresponding to a feature name in the input matrix), DrawItem (DrawThresholdContinuous [(FEATURE, DOUBLE)]), where each item is colored by the binary high / low expression of FEATURE based on DOUBLE and multiple FEATUREs can be used to combinatorically label items (FEATURE1 high / FEATURE2 low, etc.), DrawItem DrawSumContinuous, where each item is colored by the sum of the post-normalized columns (use --normalization NoneNorm for UMI counts, default), and DrawItem DrawDiversity, where each node is colored by the diversity based on the labels of each item and the color is normalized separately for the leaves and the inner nodes. The default is DrawText, unless --labels-file is provided, in which DrawItem DrawLabel is the default. If the label or feature cannot be found, the default color will be black (check your spelling!)."+               , drawCollection :: Maybe String <?> "([PieChart] | PieRing | PieNone | CollectionGraph MAXWEIGHT THRESHOLD [NODE]) How to draw item leaves in the dendrogram. PieRing draws a pie chart ring around the items. PieChart only draws a pie chart instead of items. PieNone only draws items, no pie rings or charts. (CollectionGraph MAXWEIGHT THRESHOLD [NODE]) draws the nodes and edges within leaves that are descendents of NODE (empty list [] indicates draw all leaf networks) based on the input matrix, normalizes edges based on the MAXWEIGHT, and removes edges for display less than THRESHOLD (after normalization, so for CollectionGraph 2 0.5 [26], draw the leaf graphs for all leaves under node 26, then a edge of 0.7 would be removed because (0.7 / 2) < 0.5)."+               , drawMark :: Maybe String <?> "([MarkNone] | MarkModularity) How to draw annotations around each inner node in the tree. MarkNone draws nothing and MarkModularity draws a black circle representing the modularity at that node, darker black means higher modularity for that next split."+               , drawNodeNumber :: Bool <?> "Draw the node numbers on top of each node in the graph."+               , drawMaxNodeSize :: Maybe Double <?> "([72] | DOUBLE) The max node size when drawing the graph. 36 is the theoretical default, but here 72 makes for thicker branches."+               , drawMaxLeafNodeSize :: Maybe Double <?> "([--draw-max-node-size] | DOUBLE) The max leaf node size when drawing the graph. Defaults to the value of --draw-max-node-size."+               , drawNoScaleNodes :: Bool <?> "Do not scale inner node size when drawing the graph. Instead, uses draw-max-node-size as the size of each node and is highly recommended to change as the default may be too large for this option."+               , drawLegendSep :: Maybe Double <?> "([1] | DOUBLE) The amount of space between the legend and the tree."+               , drawLegendAllLabels :: Bool <?> "Whether to show all the labels in the label file instead of only showing labels within the current tree. The program generates colors from all labels in the label file first in order to keep consistent colors. By default, this value is false, meaning that only the labels present in the tree are shown (even though the colors are the same). The subset process occurs after --draw-colors, so when using that argument make sure to account for all labels."+               , drawPalette :: Maybe String <?> "([Set1] | Hsv | Ryb) Palette to use for legend colors. With high saturation in --draw-scale-saturation, consider using Hsv to better differentiate colors."+               , drawColors :: Maybe String <?> "([Nothing] | COLORS) Custom colors for the labels or continuous features. Will repeat if more labels than provided colors. For continuous feature plots, uses first two colors [high, low], defaults to [red, white]. For instance: --draw-colors \"[\\\"#e41a1c\\\", \\\"#377eb8\\\"]\""+               , drawScaleSaturation :: Maybe Double <?> "([Nothing] | DOUBLE) Multiply the saturation value all nodes by this number in the HSV model. Useful for seeing more visibly the continuous colors by making the colors deeper against a gray scale."+               , pca :: Maybe Double <?> "([Nothing] | DOUBLE) The percent variance to retain for PCA dimensionality reduction before clustering. Default is no PCA at all in order to keep all information."+               , noFilter :: Bool <?> "Whether to bypass filtering genes and cells by low counts."+               , filterThresholds :: Maybe String <?> "([(250, 1)] | (DOUBLE, DOUBLE)) The minimum filter thresholds for (MINCELL, MINFEATURE) when filtering cells and features by low read counts. See also --no-filter."+               , prior :: Maybe String <?> "([Nothing] | STRING) The input folder containing the output from a previous run. If specified, skips clustering by using the previous clustering files."+               , order :: Maybe Double <?> "([1] | DOUBLE) The order of diversity."+               , clumpinessMethod :: Maybe String <?> "([Majority] | Exclusive | AllExclusive) The method used when calculating clumpiness: Majority labels leaves according to the most abundant label, Exclusive only looks at leaves consisting of cells solely from one label, and AllExclusive treats the leaf as containing both labels."+               , output :: Maybe String <?> "([out] | STRING) The folder containing output."}+    | Interactive { matrixPath :: [String] <?> "(PATH) The path to the input directory containing the matrix output of cellranger (matrix.mtx, genes.tsv, and barcodes.tsv) or, if genes-file and cells-file are not specified, or an input csv file containing gene row names and cell column names. If given as a list (--matrixPath input1 --matrixPath input2 etc.) then will join all matrices together. Assumes the same number and order of genes in each matrix, so only cells are added."+                  , cellWhitelistFile :: Maybe String <?> "([Nothing] | FILE) The input file containing the cells to include. No header, line separated list of barcodes."+                  , labelsFile :: Maybe String <?> "([Nothing] | FILE) The input file containing the label for each cell barcode, with \"item,label\" header."+                  , delimiter :: Maybe Char <?> "([,] | CHAR) The delimiter for the csv file if using a normal csv rather than cellranger output and for --labels-file."+                  , normalization :: Maybe String <?> "([TfIdfNorm] | UQNorm | MedNorm | TotalMedNorm | BothNorm | NoneNorm) Type of normalization before clustering. TfIdfNorm normalizes based on the prevalence of each feature. UQNorm normalizes each observation by the upper quartile non-zero counts of that observation. MedNorm normalizes each observation by the median non-zero counts of that observation. TotalMedNorm normalized first each observation by total count then by median of non-zero counts across features. BothNorm uses both normalizations (first TotalMedNorm for all analysis then additionally TfIdfNorm during clustering). NoneNorm does not normalize. Default is TfIdfNorm for clustering and NoneNorm for differential (which instead uses the recommended edgeR single cell preprocessing including normalization and filtering, any normalization provided here will result in edgeR preprocessing on top). Cannot use TfIdfNorm for any other process as NoneNorm will become the default."+                  , pca :: Maybe Double <?> "([Nothing] | DOUBLE) The percent variance to retain for PCA dimensionality reduction before clustering. Default is no PCA at all in order to keep all information."+                  , noFilter :: Bool <?> "Whether to bypass filtering genes and cells by low counts."+                  , filterThresholds :: Maybe String <?> "([(250, 1)] | (DOUBLE, DOUBLE)) The minimum filter thresholds for (MINCELL, MINFEATURE) when filtering cells and features by low read counts. See also --no-filter."+                  , prior :: Maybe String <?> "([Nothing] | STRING) The input folder containing the output from a previous run. If specified, skips clustering by using the previous clustering files."}+    | Differential { matrixPath :: [String] <?> "(PATH) The path to the input directory containing the matrix output of cellranger (matrix.mtx, genes.tsv, and barcodes.tsv) or, if genes-file and cells-file are not specified, or an input csv file containing gene row names and cell column names. If given as a list (--matrixPath input1 --matrixPath input2 etc.) then will join all matrices together. Assumes the same number and order of genes in each matrix, so only cells are added."+                   , cellWhitelistFile :: Maybe String <?> "([Nothing] | FILE) The input file containing the cells to include. No header, line separated list of barcodes."+                   , labelsFile :: Maybe String <?> "([Nothing] | FILE) The input file containing the label for each cell barcode, with \"item,label\" header."+                   , pca :: Maybe Double <?> "([Nothing] | DOUBLE) The percent variance to retain for PCA dimensionality reduction before clustering. Default is no PCA at all in order to keep all information."+                   , noFilter :: Bool <?> "Whether to bypass filtering genes and cells by low counts."+                   , filterThresholds :: Maybe String <?> "([(250, 1)] | (DOUBLE, DOUBLE)) The minimum filter thresholds for (MINCELL, MINFEATURE) when filtering cells and features by low read counts. See also --no-filter."+                   , delimiter :: Maybe Char <?> "([,] | CHAR) The delimiter for the csv file if using a normal csv rather than cellranger output and for --labels-file."+                   , normalization :: Maybe String <?> "([TfIdfNorm] | UQNorm | MedNorm | TotalMedNorm | BothNorm | NoneNorm) Type of normalization before clustering. TfIdfNorm normalizes based on the prevalence of each feature. UQNorm normalizes each observation by the upper quartile non-zero counts of that observation. MedNorm normalizes each observation by the median non-zero counts of that observation. TotalMedNorm normalized first each observation by total count then by median of non-zero counts across features. BothNorm uses both normalizations (first TotalMedNorm for all analysis then additionally TfIdfNorm during clustering). NoneNorm does not normalize. Default is TfIdfNorm for clustering and NoneNorm for differential (which instead uses the recommended edgeR single cell preprocessing including normalization and filtering, any normalization provided here will result in edgeR preprocessing on top). Cannot use TfIdfNorm for any other process as NoneNorm will become the default."+                   , prior :: Maybe String <?> "([Nothing] | STRING) The input folder containing the output from a previous run. If specified, skips clustering by using the previous clustering files."+                   , nodes :: String <?> "([NODE], [NODE]) Find the differential expression between cells belonging downstream of a list of nodes versus another list of nodes. \"([], [])\" switches the process to instead find the log2 average division between all nodes with all other cells (node / other cells) using the Kruskal-Wallis Test (--genes does not work for this, --labels works, and UQNorm for the normalization is recommended. Only returns nodes where the comparison had both groups containing at least five cells.)."+                   , labels :: Maybe String <?> "([Nothing] | ([LABEL], [LABEL])) Use --labels-file to restrict the differential analysis to cells with these labels. Same format as --nodes, so the first list in --nodes and --labels gets the cells within that list of nodes with this list of labels. The same for the second list. For instance, --nodes \"([1], [2])\" --labels \"([\\\"A\\\"], [\\\"B\\\"])\" will compare cells from node 1 of label \"A\" only with cells from node 2 of label \"B\" only. To use all cells for that set of nodes, use an empty list, i.e. --labels \"([], [\\\"A\\\"])\". When comparing all nodes with all other cells, remember that the notation would be ([Other Cells], [Node]), so to compare cells of label X in Node with cells of label Y in Other Cells, use --labels \"([\\\"Y\\\", \\\"X\\\"])\". Requires both --labels and --labels-file, otherwise will include all labels."+                   , topN :: Maybe Int <?> "([100] | INT ) The top INT differentially expressed genes."+                   , genes :: [T.Text] <?> "([Nothing] | GENE) List of genes to plot for all cells within selected nodes. Invoked by --genes CD4 --genes CD8 etc. When this argument is supplied, only the plot is outputted and edgeR differential expression is ignored. Outputs to --output."+                   , plotOutput :: Maybe String <?> "([out.pdf] | STRING) The file containing the output plot."}+    | Diversity { priors :: [String] <?> "(PATH) Either input folders containing the output from a run of too-many-cells or a csv files containing the clusters for each cell in the format \"cell,cluster\". Advanced features not available in the latter case. If --labels-file is specified, those labels designate entity type, otherwise the assigned cluster is the entity type."+                , delimiter :: Maybe Char <?> "([,] | CHAR) The delimiter for the csv file if using a normal csv rather than cellranger output and for --labels-file."+                , labelsFile :: Maybe String <?> "([Nothing] | FILE) The input file containing the label for each cell barcode, with \"item,label\" header."+                , start :: Maybe Integer <?> "([0] | INT) For the rarefaction curve, start the curve at this subsampling."+                , interval :: Maybe Integer <?> "([1] | INT) For the rarefaction curve, the amount to increase each subsampling. For instance, starting at 0 with an interval of 4, we would sampling 0, 4, 8, 12, ..."+                , end :: Maybe Integer <?> "([N] | INT) For the rarefaction curve, which subsample to stop at. By default, the curve stops at the observed number of species for each population."+                , order :: Maybe Double <?> "([1] | DOUBLE) The order of diversity."+                , output :: Maybe String <?> "([out] | STRING) The folder containing output."}+    | Paths { prior :: Maybe String <?> "([Nothing] | STRING) The input folder containing the output from a previous run. If specified, skips clustering by using the previous clustering files."+            , labelsFile :: Maybe String <?> "([Nothing] | FILE) The input file containing the label for each cell barcode, with \"item,label\" header."+            , flipDirection :: Bool <?> "Flip the starting node when calculating the distances."+            , pathDistance :: Maybe String <?> "([PathModularity] | PathStep) How to measure the distance from the starting leaf. PathModularity weighs the steps by the modularity, while PathStep counts the number of steps."+            , bandwidth :: Maybe Double <?> "([1] | DOUBLE) Bandwidth of the density plot."+            , delimiter :: Maybe Char <?> "([,] | CHAR) The delimiter for the csv file if using a normal csv rather than cellranger output and for --labels-file."+            , output :: Maybe String <?> "([out] | STRING) The folder containing output."}+    deriving (Generic)++modifiers :: Modifiers+modifiers = lispCaseModifiers { shortNameModifier = short }+  where+    short "clumpinessMethod"     = Just 'u'+    short "clusterNormalization" = Just 'C'+    short "dendrogramOutput"     = Just 'U'+    short "drawCollection"       = Just 'E'+    short "drawColors"           = Just 'R'+    short "drawDendrogram"       = Just 'D'+    short "drawLeaf"             = Just 'L'+    short "drawMark"             = Just 'K'+    short "drawMaxNodeSize"      = Just 'A'+    short "drawMaxLeafNodeSize"  = Nothing+    short "drawNoScaleNodes"     = Just 'W'+    short "drawNodeNumber"       = Just 'N'+    short "drawLegendSep"        = Just 'Q'+    short "drawLegendAllLabels"  = Just 'J'+    short "drawPalette"          = Just 'Y'+    short "drawScaleSaturation"  = Just 'V'+    short "eigenGroup"           = Just 'B'+    short "filterThresholds"     = Just 'H'+    short "labels"               = Nothing+    short "maxDistance"          = Just 'T'+    short "maxProportion"        = Just 'X'+    short "maxStep"              = Just 'S'+    short "minSize"              = Just 'M'+    short "noFilter"             = Just 'F'+    short "normalization"        = Just 'z'+    short "numEigen"             = Just 'G'+    short "order"                = Just 'O'+    short "pca"                  = Just 'a'+    short "plotOutput"           = Nothing+    short "priors"               = Just 'P'+    short "projectionFile"       = Just 'j'+    short x                      = firstLetter x++instance ParseRecord Options where+    parseRecord = parseRecordWithModifiers modifiers++-- | Notify user of limitations and error out for incompatabilities. Empty for+-- now.+limitationWarningsErrors :: Options -> IO ()+limitationWarningsErrors opts = do+    return ()++-- | Read or return an error.+readOrErr err = fromMaybe (error err) . readMaybe++-- | Normalization defaults.+getNormalization :: Options -> NormType+getNormalization opts@(MakeTree{}) =+  maybe+    TfIdfNorm+    (readOrErr "Cannot read --normalization.")+    . unHelpful+    . normalization+    $ opts+getNormalization opts@(Interactive{}) =+  maybe+    TfIdfNorm+    (readOrErr "Cannot read --normalization.")+    . unHelpful+    . normalization+    $ opts+getNormalization opts@(Differential{}) =+  maybe+    NoneNorm+    (readOrErr "Cannot read --normalization.")+    . unHelpful+    . normalization+    $ opts++-- | Load the single cell matrix.+loadSSM :: Options -> FilePath -> IO SingleCells+loadSSM opts matrixPath' = do+    fileExist      <- FP.doesFileExist matrixPath'+    directoryExist <- FP.doesDirectoryExist matrixPath'++    let matrixFile' =+            case (fileExist, directoryExist) of+                (False, False) -> error "\nMatrix path does not exist."+                (True, False)  -> Left $ MatrixFile matrixPath'+                (False, True)  ->+                    Right . MatrixFile $ matrixPath' FP.</> "matrix.mtx"+        genesFile'  = GeneFile $ matrixPath' FP.</> "genes.tsv"+        cellsFile'  = CellFile $ matrixPath' FP.</> "barcodes.tsv"+        delimiter'      =+            Delimiter . fromMaybe ',' . unHelpful . delimiter $ opts+        unFilteredSc   =+            case matrixFile' of+                (Left file) -> loadSparseMatrixDataStream+                                delimiter'+                                file+                (Right file) -> loadCellrangerData+                                    genesFile'+                                    cellsFile'+                                    file+    unFilteredSc++-- | Load all single cell matrices.+loadAllSSM :: Options -> IO (Maybe SingleCells)+loadAllSSM opts = runMaybeT $ do+    let matrixPaths'       = unHelpful . matrixPath $ opts+        cellWhitelistFile' =+            fmap CellWhitelistFile . unHelpful . cellWhitelistFile $ opts+        normalization'     = getNormalization opts+        pca'               = fmap PCAVar . unHelpful . pca $ opts+        noFilterFlag'      = NoFilterFlag . unHelpful . noFilter $ opts+        filterThresholds'  = FilterThresholds+                           . maybe (250, 1) read+                           . unHelpful+                           . filterThresholds+                           $ opts++    mats <- MaybeT+          $ if null matrixPaths'+              then return Nothing+              else fmap Just . mapM (loadSSM opts) $ matrixPaths'+    cellWhitelist <- liftIO . sequence $ fmap getCellWhitelist cellWhitelistFile'++    let whiteListFilter Nothing = id+        whiteListFilter (Just wl) = filterWhitelistSparseMat wl+        unFilteredSc = mconcat mats+        sc           =+            (\ x -> if unNoFilterFlag noFilterFlag'+                        then x+                        else filterNumSparseMat filterThresholds' x+            )+                . whiteListFilter cellWhitelist+                $ unFilteredSc+        normMat TfIdfNorm    = id -- Normalize during clustering.+        normMat UQNorm       = uqScaleSparseMat+        normMat MedNorm      = medScaleSparseMat+        normMat TotalMedNorm = scaleSparseMat+        normMat BothNorm     = scaleSparseMat+        normMat NoneNorm     = id+        processMat  = (\m -> maybe m (flip pcaDenseMat m) pca')+                    . normMat normalization'+                    . _matrix+        processedSc = sc { _matrix = processMat sc }++    return processedSc++makeTreeMain :: Options -> IO ()+makeTreeMain opts = H.withEmbeddedR defaultConfig $ do+    let readOrErr err = fromMaybe (error err) . readMaybe+        matrixPaths'      = unHelpful . matrixPath $ opts+        labelsFile'       =+            fmap LabelFile . unHelpful . labelsFile $ opts+        prior'            =+            fmap PriorPath . unHelpful . prior $ opts+        delimiter'        =+            Delimiter . fromMaybe ',' . unHelpful . delimiter $ opts+        eigenGroup'       =+            maybe SignGroup (readOrErr "Cannot read eigen-group.")+              . unHelpful+              . eigenGroup+              $ opts+        normalization'    = getNormalization opts+        numEigen'         = fmap NumEigen . unHelpful . numEigen $ opts+        minSize'          = fmap MinClusterSize . unHelpful . minSize $ opts+        maxStep'          = fmap MaxStep . unHelpful . maxStep $ opts+        maxProportion'    =+            fmap MaxProportion . unHelpful . maxProportion $ opts+        minDistance'      = fmap MinDistance . unHelpful . minDistance $ opts+        smartCutoff'      = fmap SmartCutoff . unHelpful . smartCutoff $ opts+        dendrogramOutput' = DendrogramFile+                          . fromMaybe "dendrogram.svg"+                          . unHelpful+                          . dendrogramOutput+                          $ opts+        matrixOutput'     = fmap (MatrixFile . (unOutputDirectory output' FP.</>))+                          . unHelpful+                          . matrixOutput+                          $ opts+        drawLeaf'         =+            maybe+              (maybe DrawText (const (DrawItem DrawLabel)) labelsFile')+              (readOrErr "Cannot read draw-leaf.")+                . unHelpful+                . drawLeaf+                $ opts+        drawCollection'   =+            maybe PieChart (readOrErr "Cannot read draw-collection.")+              . unHelpful+              . drawCollection+              $ opts+        drawMark'         = maybe MarkNone (readOrErr "Cannot read draw-mark.")+                          . unHelpful+                          . drawMark+                          $ opts+        drawNodeNumber'   = DrawNodeNumber . unHelpful . drawNodeNumber $ opts+        drawMaxNodeSize'  =+            DrawMaxNodeSize . fromMaybe 72 . unHelpful . drawMaxNodeSize $ opts+        drawMaxLeafNodeSize' = DrawMaxLeafNodeSize+                             . fromMaybe (unDrawMaxNodeSize drawMaxNodeSize')+                             . unHelpful+                             . drawMaxLeafNodeSize+                             $ opts+        drawNoScaleNodes' =+            DrawNoScaleNodesFlag . unHelpful . drawNoScaleNodes $ opts+        drawLegendSep'    = DrawLegendSep+                          . fromMaybe 1+                          . unHelpful+                          . drawLegendSep+                          $ opts+        drawLegendAllLabels' =+            DrawLegendAllLabels . unHelpful . drawLegendAllLabels $ opts+        drawPalette' = maybe+                        Set1+                        (fromMaybe (error "Cannot read palette.") . readMaybe)+                     . unHelpful+                     . drawPalette+                     $ opts+        drawColors'       = fmap ( CustomColors+                                 . fmap sRGB24read+                                 . (\x -> readOrErr "Cannot read draw-colors." x :: [String])+                                 )+                          . unHelpful+                          . drawColors+                          $ opts+        drawScaleSaturation' =+            fmap DrawScaleSaturation . unHelpful . drawScaleSaturation $ opts+        order'            = Order . fromMaybe 1 . unHelpful . order $ opts+        clumpinessMethod' =+            maybe Clump.Majority (readOrErr "Cannot read clumpiness-method.")+              . unHelpful+              . clumpinessMethod+              $ opts+        projectionFile' =+            fmap ProjectionFile . unHelpful . projectionFile $ opts+        output'           =+            OutputDirectory . fromMaybe "out" . unHelpful . output $ opts++    -- Increment  progress bar.+    Progress.autoProgressBar+        (Progress.msg "Loading matrix")+        Progress.percentage+        80+        $ Progress.Progress 0 10++    -- Load matrix once.+    processedSc <- loadAllSSM opts++    -- Notify user of limitations.+    limitationWarningsErrors opts++    -- Increment  progress bar.+    Progress.autoProgressBar+        (Progress.msg "Planning leaf colors")+        Progress.percentage+        80+        $ Progress.Progress 1 10++    -- Where to place output files.+    FP.createDirectoryIfMissing True . unOutputDirectory $ output'++    -- Get the label map from either a file or from expression thresholds.+    labelMap <- case drawLeaf' of+                    (DrawItem (DrawThresholdContinuous gs)) ->+                        return+                            . Just+                            . getLabelMapThresholdContinuous+                                (fmap (L.over L._1 Feature) gs)+                            . extractSc+                            $ processedSc+                    _ -> mapM (loadLabelData delimiter') $ labelsFile'++    -- Increment  progress bar.+    Progress.autoProgressBar+        (Progress.msg "Planting tree")+        Progress.percentage+        80+        $ Progress.Progress 2 10++    --R.withEmbeddedR R.defaultConfig $ R.runRegion $ do+        -- For r clustering.+        -- mat         <- scToRMat processedSc+        -- clusterRes  <- hdbscan mat+        -- clusterList <- clustersToClusterList sc clusterRes++        -- For agglomerative clustering.+        --let clusterResults = fmap hClust processedSc++    -- Load previous results or calculate results if first run.+    originalClusterResults <- case prior' of+        Nothing -> do+            let (fullCr, _) = hSpecClust eigenGroup' normalization' numEigen'+                            . extractSc+                            $ processedSc++            return fullCr :: IO ClusterResults+        (Just x) -> do+            let clInput = unPriorPath x FP.</> "cluster_list.json"+                treeInput = unPriorPath x FP.</> "cluster_tree.json"++            -- Strict loading in order to avoid locked file.+            loadClusterResultsFiles clInput treeInput++    -- Increment  progress bar.+    Progress.autoProgressBar+        (Progress.msg "Measuring roots")+        Progress.percentage+        80+        $ Progress.Progress 3 10++    let birchMat = processedSc+        birchSimMat =+            case (not . null . unHelpful . matrixPath $ opts, drawCollection') of+                (True, CollectionGraph{} )  ->+                    Just+                        . B2Matrix+                        . L.over matrix (MatObsRow . unB2 . b1ToB2 . B1 . unMatObsRow)+                        . extractSc+                        $ processedSc+                _ -> Nothing++    -- Increment  progress bar.+    Progress.autoProgressBar+        (Progress.msg "Sketching tree")+        Progress.percentage+        80+        $ Progress.Progress 4 10++    let config :: BirchBeer.Types.Config CellInfo SingleCells+        config = BirchBeer.Types.Config+                    { _birchLabelMap = labelMap+                    , _birchMinSize = minSize'+                    , _birchMaxStep = maxStep'+                    , _birchMaxProportion = maxProportion'+                    , _birchMinDistance = minDistance'+                    , _birchSmartCutoff = smartCutoff'+                    , _birchOrder = Just order'+                    , _birchDrawLeaf = drawLeaf'+                    , _birchDrawCollection = drawCollection'+                    , _birchDrawMark = drawMark'+                    , _birchDrawNodeNumber = drawNodeNumber'+                    , _birchDrawMaxNodeSize = drawMaxNodeSize'+                    , _birchDrawMaxLeafNodeSize = drawMaxLeafNodeSize'+                    , _birchDrawNoScaleNodes = drawNoScaleNodes'+                    , _birchDrawLegendSep    = drawLegendSep'+                    , _birchDrawLegendAllLabels = drawLegendAllLabels'+                    , _birchDrawPalette = drawPalette'+                    , _birchDrawColors = drawColors'+                    , _birchDrawScaleSaturation = drawScaleSaturation'+                    , _birchTree = _clusterDend originalClusterResults+                    , _birchMat = birchMat+                    , _birchSimMat = birchSimMat+                    }++    (plot, labelColorMap, itemColorMap, markColorMap, tree', gr') <- mainDiagram config++    -- Increment  progress bar.+    Progress.autoProgressBar+        (Progress.msg "Recording tree measurements")+        Progress.percentage+        80+        $ Progress.Progress 5 10++    -- Write results.+    clusterResults <- case prior' of+        Nothing -> do+            let clusterList' = treeToClusterList tree'+                cr' = ClusterResults clusterList' tree'++            return cr'++        (Just x) -> do+            let clusterList' = treeToClusterList tree'+                cr' = ClusterResults clusterList' tree'++            return cr'++    B.writeFile+        (unOutputDirectory output' FP.</> "cluster_list.json")+        . A.encode+        . _clusterList+        $ clusterResults+    B.writeFile+        (unOutputDirectory output' FP.</> "cluster_tree.json")+        . A.encode+        . _clusterDend+        $ clusterResults+    T.writeFile+        (unOutputDirectory output' FP.</> "graph.dot")+        . G.printDotGraph+        . G.graphToDot G.nonClusteredParams+        . unClusterGraph+        $ gr'+    B.writeFile+        (unOutputDirectory output' FP.</> "cluster_info.csv")+        . printClusterInfo+        $ gr'+    case matrixOutput' of+        Nothing  -> return ()+        (Just x) -> writeMatrixLike x . extractSc $ processedSc+    B.writeFile+        (unOutputDirectory output' FP.</> "node_info.csv")+        . printNodeInfo labelMap+        $ gr'+    case labelMap of+        Nothing   -> return ()+        (Just lm) ->+            case clusterDiversity order' lm clusterResults of+                (Left err) -> hPutStrLn stderr+                            $ err+                           <> "\nError in diversity, skipping cluster_diversity.csv output."+                (Right result) ->+                    B.writeFile+                        ( unOutputDirectory output'+                   FP.</> "cluster_diversity.csv"+                        )+                        . printClusterDiversity+                        $ result++    -- Increment  progress bar.+    Progress.autoProgressBar+        (Progress.msg "Counting leaves")+        Progress.percentage+        80+        $ Progress.Progress 6 10++    -- Header+    B.putStrLn $ "cell,cluster,path"++    -- Body+    B.putStrLn+        . CSV.encode+        . fmap (\ (!ci, !(c:cs))+                -> ( unCell . _barcode $ ci+                , showt $ unCluster c+                , T.intercalate "/" . fmap (showt . unCluster) $ c:cs+                )+                )+        . _clusterList+        $ clusterResults++    -- Increment  progress bar.+    Progress.autoProgressBar+        (Progress.msg "Painting sketches")+        Progress.percentage+        80+        $ Progress.Progress 7 10++    -- Plot only if needed and ignore non-tree analyses if dendrogram is+    -- supplied.+    H.runRegion $ do+        -- Calculations with plotting the label map (clumpiness).+        case labelMap of+            Nothing ->+                H.io $ hPutStrLn stderr "\nClumpiness requires labels for cells, skipping..."+            (Just lm) -> do+                -- Get clumpiness.+                case treeToClumpList clumpinessMethod' lm . _clusterDend $ clusterResults of+                    (Left err) -> H.io+                                . hPutStrLn stderr+                                $ err+                               <> "\nError in clumpiness, skipping clumpiness.* output."+                    (Right clumpList) -> do+                        -- Save clumpiness to a file.+                        H.io+                            . B.writeFile (unOutputDirectory output' FP.</> "clumpiness.csv")+                            . clumpToCsv+                            $ clumpList++                        -- Plot clumpiness.+                        either (H.io . hPutStrLn stderr) id+                            $ plotClumpinessHeatmapR+                                (unOutputDirectory output' FP.</> "clumpiness.pdf")+                                clumpList++        -- Increment  progress bar.+        H.io $ Progress.autoProgressBar+            (Progress.msg "Painting tree")+            Progress.percentage+            80+            $ Progress.Progress 8 10++        -- Plot.+        H.io $ do+            -- cr <- clusterResults+            -- gr <- graph+            -- cm <- itemColorMap++            -- plot <- if drawDendrogram'+            --         then return . plotDendrogram legend drawLeaf' cm . _clusterDend $ cr+            --         else do+            --             plotGraph legend drawConfig cm markColorMap gr++            D.renderCairo+                    ( unOutputDirectory output'+               FP.</> unDendrogramFile dendrogramOutput'+                    )+                    (D.mkHeight 1000)+                    plot++        -- Increment  progress bar.+        H.io $ Progress.autoProgressBar+            (Progress.msg "Squishing tree")+            Progress.percentage+            80+            $ Progress.Progress 9 10++        -- Plot clustering of the projections.+        case projectionFile' of+          Nothing  -> return ()+          (Just f) -> do+            -- Load projection map if provided.+            projectionMap <- H.io $ loadProjectionMap f++            plotClustersR+              (unOutputDirectory output' FP.</> "projection.pdf")+              projectionMap+              . _clusterList+              $ clusterResults++            -- Plot clustering with labels.+            case (labelMap, itemColorMap) of+                (Just lm, Just icm) ->+                    plotLabelClustersR+                        (unOutputDirectory output' FP.</> "label_projection.pdf")+                        projectionMap+                        lm+                        icm+                        (_clusterList clusterResults)+                _ -> return ()++        -- Increment  progress bar.+        H.io $ Progress.autoProgressBar+            (Progress.msg "Packing up")+            Progress.percentage+            80+            $ Progress.Progress 10 10++        return ()++-- | Interactive tree interface.+interactiveMain :: Options -> IO ()+interactiveMain opts = H.withEmbeddedR defaultConfig $ do+    let labelsFile'    =+            fmap LabelFile . unHelpful . labelsFile $ opts+        prior'         = maybe (error "\nRequires --prior") PriorPath+                       . unHelpful+                       . prior+                       $ opts+        delimiter'     =+            Delimiter . fromMaybe ',' . unHelpful . delimiter $ opts+        normalization'    = getNormalization opts++    mat <- loadAllSSM opts+    labelMap <- sequence . fmap (loadLabelData delimiter') $ labelsFile'++    tree <- fmap (either error id . A.eitherDecode)+          . B.readFile+          . (FP.</> "cluster_tree.json")+          . unPriorPath+          $ prior' :: IO (Tree (TreeNode (V.Vector CellInfo)))++    interactiveDiagram+        tree+        labelMap+        mat+        . fmap ( B2Matrix+               . L.over matrix (MatObsRow . unB2 . b1ToB2 . B1 . unMatObsRow)+               )+        $ mat++    return ()++-- | Differential path.+differentialMain :: Options -> IO ()+differentialMain opts = do+    let readOrErr err = fromMaybe (error err) . readMaybe+        delimiter'     =+            Delimiter . fromMaybe ',' . unHelpful . delimiter $ opts+        labelsFile' =+            fmap LabelFile . unHelpful . labelsFile $ opts+        nodes'    =+          DiffNodes . readOrErr "Cannot read --nodes." . unHelpful . nodes $ opts+        prior'    = PriorPath+                  . fromMaybe (error "\nRequires a previous run to get the graph.")+                  . unHelpful+                  . prior+                  $ opts+        topN'     = TopN . fromMaybe 100 . unHelpful . topN $ opts+        genes'    = fmap Gene . unHelpful . genes $ opts+        labels'   = fmap ( DiffLabels+                         . L.over L.both ( (\x -> bool (Just x) Nothing . Set.null $ x)+                                         . Set.fromList+                                         . fmap Label+                                         )+                         . readOrErr "Cannot read --labels."+                         )+                  . unHelpful+                  . labels+                  $ opts+        (combined1, combined2) = combineNodesLabels nodes' labels'+        plotOutputR = fromMaybe "out.pdf" . unHelpful . plotOutput $ opts++    processedSc <- loadAllSSM opts++    labelMap <- mapM (loadLabelData delimiter') $ labelsFile'++    let clInput = (FP.</> "cluster_list.json") . unPriorPath $ prior'+        treeInput = (FP.</> "cluster_tree.json") . unPriorPath $ prior'++        cr :: IO ClusterResults+        cr = loadClusterResultsFiles clInput treeInput++    gr <- fmap (treeToGraph . _clusterDend) cr++    H.withEmbeddedR defaultConfig $ H.runRegion $ do+      case genes' of+        [] -> do+          case nodes' of+            (DiffNodes ([], [])) -> do+              let res = getAllDEGraphKruskalWallis+                          topN'+                          labelMap+                          (maybe (DiffLabels (Nothing, Nothing)) id labels')+                          (extractSc processedSc)+                      $ gr++              H.io . B.putStrLn . getAllDEStringKruskalWallis $ res+            (DiffNodes ([], _)) -> error "Need other nodes to compare with. If every node should be compared to all other nodes using Mann-Whitney U, use \"([], [])\"."+            (DiffNodes (_, [])) -> error "Need other nodes to compare with. If every node should be compared to all other nodes using Mann-Whitney U, use \"([], [])\"."+            _ -> do+              res <- getDEGraph+                      topN'+                      labelMap+                      (extractSc processedSc)+                      combined1+                      combined2+                      gr++              H.io . B.putStrLn . getDEString $ res+        _ -> do+          diffPlot <- getSingleDiff+                       False+                       labelMap+                       (extractSc processedSc)+                       combined1+                       combined2+                       genes'+                       gr+          [r| suppressMessages(ggsave(diffPlot_hs, file = plotOutputR_hs)) |]++          let normOutputR = FP.replaceBaseName+                              plotOutputR+                             (FP.takeBaseName plotOutputR <> "_scaled")++          diffNormPlot <- getSingleDiff+                            True+                            labelMap+                            (extractSc processedSc)+                            combined1+                            combined2+                            genes'+                            gr+          [r| suppressMessages(ggsave(diffNormPlot_hs, file = normOutputR_hs)) |]++          return ()++-- | Diversity path.+diversityMain :: Options -> IO ()+diversityMain opts = do+    let priors'         =+            fmap PriorPath . unHelpful . priors $ opts+        delimiter'     =+            Delimiter . fromMaybe ',' . unHelpful . delimiter $ opts+        labelsFile'       =+            fmap LabelFile . unHelpful . labelsFile $ opts+        output'         =+            OutputDirectory . fromMaybe "out" . unHelpful . output $ opts+        order'       = Order . fromMaybe 1 . unHelpful . order $ opts+        start'       = Start . fromMaybe 0 . unHelpful . start $ opts+        interval'    = Interval . fromMaybe 1 . unHelpful . interval $ opts+        endMay'      = fmap End . unHelpful . end $ opts++    -- Where to place output files.+    FP.createDirectoryIfMissing True . unOutputDirectory $ output'++    labelMap <- sequence . fmap (loadLabelData delimiter') $ labelsFile'++    pops <- fmap ( either+                    (\err -> error $ err <> "\nEncountered error in population loading, aborting process.")+                    id+                 . sequence+                 )+          . mapM (\x -> (fmap . fmap) (Label . T.pack . unPriorPath $ x,)+                      . loadPopulation labelMap+                      $ x+                 )+          $ priors'++    popDiversities <-+        mapM+            (\ (l, pop) -> getPopulationDiversity+                                l+                                order'+                                start'+                                interval'+                                endMay'+                                pop+            )+            pops++    -- Output quantifications.+    B.writeFile (unOutputDirectory output' FP.</> "diversity.csv")+      . CSV.encodeDefaultOrderedByName+      $ popDiversities++    -- D.renderCairo (unOutputDirectory output' FP.</> "diversity.pdf") D.absolute+    --     . plotDiversity+    --     $ popDiversities++    -- D.renderCairo (unOutputDirectory output' FP.</> "chao1.pdf") D.absolute+    --     . plotChao1+    --     $ popDiversities++    -- D.renderCairo (unOutputDirectory output' FP.</> "rarefaction.pdf") D.absolute+    --     . plotRarefaction+    --     $ popDiversities++    -- Output plots.+    let colors = D.colorRamp (length pops) . D.brewerSet D.Set1 $ 9++    H.withEmbeddedR defaultConfig $ H.runRegion $ do+        let divFile = unOutputDirectory output' FP.</> "diversity.pdf"+        divPlot <- plotDiversityR colors popDiversities+        [r| suppressMessages(ggsave(divPlot_hs, file = divFile_hs)) |]++        -- let chao1File = unOutputDirectory output' FP.</> "chao_r.pdf"+        -- chao1Plot <- plotChao1R colors popDiversities+        -- [r| suppressMessages(ggsave(chao1Plot_hs, file = chao1File_hs)) |]++        let rarefactionFile = unOutputDirectory output' FP.</> "rarefaction.pdf"+        rarefactionPlot <- plotRarefactionR colors popDiversities+        [r| suppressMessages(ggsave(rarefactionPlot_hs, file = rarefactionFile_hs)) |]++        return ()++    return ()++-- | Paths path.+pathsMain :: Options -> IO ()+pathsMain opts = do+    let labelsFile'   =+            maybe (error "\nNeed a label file.") LabelFile+                . unHelpful+                . labelsFile+                $ opts+        prior'        =+            maybe (error "\nNeed a prior path containing tree.") PriorPath+                . unHelpful+                . prior+                $ opts+        delimiter'    =+            Delimiter . fromMaybe ',' . unHelpful . delimiter $ opts+        bandwidth'    = Bandwidth . fromMaybe 1 . unHelpful . bandwidth $ opts+        direction'    = FlipFlag . unHelpful . flipDirection $ opts+        pathDistance' =+            maybe PathStep read . unHelpful . pathDistance $ opts+        output'       =+            OutputDirectory . fromMaybe "out" . unHelpful . output $ opts++    -- Where to place output files.+    FP.createDirectoryIfMissing True . unOutputDirectory $ output'++    -- Get the label map from a file.+    labelMap <- loadLabelData delimiter' labelsFile'++    -- Load previous results or calculate results if first run.+    tree <- fmap (either error id . A.eitherDecode)+          . B.readFile+          . (FP.</> "cluster_tree.json")+          . unPriorPath+          $ prior'++    let gr = treeToGraph tree+        pathDistances :: [(CellInfo, Double)]+        pathDistances = linearItemDistance direction' pathDistance' gr+        labeledPathDistances =+            labelItemDistance labelMap pathDistances++    H.withEmbeddedR defaultConfig $ H.runRegion $ do+        plotPathDistanceR+            (unOutputDirectory output' FP.</> "path_distances.pdf")+            bandwidth'+            labeledPathDistances+        return ()++    return ()++main :: IO ()+main = do+    opts <- getRecord "too-many-cells, Gregory W. Schwartz.\+                      \ Clusters and analyzes single cell data."++    case opts of+        MakeTree{}       -> makeTreeMain opts+        Interactive{}    -> interactiveMain opts+        Differential{}   -> differentialMain opts+        Main.Diversity{} -> diversityMain opts+        Paths{}          -> pathsMain opts
+ src/TooManyCells/Differential/Differential.hs view
@@ -0,0 +1,244 @@+{- TooManyCells.Differential.Differential+Gregory W. Schwartz++Functions for finding the differential between groups of cells.+-}++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE QuasiQuotes #-}++module TooManyCells.Differential.Differential+    ( scToTwoD+    , getDEGraph+    , getDEString+    , getSingleDiff+    , combineNodesLabels+    , getAllDEGraphKruskalWallis+    , getAllDEStringKruskalWallis+    ) where++-- Remote+import BirchBeer.Types+import BirchBeer.Utility (getGraphLeaves, getGraphLeafItems)+import Control.Monad (join, mfilter)+import Data.Function (on)+import Data.List (sort, sortBy)+import Data.Maybe (fromMaybe, catMaybes, isJust)+import Data.Monoid ((<>))+import Language.R as R+import Language.R.QQ (r)+import TextShow (showt)+import Control.Parallel.Strategies (parMap, withStrategy, parBuffer, rdeepseq)+import qualified "differential" Differential as Diff+import qualified "differential" Plot as Diff+import qualified "differential" Types as Diff+import qualified Control.Lens as L+import qualified Data.ByteString.Lazy.Char8 as B+import qualified Data.Csv as CSV+import qualified Data.Foldable as F+import qualified Data.Graph.Inductive as G+import qualified Data.Map as Map+import qualified Data.Set as Set+import qualified Data.Sparse.Common as S+import qualified Data.Vector as V+import qualified System.FilePath as FP++-- Local+import TooManyCells.Differential.Types+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types++-- | Convert a single cell matrix to a two dimensional matrix.+scToTwoD :: [(Int, Cell, (Int, Diff.Status))] -> SingleCells -> Diff.TwoDMat+scToTwoD cellGroups sc =+    Diff.TwoDMat rNames cNames statuses nRows nCols . S.toListSM $ filteredMat+  where+    rNames = fmap (Diff.Name . unGene) . V.toList . _colNames $ sc+    cNames = fmap (Diff.Name . unCell . L.view L._2) cellGroups -- We flip row and column because cells are columns here+    statuses = fmap (Diff.Status . showt . L.view (L._3 . L._1)) cellGroups+    nRows    = S.nrows filteredMat+    nCols    = S.ncols filteredMat+    filteredMat = S.fromColsL -- Here the columns should be observations.+                . fmap (S.extractRow (unMatObsRow . _matrix $ sc) . L.view L._1)+                $ cellGroups++-- | Get the indices and statuses for two lists of nodes.+getStatuses+    :: Maybe LabelMap+    -> ([G.Node], Maybe (Set.Set Label))+    -> ([G.Node], Maybe (Set.Set Label))+    -> ClusterGraph CellInfo+    -> [(Int, Cell, (Int, Diff.Status))]+getStatuses lm (v1, l1) (v2, l2) (ClusterGraph gr) =+    sort+        . F.toList+        $ mappend (collapseStatus (1 :: Int) v1 l1) (collapseStatus (2 :: Int) v2 l2)+  where+    collapseStatus s vs ls =+        fmap (\ !x -> (unRow . _cellRow $ x, _barcode x, (s, Diff.Status . showt $ vs)))+            . mfilter (validCellInfo lm ls)+            . join+            . mconcat+            . fmap (fmap (fromMaybe mempty . snd) . getGraphLeaves gr)+            $ vs++-- | Filter barcodes by labels.+validCellInfo :: Maybe LabelMap -> Maybe (Set.Set Label) -> CellInfo -> Bool+validCellInfo Nothing _ = const True+validCellInfo _ Nothing = const True+validCellInfo (Just (LabelMap lm)) (Just ls) =+  maybe False (flip Set.member ls)+    . flip Map.lookup lm+    . Id+    . unCell+    . L.view barcode++-- | Filter barcodes by labels.+validCell :: Maybe LabelMap -> Maybe (Set.Set Label) -> Cell -> Bool+validCell Nothing _ = const True+validCell _ Nothing = const True+validCell (Just (LabelMap lm)) (Just ls) =+  maybe False (flip Set.member ls)+    . flip Map.lookup lm+    . Id+    . unCell++-- | Get the differential expression of two sets of cells, filtered by labels.+getDEGraph :: TopN+           -> Maybe LabelMap+           -> SingleCells+           -> ([G.Node], Maybe (Set.Set Label))+           -> ([G.Node], Maybe (Set.Set Label))+           -> ClusterGraph CellInfo+           -> R.R s [(Diff.Name, Double, Diff.PValue, Diff.FDR)]+getDEGraph (TopN topN) lm sc v1 v2 gr = do+    let cellGroups = getStatuses lm v1 v2 gr+        mat        = scToTwoD cellGroups sc++    Diff.edgeR topN mat++-- | Get the differential expression of each cluster to each other cluster using+-- KruskalWallis.+getAllDEGraphKruskalWallis :: TopN+                    -> Maybe LabelMap+                    -> DiffLabels+                    -> SingleCells+                    -> ClusterGraph CellInfo+                    -> [(G.Node, Gene, Diff.Log2Diff, Maybe Diff.PValue, Maybe Diff.FDR)]+getAllDEGraphKruskalWallis topN lm ls sc gr =+  mconcat+    . catMaybes+    . parMap rdeepseq (\n -> compareClusterToOthersKruskalWallis n topN lm ls sc mat gr)+    $ nodes+  where+    nodes = filter (/= 0) . G.nodes . unClusterGraph $ gr -- Don't want to look at root.+    mat = S.transpose . unMatObsRow . L.view matrix $ sc++-- | Get the differential expression of a cluster (n) to all other clusters (ns)+-- using KruskalWallis such that n / ns.+compareClusterToOthersKruskalWallis+  :: G.Node+  -> TopN+  -> Maybe LabelMap+  -> DiffLabels+  -> SingleCells+  -> S.SpMatrix Double+  -> ClusterGraph CellInfo+  -> Maybe [(G.Node, Gene, Diff.Log2Diff, Maybe Diff.PValue, Maybe Diff.FDR)]+compareClusterToOthersKruskalWallis n (TopN topN) lm (DiffLabels (ls1, ls2)) sc mat gr+  | fastFiveCheck nCells || fastFiveCheck nsCells = Nothing+  | otherwise = Just . take topN . sortBy (compare `on` (L.view L._4)) $ res+  where+    fastFiveCheck = (< 5) . length . take 5+    nCells' = F.toList $ getGraphLeafItems gr n+    nCellsSet = Set.fromList . fmap (L.view barcode) $ nCells'+    nCells = fmap (unRow . L.view cellRow)+           . filter (validCellInfo lm ls2)+           $ nCells' -- All cells from node and labels+    nsCells =+      fmap fst+        . filter (\ (_, !x) -> validCell lm ls1 x && not (Set.member x nCellsSet)) -- All cells outside of node and from labels+        . zip [0..]+        . V.toList+        . L.view rowNames+        $ sc+    res = filter (isJust . L.view L._4)+        . ( zipWith+              (\name (!x, !y, !z) -> (n, name, x, y, z))+              (V.toList . L.view colNames $ sc)+          )+        $ Diff.differentialMatrixFeatRow nsCells nCells mat -- Here the matrix rows are features++-- | Get the differential expression of two sets of cells.+getDEString :: [(Diff.Name, Double, Diff.PValue, Diff.FDR)]+            -> B.ByteString+getDEString xs = header <> "\n" <> body+  where+    header = "gene,logFC,pVal,FDR"+    body   = CSV.encode+           . fmap ( L.over L._1 Diff.unName+                  . L.over L._3 Diff.unPValue+                  . L.over L._4 Diff.unFDR+                  )+           $ xs++-- | Get the differential expression of each node to all other nodes using+-- KruskalWallis.+getAllDEStringKruskalWallis+  :: [(G.Node, Gene, Diff.Log2Diff, Maybe Diff.PValue, Maybe Diff.FDR)] -> B.ByteString+getAllDEStringKruskalWallis xs = header <> "\n" <> body+  where+    header = "node,gene,log2FC,pVal,FDR"+    body   = CSV.encode+           . fmap ( L.over L._5 (maybe "NA" (showt . Diff.unFDR))+                  . L.over L._4 (maybe "NA" (showt . Diff.unPValue))+                  . L.over L._3 Diff.unLog2Diff+                  . L.over L._2 unGene+                  )+           $ xs++-- | Convert a single cell matrix to a list of Entities with the specified+-- features.+scToEntities :: [Gene]+             -> [(Int, Cell, (Int, Diff.Status))]+             -> SingleCells+             -> [Diff.Entity]+scToEntities genes cellGroups sc =+    concatMap (\x -> fmap (toEntity x) geneIdxs) cellGroups+  where+    mat = getMatrix sc+    toEntity (cellIdx, _, (_, status)) (Gene gene, idx) =+      Diff.Entity (Diff.Name gene) status $ S.lookupWD_SM mat (cellIdx, idx)+    geneIdxs :: [(Gene, Int)]+    geneIdxs = fmap (\ !x -> ( x+                             , fromMaybe (err x)+                             $ V.elemIndex (unGene x) (getColNames sc)+                             )+                    ) genes+    err x = error $ "Feature " <> show x <> " not found for differential."++-- | Get the differential expression plot of features over statuses, filtered by labels.+getSingleDiff :: Bool+              -> Maybe LabelMap+              -> SingleCells+              -> ([G.Node], Maybe (Set.Set Label))+              -> ([G.Node], Maybe (Set.Set Label))+              -> [Gene]+              -> ClusterGraph CellInfo+              -> R.R s (R.SomeSEXP s)+getSingleDiff normalize lm sc v1 v2 genes gr = do+  let cellGroups = getStatuses lm v1 v2 gr+      entities = scToEntities genes cellGroups sc++  Diff.plotSingleDiff normalize entities++-- | Combine nodes and labels.+combineNodesLabels+    :: DiffNodes+    -> Maybe DiffLabels+    -> (([G.Node], Maybe (Set.Set Label)), ([G.Node], Maybe (Set.Set Label)))+combineNodesLabels (DiffNodes (v1, v2)) Nothing = ((v1, Nothing), (v2, Nothing))+combineNodesLabels (DiffNodes (v1, v2)) (Just (DiffLabels (l1, l2))) =+  ((v1, l1), (v2, l2))
+ src/TooManyCells/Differential/Types.hs view
@@ -0,0 +1,22 @@+{- TooManyCells.Differential.Types+Gregory W. Schwartz++Collects the differental types used in the program.+-}++{-# LANGUAGE StrictData #-}++module TooManyCells.Differential.Types where++-- Remote+import BirchBeer.Types+import qualified Data.Graph.Inductive as G+import qualified Data.Set as Set++-- Local++-- Basic+newtype TopN = TopN { unTopN :: Int }+newtype DiffNodes = DiffNodes {unDiffNodes :: ([G.Node], [G.Node])}+newtype DiffLabels =+  DiffLabels { unDiffLabels :: (Maybe (Set.Set Label), Maybe (Set.Set Label)) }
+ src/TooManyCells/Diversity/Diversity.hs view
@@ -0,0 +1,63 @@+{- TooManyCells.Diversity.Diversity+Gregory W. Schwartz++Collects the functions pertaining to finding the diversity of populations.+-}++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE PackageImports #-}++module TooManyCells.Diversity.Diversity+    ( getPopulationDiversity+    , getPopulationSize+    ) where++-- Remote+import BirchBeer.Types+import Data.Maybe (fromMaybe)+import Math.Diversity.Diversity (diversityOfMap, chao1, rarefactionCurve)+import qualified Data.Map.Strict as Map+import qualified Data.Sequence as Seq++-- Local+import TooManyCells.Diversity.Types+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types++-- | Find the diversity, Chao1 estimator, and rarefaction curve of a population.+getPopulationDiversity :: Label+                       -> Order+                       -> Start+                       -> Interval+                       -> Maybe End+                       -> Population+                       -> IO PopulationDiversity+getPopulationDiversity+    label+    (Order order)+    (Start start)+    (Interval interval)+    end'+    (Population pop) = do+        let diversity   = Diversity . diversityOfMap order $ popCount+            chao        = Chao1 . chao1 $ popCount+            popCount    = Map.map Seq.length pop+            end         =+                fromMaybe (unSize . getPopulationSize . Population $ pop)+                    . fmap unEnd+                    $ end'+            getRarefactionPoint (!x, Just (!y, _)) = (X $ fromIntegral x, Y y)+            getRarefactionPoint (_, Nothing)       =+                error "Impossible rarefaction point."++        rarefaction <- fmap (Rarefaction . fmap getRarefactionPoint)+                     . rarefactionCurve False 0 start interval end+                     . Map.mapKeys (\ (Species !x) -> (show x, show x))+                     $ popCount++        return $ PopulationDiversity label diversity chao rarefaction++-- | Get the number of cells in a population.+getPopulationSize :: Population -> Size+getPopulationSize =+    Size . fromIntegral . Map.foldl' (+) 0 . Map.map Seq.length . unPopulation
+ src/TooManyCells/Diversity/Load.hs view
@@ -0,0 +1,139 @@+{- TooManyCells.Diversity.Load+Gregory W. Schwartz++Collects the functions pertaining to the loading of data.+-}++{-# LANGUAGE PackageImports #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE BangPatterns #-}++module TooManyCells.Diversity.Load+    ( loadPopulation+    ) where++-- Remote+import BirchBeer.Types+import Control.Monad.Except (runExceptT, ExceptT (..))+import Control.Monad.Managed (with, liftIO, Managed (..))+import Data.Matrix.MatrixMarket (readMatrix)+import Data.Maybe (fromMaybe)+import Data.Monoid ((<>))+import Data.Tuple (swap)+import Math.Clustering.Hierarchical.Spectral.Sparse (B (..))+import Safe (headMay)+import TextShow (showt)+import qualified Control.Lens as L+import qualified Data.Aeson as A+import qualified Data.ByteString.Lazy.Char8 as B+import qualified Data.ByteString.Streaming.Char8 as BS+import qualified Data.Foldable as F+import qualified Data.Map.Strict as Map+import qualified Data.Sequence as Seq+import qualified Data.Text as T+import qualified Data.Text.Read as T+import qualified Streaming as S+import qualified Streaming.Cassava as S+import qualified Streaming.Prelude as S+import qualified Streaming.With.Lifted as SW+import qualified System.Directory as FP+import qualified System.FilePath as FP++-- Local+import TooManyCells.Diversity.Types+import TooManyCells.File.Types+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Utility+import TooManyCells.Matrix.Types++-- | Load a population representation from a cluster file+loadPopulationCsv :: PriorPath -> IO (Either String Population)+loadPopulationCsv file = do+    let getCols :: Map.Map T.Text T.Text -> Either String (Species, Seq.Seq Cell)+        getCols m = do+            x <- do+                    maybe (Left "\nNo cluster column.") (Right . Species)+                    . Map.lookup "cluster"+                    $ m+            y <- do+                    maybe+                        (Left "\nNo cell column.")+                        (Right . Seq.singleton . Cell)+                    . Map.lookup "cell"+                    $ m++            return (x, y)++    flip with return $ do+        contents   <- SW.withBinaryFileContents . unPriorPath $ file+        population <- fmap (\x -> do+                                x' <- either (Left . show) Right x+                                fmap (Population . Map.fromListWith (Seq.><))+                                    . sequence+                                    $ x'+                           )+                    . runExceptT+                    . S.toList_+                    . S.map getCols+                    . S.decodeByName+                    $ (contents :: BS.ByteString (ExceptT S.CsvParseException Managed) ())++        return population++-- | Convert previous cluster results to a population representation.+priorToPopulation :: ClusterResults -> Either String Population+priorToPopulation =+    fmap (Population . Map.fromListWith (Seq.><))+        . mapM (\(!x, !y) -> do+                    let x' = Seq.singleton . _barcode $ x+                    y' <- maybe+                            (Left "\nNo cluster for cell.")+                            (Right . Species . showt . unCluster)+                        . headMay+                        $ y+                    return (y', x')+               )+        . _clusterList++-- | Convert a Population to a custom population with a label map.+popToLabelPop :: LabelMap -> Population -> Either String Population+popToLabelPop (LabelMap lm) = fmap (Population . Map.fromListWith (Seq.><))+                            . mapM getPopEntry+                            . F.toList+                            . mconcat+                            . Map.elems+                            . unPopulation+  where+    getPopEntry (Cell x) =+      ( maybe+            (Left $ "\nMissing label for " <> (show x))+            (Right . Species . unLabel)+            (Map.lookup (Id x) lm)+      )+        >>= Right . (, Seq.singleton . Cell $ x)++-- | Load the populations from a list of files. If a label map is provided, the+-- species are the labels, otherwise they are the clusters.+loadPopulation :: Maybe LabelMap+               -> PriorPath+               -> IO (Either String Population)+loadPopulation lm (PriorPath path) = do+    dirExist <- FP.doesDirectoryExist path+    fileExist <- FP.doesFileExist path+    res <- case (dirExist, fileExist) of+        (False, False) -> return $ Left "\nInput does not exist."+        (_, True)      -> runExceptT $ do+            pop <- ExceptT . loadPopulationCsv . PriorPath $ path+            return pop+        otherwise      -> runExceptT $ do+            let crInput = path FP.</> "cluster_results.json"++            pop <- ExceptT+                 . fmap ((=<<) priorToPopulation . A.eitherDecode)+                 . B.readFile+                 $ crInput++            return pop++    return . maybe res (\x -> res >>= popToLabelPop x) $ lm
+ src/TooManyCells/Diversity/Plot.hs view
@@ -0,0 +1,153 @@+{- TooManyCells.Diversity.Plot+Gregory W. Schwartz++Collects the functions pertaining to the plotting of data.+-}++{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE QuasiQuotes #-}++module TooManyCells.Diversity.Plot+    ( plotDiversity+    , plotChao1+    , plotRarefaction+    , plotDiversityR+    , plotChao1R+    , plotRarefactionR+    ) where++-- Remote+import BirchBeer.Types+import Diagrams.Prelude+import Diagrams.Backend.Cairo+import Data.Char (toUpper)+import Data.Colour.Palette.BrewerSet (ColorCat (..), brewerSet)+import qualified Data.Colour.Palette.BrewerSet as Brewer+import Control.Lens+import Control.Monad (forM)+import Language.R as R+import Language.R.QQ (r)+import Plots+import Plots.Axis.Line+import qualified Data.Text as T++-- Local+import TooManyCells.Diversity.Types+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types++-- | Get the label of a population diversity as a String.+getPopLabel :: PopulationDiversity -> String+getPopLabel = T.unpack . unLabel . popLabel++-- | Plot the diversity of a group of populations.+plotDiversity :: [PopulationDiversity] -> Diagram B+plotDiversity xs = renderAxis $ r2Axis &~ do+    namedBarPlot (fmap (\x -> (getPopLabel x, unDiversity . popDiversity $ x)) xs) $ do+        vertical .= True+    yMin ?= 0+    hideGridLines+    hide (xAxis . minorTicks)+    hide (xAxis . majorTicks)+    plotColour .= black+    yLabel .= "Diversity"++-- | Plot the Chao1 of a group of populations.+plotChao1 :: [PopulationDiversity] -> Diagram B+plotChao1 xs = renderAxis $ r2Axis &~ do+    namedBarPlot (fmap (\x -> (getPopLabel x, unChao1 . popChao1 $ x)) xs) $ do+        vertical .= True+    hideGridLines+    yMin ?= 0+    hide (xAxis . minorTicks)+    hide (xAxis . majorTicks)+    plotColour .= black+    yLabel .= "Chao1"++-- | Plot the rarefaction curves of a group of populations.+plotRarefaction :: [PopulationDiversity] -> Diagram B+plotRarefaction xs = renderAxis $ r2Axis &~ do+    forM xs $ \pop -> do+        linePlot (fmap (over _2 unY . over _1 unX) . unRarefaction . popRarefaction $ pop) $ do+            key . getPopLabel $ pop++    hideGridLines+    xAxis.axisLineType .= LeftAxisLine+    yAxis.axisLineType .= LeftAxisLine+    axisColourMap .= (colourMap . zip [1..] . brewerSet Brewer.Set1 $ 9)+    xLabel .= "Subsample (# cells)"+    yLabel .= "Estimated clusters (# clusters)"++-- | Plot the diversity of a group of populations.+plotDiversityR :: [Colour Double] -> [PopulationDiversity] -> R s (R.SomeSEXP s)+plotDiversityR colors pops = do+    let labels = fmap getPopLabel pops+        values = fmap (unDiversity . popDiversity) pops+        colorsR = fmap (fmap toUpper . sRGB24show) colors++    [r| suppressMessages(library(ggplot2))+        suppressMessages(library(cowplot))++        df = data.frame(x = labels_hs, y = values_hs)++        ggplot(df, aes(x = reorder(x, -y), y = y, fill = x)) ++            geom_col() ++            xlab("") ++            ylab("Diversity") ++            scale_fill_manual(values = as.character(colorsR_hs)) ++            guides(fill = "none") ++            theme(aspect.ratio = 1, axis.text.x = element_text(angle = 315, hjust = 0))+    |]++-- | Plot the Chao1 of a group of populations.+plotChao1R :: [Colour Double] -> [PopulationDiversity] -> R s (R.SomeSEXP s)+plotChao1R colors pops = do+    let labels = fmap getPopLabel pops+        values = fmap (unChao1 . popChao1) pops+        colorsR = fmap (fmap toUpper . sRGB24show) colors++    [r| suppressMessages(library(ggplot2))+        suppressMessages(library(cowplot))++        df = data.frame(x = labels_hs, y = values_hs)++        ggplot(df, aes(x = reorder(x, -y), y = y, fill = x)) ++            geom_col() ++            xlab("") ++            ylab("Chao1") ++            scale_fill_manual(values = as.character(colorsR_hs)) ++            guides(fill = "none") ++            theme(aspect.ratio = 1, axis.text.x = element_text(angle = 315, hjust = 0))+    |]++-- | Plot the rarefaction curves of a group of populations.+plotRarefactionR ::+     [Colour Double] -> [PopulationDiversity] -> R s (R.SomeSEXP s)+plotRarefactionR colors pops = do+    let labels =+            concatMap+                (\pop ->+                      replicate+                          (length . unRarefaction . popRarefaction $ pop)+                          (getPopLabel pop)+                )+                pops+        valuesX =+            fmap (unX . fst) . concatMap (unRarefaction . popRarefaction) $ pops+        valuesY =+            fmap (unY . snd) . concatMap (unRarefaction . popRarefaction) $ pops+        colorsR = fmap (fmap toUpper . sRGB24show) colors++    [r| suppressMessages(library(ggplot2))+        suppressMessages(library(cowplot))++        df = data.frame(x = valuesX_hs, y = valuesY_hs, labels = labels_hs)++        ggplot(df, aes(x = x, y = y, color = labels)) ++            geom_line() ++            xlab("Subsample") ++            ylab("Estimated richness") ++            scale_color_manual(values = as.character(colorsR_hs)) ++            guides(color = guide_legend(title = "")) ++            theme(aspect.ratio = 0.5)+    |]
+ src/TooManyCells/Diversity/Types.hs view
@@ -0,0 +1,76 @@+{- TooManyCells.Diversity.Types+Gregory W. Schwartz++Collects the types used in the program+-}++{-# LANGUAGE StrictData #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE OverloadedStrings #-}++module TooManyCells.Diversity.Types where++-- Remote+import BirchBeer.Types+import Data.List (intercalate)+import GHC.Generics+import qualified Data.ByteString.Char8 as B+import qualified Data.Csv as CSV+import qualified Data.Sequence as Seq+import qualified Data.Text as T+import qualified Data.Map.Strict as Map++-- Local+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types+++-- Basic+newtype Size        = Size { unSize :: Integer } deriving (Eq, Ord, Read, Show)+newtype Start       = Start { unStart :: Integer } deriving (Eq, Ord, Read, Show)+newtype Interval    = Interval { unInterval :: Integer } deriving (Eq, Ord, Read, Show)+newtype End         = End { unEnd :: Integer } deriving (Eq, Ord, Read, Show)+newtype Species     = Species { unSpecies :: T.Text } deriving (Eq, Ord, Read, Show)+newtype Diversity   = Diversity+    { unDiversity :: Double+    } deriving (Eq,Ord,Read,Show,Generic)+newtype Chao1       = Chao1+    { unChao1 :: Double+    } deriving (Eq,Ord,Read,Show,Generic)+newtype Rarefaction = Rarefaction+    { unRarefaction :: [(X, Y)]+    } deriving (Eq,Ord,Read,Show,Generic)+newtype Population = Population+    { unPopulation :: Map.Map Species (Seq.Seq Cell)+    } deriving (Eq, Ord, Read, Show, Generic)++-- Advanced+data PopulationDiversity = PopulationDiversity+    { popLabel       :: Label+    , popDiversity   :: Diversity+    , popChao1       :: Chao1+    , popRarefaction :: Rarefaction+    }+    deriving (Generic)++instance CSV.ToField Label where+  toField = B.pack . T.unpack . unLabel+instance CSV.ToField Diversity where+  toField = B.pack . show . unDiversity+instance CSV.ToField Chao1 where+  toField = B.pack . show . unChao1+instance CSV.ToField Rarefaction where+  toField = B.pack+          . intercalate "/"+          . fmap (\(X !x, Y !y) -> show x <> "-" <> show y)+          . unRarefaction++instance CSV.ToNamedRecord PopulationDiversity where+  toNamedRecord (PopulationDiversity l d _ r) =+    CSV.namedRecord+      ["label" CSV..= l, "diversity" CSV..= d, "rarefaction" CSV..= r]++instance CSV.DefaultOrdered PopulationDiversity where+  headerOrder _ = CSV.header ["label", "diversity", "rarefaction"]
+ src/TooManyCells/File/Types.hs view
@@ -0,0 +1,52 @@+{- TooManyCells.File.Types+Gregory W. Schwartz++Collects the file and argument types used in the program.+-}++{-# LANGUAGE StrictData #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE QuasiQuotes #-}++module TooManyCells.File.Types where++-- Remote+import Data.Colour.Palette.BrewerSet (Kolor)+import Data.Colour.SRGB (Colour (..), RGB (..), toSRGB)+import Data.Map.Strict (Map)+import Data.Text (Text)+import Data.Vector (Vector)+import GHC.Generics (Generic)+import Language.R as R+import Language.R.QQ (r)+import Math.Clustering.Hierarchical.Spectral.Sparse (ShowB)+import Math.Clustering.Hierarchical.Spectral.Types (ClusteringTree, ClusteringVertex)+import Math.Modularity.Types (Q (..))+import qualified Data.Aeson as A+import qualified Data.Clustering.Hierarchical as HC+import qualified Data.Graph.Inductive as G+import qualified Data.Sequence as Seq+import qualified Data.Sparse.Common as S+import qualified Numeric.LinearAlgebra as H++-- Local++-- Basic+newtype DendrogramFile  = DendrogramFile { unDendrogramFile :: FilePath }+newtype CellFile        = CellFile { unCellFile :: FilePath }+newtype GeneFile        = GeneFile { unGeneFile :: FilePath }+newtype MatrixFile = MatrixFile+    { unMatrixFile :: FilePath+    } deriving (Read,Show)+newtype ProjectionFile  = ProjectionFile { unProjectionFile :: FilePath }+newtype CellWhitelistFile = CellWhitelistFile+    { unCellWhitelistFile :: FilePath+    }+newtype PriorPath   = PriorPath+    { unPriorPath :: FilePath+    } deriving (Eq,Ord,Read,Show)+newtype OutputDirectory  = OutputDirectory { unOutputDirectory :: FilePath }++-- Advanced
+ src/TooManyCells/MakeTree/Adjacency.hs view
@@ -0,0 +1,68 @@+{- TooManyCells.MakeTree.Adjacency+Gregory W. Schwartz++Collects functions pertaining to calculating similarities and adjacency+matrices.+-}++module TooManyCells.MakeTree.Adjacency+    ( cosineSimilarityDense+    , cosineSimilaritySparse+    , getDenseAdjacencyMat+    , getSparseAdjacencyMat+    ) where++-- Remote+import qualified Numeric.LinearAlgebra as H+import qualified Data.Sparse.Common as S++-- Local+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types+import TooManyCells.Matrix.Utility++-- | Get the cosine similarity between two vectors.+cosineSimilarityDense :: H.Vector Double -> H.Vector Double -> Double+cosineSimilarityDense v w = H.dot v w / (H.norm_2 v * H.norm_2 w)++-- | Get the cosine similarity between two vectors.+cosineSimilaritySparse :: S.SpVector Double -> S.SpVector Double -> Double+cosineSimilaritySparse v w = dot v w / (norm2 v * norm2 w)+  where+    dot x = sum . S.liftU2 (*) x+    norm2 = sqrt . sum . fmap (** 2)++-- | Get an adjacency matrix based on a matrix where each row is an observation+-- and the adjacencies are cosine similarities.+getDenseAdjacencyMat :: MatObsRow -> AdjacencyMat+getDenseAdjacencyMat (MatObsRow sparseMat) =+    AdjacencyMat $ H.assoc (size, size) 0 assocList+  where+    mat = sparseToHMat sparseMat+    size :: Int+    size       = H.rows mat+    getSim :: Int -> Int -> Double+    getSim i j = if i == j+                    then 0+                    else cosineSimilarityDense (mat H.! i) (mat H.! j)+    assocList :: [((Int, Int), Double)]+    assocList  = (\i j -> ((i, j), getSim i j))+             <$> [0,1 .. (size - 1)]+             <*> [0,1 .. (size - 1)]++-- | Get an adjacency matrix based on a matrix where each row is an observation+-- and the adjacencies are cosine similarities.+getSparseAdjacencyMat :: MatObsRow -> AdjacencyMat+getSparseAdjacencyMat (MatObsRow mat) =+    AdjacencyMat $ H.assoc (size, size) 0 assocList+  where+    size :: Int+    size       = S.nrows mat+    getSim :: Int -> Int -> Double+    getSim i j = if i == j+                    then 0+                    else cosineSimilaritySparse (S.extractRow mat i) (S.extractRow mat j)+    assocList :: [((Int, Int), Double)]+    assocList  = (\i j -> ((i, j), getSim i j))+             <$> [0,1 .. (size - 1)]+             <*> [0,1 .. (size - 1)]
+ src/TooManyCells/MakeTree/Clumpiness.hs view
@@ -0,0 +1,105 @@+{- TooManyCells.MakeTree.Clumpiness+Gregory W. Schwartz++Collects the functions pertaining to finding the clumpiness from a single cell+dendrogram.+-}++{-# LANGUAGE PackageImports #-}+{-# LANGUAGE OverloadedStrings #-}++module TooManyCells.MakeTree.Clumpiness+    ( dendToClumpList+    , treeToClumpList+    , clumpToCsv+    ) where++-- Remote+import BirchBeer.Types+import Data.Maybe (fromMaybe)+import Data.Monoid ((<>))+import Data.Tree (Tree(..))+import qualified "find-clumpiness" Clumpiness as Clump+import qualified "find-clumpiness" Types as Clump+import qualified Control.Lens as L+import qualified Data.ByteString.Lazy.Char8 as B+import qualified Data.Clustering.Hierarchical as HC+import qualified Data.Csv as CSV+import qualified Data.Map.Strict as Map+import qualified Data.Sequence as Seq+import qualified Data.Text as T+import qualified Data.Vector as V++-- Local+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types++-- | Convert a single cell dendrogram to a workable format for clumpiness.+dendToClumpDend+    :: (TreeItem a)+    => LabelMap+    -> HC.Dendrogram (V.Vector a)+    -> Either String (Tree Clump.NodeLabel)+dendToClumpDend (LabelMap labelMap) dend = do+    inputTree <- sequence+               . fmap ( fmap (Seq.fromList . fmap unLabel . V.toList)+                      . sequence+                      . fmap ( (\ x+                               -> Map.findWithDefault+                                   (Left ("\nCell has no label: " <> show x))+                                   x+                                   (fmap Right labelMap)+                               )+                               . getId+                             )+                      )+               $ dend++    return $ Clump.makeWorkable inputTree++-- | Convert a single cell tree to a workable format for clumpiness.+treeToClumpTree+    :: (TreeItem a)+    => LabelMap+    -> Tree (TreeNode (V.Vector a))+    -> Either String (Tree Clump.NodeLabel)+treeToClumpTree (LabelMap labelMap) tree = do+    inputTree <- sequence+               . fmap ( fmap (Seq.fromList . fmap unLabel . V.toList)+                      . sequence+                      . fmap ( (\ x+                               -> Map.findWithDefault+                                   (Left ("\nCell has no label: " <> show x))+                                   x+                                   (fmap Right labelMap)+                               )+                               . getId+                             )+                      . fromMaybe V.empty+                      . L.view item+                      )+               $ tree++    return $ Clump.makeWorkable inputTree++-- | Format clumpiness output to a CSV.+clumpToCsv :: [(T.Text, T.Text, Double)] -> B.ByteString+clumpToCsv = (<>) "label1,label2,value\n" . CSV.encode++-- | Get the clumpiness of the single cell labels for a dendrogram.+dendToClumpList+    :: Clump.Exclusivity+    -> LabelMap+    -> HC.Dendrogram (V.Vector CellInfo)+    -> Either String [(T.Text, T.Text, Double)]+dendToClumpList exclusivity labelMap =+    fmap (Clump.getClumpiness exclusivity False False) . dendToClumpDend labelMap++-- | Get the clumpiness of the single cell labels for a tree.+treeToClumpList+    :: Clump.Exclusivity+    -> LabelMap+    -> Tree (TreeNode (V.Vector CellInfo))+    -> Either String [(T.Text, T.Text, Double)]+treeToClumpList exclusivity labelMap =+    fmap (Clump.getClumpiness exclusivity False False) . treeToClumpTree labelMap
+ src/TooManyCells/MakeTree/Cluster.hs view
@@ -0,0 +1,255 @@+{- TooManyCells.MakeTree.Cluster+Gregory W. Schwartz++Collects the functions pertaining to the clustering of columns.+-}++{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE OverloadedStrings #-}++module TooManyCells.MakeTree.Cluster+    ( hdbscan+    , clustersToClusterList+    , hClust+    , hSpecClust+    , assignClusters+    , dendrogramToClusterList+    , treeToClusterList+    , clusterDiversity+    ) where++-- Remote+import BirchBeer.Types+import BirchBeer.Utility (getGraphLeaves, getGraphLeavesWithParents, dendrogramToGraph, dendToTree, treeToGraph)+import Control.Monad (join)+import Data.Function (on)+import Data.List (sortBy, groupBy, zip4, genericLength)+import Data.Int (Int32)+import Data.Maybe (fromMaybe, catMaybes, mapMaybe)+import Data.Monoid ((<>))+import Data.Tree (Tree (..))+import Data.Tuple (swap)+import H.Prelude (io)+import Language.R as R+import Language.R.QQ (r)+import Math.Clustering.Hierarchical.Spectral.Sparse (hierarchicalSpectralCluster, B (..))+import Math.Clustering.Hierarchical.Spectral.Types (clusteringTreeToDendrogram, getClusterItemsDend, EigenGroup (..))+import Math.Diversity.Diversity (diversity)+import Statistics.Quantile (continuousBy, s)+import System.IO (hPutStrLn, stderr)+import Safe (headMay)+import TextShow (showt)+import qualified Control.Lens as L+import qualified Data.ByteString.Lazy.Char8 as B+import qualified Data.Clustering.Hierarchical as HC+import qualified Data.Csv as CSV+import qualified Data.Foldable as F+import qualified Data.Graph.Inductive as G+import qualified Data.Map.Strict as Map+import qualified Data.Sequence as Seq+import qualified Data.Sparse.Common as S+import qualified Data.Text as T+import qualified Data.Vector as V+import qualified Data.Vector.Unboxed as VU+import qualified Numeric.LinearAlgebra as H++-- Local+import TooManyCells.MakeTree.Adjacency+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types+import TooManyCells.Diversity.Types++-- | Cluster cLanguage.R.QQ (r)olumns of a sparse matrix using HDBSCAN.+hdbscan :: RMatObsRow s -> R s (R.SomeSEXP s)+hdbscan (RMatObsRow mat) = do+    [r| library(dbscan) |]++    clustering  <- [r| hdbscan(mat_hs, minPts = 5) |]++    return clustering++-- | Hierarchical clustering.+hClust :: SingleCells -> ClusterResults+hClust sc =+    ClusterResults { _clusterList = clustering+                   , _clusterDend = dendToTree cDend+                   }+  where+    cDend = fmap ( V.singleton+                 . (\ (!w, _, !y)+                   -> CellInfo { _barcode = w, _cellRow = y }+                   )+                 )+            dend+    clustering = assignClusters+               . fmap ( fmap ((\(!w, _, !y) -> CellInfo w y))+                      . HC.elements+                      )+               . flip HC.cutAt (findCut dend)+               $ dend+    dend = HC.dendrogram HC.CLINK items euclDist+    euclDist x y =+        sqrt . sum . fmap (** 2) $ S.liftU2 (-) (L.view L._2 y) (L.view L._2 x)+    items = (\ fs+            -> zip3+                   (V.toList $ _rowNames sc)+                   fs+                   (fmap Row . take (V.length . _rowNames $ sc) . iterate (+ 1) $ 0)+            )+          . S.toRowsL+          . unMatObsRow+          . _matrix+          $ sc++-- | Assign clusters to values. Thanks to hierarchical clustering, we can have+-- a cell belong to multiple clusters.+assignClusters :: [[a]] -> [(a, [Cluster])]+assignClusters =+    concat . zipWith (\c -> flip zip (repeat c)) (fmap ((:[]) . Cluster) [1..])++-- | Find cut value.+findCut :: HC.Dendrogram a -> HC.Distance+findCut = continuousBy s 9 10 . VU.fromList . F.toList . flattenDist+  where+    flattenDist (HC.Leaf _)          = Seq.empty+    flattenDist (HC.Branch !d !l !r) =+        (Seq.<|) d . (Seq.><) (flattenDist l) . flattenDist $ r++-- | Convert the cluster object from hdbscan to a cluster list.+clustersToClusterList :: SingleCells+                      -> R.SomeSEXP s+                      -> R s [(Cell, Cluster)]+clustersToClusterList sc clustering = do+    io . hPutStrLn stderr $ "Calculating clusters."+    clusters <- [r| clustering_hs$cluster |]+    return+        . zip (V.toList . _rowNames $ sc)+        . fmap (Cluster . fromIntegral)+        $ (R.fromSomeSEXP clusters :: [Int32])++-- | Hierarchical spectral clustering.+hSpecClust :: EigenGroup+           -> NormType+           -> Maybe NumEigen+           -> SingleCells+           -> (ClusterResults, ClusterGraph CellInfo)+hSpecClust eigenGroup norm numEigen sc =+    ( ClusterResults { _clusterList = clustering+                     , _clusterDend = dendToTree dend+                     }+    , gr+    )+  where+    clustering :: [(CellInfo, [Cluster])]+    clustering =+        concatMap (\ (!ns, (_, !xs))+                  -> zip (maybe [] F.toList xs) . repeat . fmap Cluster $ ns+                  )+            . F.toList+            . flip getGraphLeavesWithParents 0+            . unClusterGraph+            $ gr+    gr         = dendrogramToGraph dend+    dend       = clusteringTreeToDendrogram tree+    tree       = hSpecCommand norm+               . Left+               . unMatObsRow+               . _matrix+               $ sc+    items      = V.zipWith+                    (\x y -> CellInfo x y)+                    (_rowNames sc)+                    (fmap Row . flip V.generate id . V.length . _rowNames $ sc)+    hSpecCommand TfIdfNorm   =+        hierarchicalSpectralCluster+          eigenGroup+          True+          (fmap unNumEigen numEigen)+          Nothing+          Nothing+          items+    hSpecCommand BothNorm =+        hierarchicalSpectralCluster+          eigenGroup+          True+          (fmap unNumEigen numEigen)+          Nothing+          Nothing+          items+    hSpecCommand _        =+        hierarchicalSpectralCluster+          eigenGroup+          False+          (fmap unNumEigen numEigen)+          Nothing+          Nothing+          items++dendrogramToClusterList :: HC.Dendrogram (V.Vector CellInfo)+                        -> [(CellInfo, [Cluster])]+dendrogramToClusterList =+    concatMap (\ (!ns, (_, !xs))+                -> zip (maybe [] F.toList xs) . repeat . fmap Cluster $ ns+                )+        . F.toList+        . flip getGraphLeavesWithParents 0+        . unClusterGraph+        . dendrogramToGraph++treeToClusterList :: Tree (TreeNode (V.Vector CellInfo))+                        -> [(CellInfo, [Cluster])]+treeToClusterList =+    concatMap (\ (!ns, (_, !xs))+                -> zip (maybe [] F.toList xs) . repeat . fmap Cluster $ ns+                )+        . F.toList+        . flip getGraphLeavesWithParents 0+        . unClusterGraph+        . treeToGraph++-- | Find the diversity of each leaf cluster.+clusterDiversity :: Order+                 -> LabelMap+                 -> ClusterResults+                 -> Either String [(Cluster, Diversity, Size)]+clusterDiversity (Order order) (LabelMap lm) = do+    let getDiversityOfCluster :: [(CellInfo, [Cluster])]+                              -> Either String [(Cluster, Diversity, Size)]+        getDiversityOfCluster =+            join+                . fmap ( sequence+                       . fmap+                            (\ (!c, !xs)+                            -> do+                                diversities <- fmap (Diversity . diversity order)+                                                . sequence+                                                . fmap cellInfoToLabel+                                                $ xs+                                return (c, diversities, Size $ genericLength xs)+                            )+                       )+                . groupCellsByCluster+        cellInfoToLabel :: CellInfo -> Either String Label+        cellInfoToLabel =+            flip (Map.findWithDefault (Left "\nCell missing a label.")) (fmap Right lm)+                . Id+                . unCell+                . _barcode+        groupCellsByCluster :: [(CellInfo, [Cluster])]+                            -> Either String [(Cluster, [CellInfo])]+        groupCellsByCluster = sequence+                            . fmap assignCluster+                            . groupBy ((==) `on` (headMay . snd))+                            . sortBy (compare `on` (headMay . snd))+        assignCluster :: [(CellInfo, [Cluster])] -> Either String (Cluster, [CellInfo])+        assignCluster [] = Left "\nEmpty cluster."+        assignCluster all@(x:_) = do+            cluster <- fromMaybe (Left "\nNo cluster for cell.")+                    . fmap Right+                    . headMay+                    . snd+                    $ x+            return (cluster, fmap fst all)++    getDiversityOfCluster . _clusterList
+ src/TooManyCells/MakeTree/Load.hs view
@@ -0,0 +1,75 @@+{- TooManyCells.MakeTree.Load+Gregory W. Schwartz++Collects the functions pertaining to loading labels for the tree.+-}++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE OverloadedStrings #-}++module TooManyCells.MakeTree.Load+    ( loadClusterResultsFiles+    , loadClusterResults+    ) where++-- Remote+import BirchBeer.Load+import BirchBeer.Types+import BirchBeer.Utility+import Control.DeepSeq (force)+import Control.Exception (evaluate)+import Control.Monad.Except (runExceptT, ExceptT (..))+import Control.Monad.Managed (with, liftIO, Managed (..))+import Data.Char (ord)+import Data.Matrix.MatrixMarket (readMatrix)+import Data.Maybe (fromMaybe, maybe)+import Data.Monoid ((<>))+import Data.Vector (Vector)+import Safe+import qualified Control.Lens as L+import qualified Data.Aeson as A+import qualified Data.ByteString.Lazy.Char8 as B+import qualified Data.ByteString.Streaming.Char8 as BS+import qualified Data.Csv as CSV+import qualified Data.Foldable as F+import qualified Data.Map as Map+import qualified Data.Sparse.Common as HS+import qualified Data.Text as T+import qualified Data.Text.Read as T+import qualified Data.Vector as V+import qualified Numeric.LinearAlgebra as H+import qualified Streaming as S+import qualified Streaming.Cassava as S+import qualified Streaming.Prelude as S+import qualified Streaming.With.Lifted as SW++-- Local+import TooManyCells.File.Types+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types++-- | Load a format for the tree and results from a file.+loadClusterResultsFiles :: FilePath -> FilePath -> IO ClusterResults+loadClusterResultsFiles clusterListFile treeFile = do+  clusterList <-+    fmap (either error id . A.eitherDecode) . B.readFile $ clusterListFile+  tree        <-+    fmap (either error id . A.eitherDecode) . B.readFile $ treeFile++  return $ ClusterResults clusterList tree++-- | Load a format for the tree and results from a file.+loadClusterResults :: FilePath -> IO ClusterResults+loadClusterResults file = do+  dend <-+    fmap (fmap clusterResultConversion . A.eitherDecode) . B.readFile $ file+  tree <- fmap A.eitherDecode . B.readFile $ file++  return . either error id $ dend <> tree++-- | Convert a dendrogram type to a tree type in the cluster results.+clusterResultConversion :: ClusterResultsDend -> ClusterResults+clusterResultConversion cr =+  ClusterResults { _clusterList = _clusterList' cr+                 , _clusterDend = dendToTree $ _clusterDend' cr+                 }
+ src/TooManyCells/MakeTree/Plot.hs view
@@ -0,0 +1,273 @@+{- TooManyCells.MakeTree.Plot+Gregory W. Schwartz++Collects the functions pertaining to plotting the clusterings.+-}++{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE NoMonomorphismRestriction #-}+{-# LANGUAGE GADTs #-}++module TooManyCells.MakeTree.Plot+    ( plotClustersR+    , plotLabelClustersR+    , plotClumpinessHeatmapR+    ) where++-- Remote+import BirchBeer.Types+import Control.Monad (forM, mapM, join)+import Control.Monad.State (State (..))+import Data.Colour (AffineSpace (..), withOpacity)+import Data.Colour.Names (black)+import Data.Colour.Palette.BrewerSet (brewerSet, ColorCat(..), Kolor)+import Data.Colour.SRGB (RGB (..), toSRGB, sRGB24show)+import Data.Function (on)+import Data.List (nub, sort, sortBy, foldl1', transpose, unzip3, unzip4)+import Data.Maybe (fromMaybe, catMaybes)+import Data.Tuple (swap)+import Diagrams.Backend.Cairo+-- import Diagrams.Dendrogram (dendrogramCustom, Width(..))+import Diagrams.Prelude+import Graphics.SVGFonts+import Language.R as R+import Language.R.QQ (r)+import Math.Clustering.Hierarchical.Spectral.Types (getClusterItemsDend)+import Plots+import Plots.Axis.ColourBar+import Plots.Legend+import qualified Control.Foldl as Fold+import qualified Control.Lens as L+import qualified Data.Clustering.Hierarchical as HC+import qualified Data.Colour.Palette.BrewerSet as Brewer+import qualified Data.Foldable as F+import qualified Data.Graph.Inductive as G+import qualified Data.GraphViz as G+import qualified Data.GraphViz.Attributes.Complete as G+import qualified Data.List.Split as Split+import qualified Data.Map.Strict as Map+import qualified Data.Sequence as Seq+import qualified Data.Set as Set+import qualified Data.Sparse.Common as S+import qualified Data.Text as T+import qualified Data.Vector as V+import qualified Diagrams.TwoD.GraphViz as G hiding (mkGraph)+import qualified Numeric.LinearAlgebra as H++-- Local+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types++-- | Get the projections and label for a cell.+getProjections :: ProjectionMap+               -> (CellInfo, Cluster)+               -> Maybe (Double, Double, String)+getProjections (ProjectionMap pm) (CellInfo { _barcode = !b }, Cluster !c) = do+    p <- Map.lookup b pm+    return $ (unX . fst $ p, unY . snd $ p, show c)+    +-- | Get the projections and label with colors for a cell.+getProjectionsColor :: LabelMap+                    -> ItemColorMap+                    -> ProjectionMap+                    -> (CellInfo, Cluster)+                    -> Maybe (Double, Double, String, String)+getProjectionsColor+  (LabelMap lm)+  (ItemColorMap icm)+  (ProjectionMap pm)+  (cell@(CellInfo { _barcode = !b }), Cluster !c) = do+  p <- Map.lookup b pm++  let barcodeToColor x = sRGB24show $ Map.findWithDefault black x icm+      barcodeToLabel x = Map.findWithDefault (Label "") x lm+      l = T.unpack . unLabel . barcodeToLabel . getId $ cell+      c = barcodeToColor . getId $ cell++  return $ (unX . fst $ p, unY . snd $ p, l, c)++-- -- | Plot clusters on a 2D axis.+-- plotClusters :: [(CellInfo, Cluster)] -> Axis B V2 Double+-- plotClusters vs = r2Axis &~ do++--     forM vs $ \(CellInfo { _projection = (X !x, Y !y)}, Cluster c) ->+--         scatterPlot [(x, y)] $ do+--             let color = (cycle colours2) !! c+--             plotMarker .= circle 1 # fc color # lwO 1 # lc color++--     hideGridLines++-- | Plot clusters.+plotClustersR :: String -> ProjectionMap -> [(CellInfo, [Cluster])] -> R s ()+plotClustersR outputPlot pm clusterList = do+    let clusterListOrdered =+            sortBy (compare `on` snd) . fmap (L.over L._2 head) $ clusterList -- The first element in the list is the main cluster.+        (xs, ys, cs) =+          unzip3 . catMaybes . fmap (getProjections pm) $ clusterListOrdered+    [r| suppressMessages(library(ggplot2))+        suppressMessages(library(cowplot))+        df = data.frame(x = xs_hs, y = ys_hs, c = cs_hs)+        df$c = factor(df$c, unique(df$c))+        p = ggplot(df, aes(x = x, y = y, color = factor(c))) ++                geom_point() ++                xlab("Projection 1") ++                ylab("Projection 2") ++                scale_color_discrete(guide = guide_legend(title = "Cluster", ncol = 3)) ++                theme(aspect.ratio = 1)++        suppressMessages(ggsave(p, file = outputPlot_hs))+    |]++    return ()++-- | Plot clusters.+plotLabelClustersR :: String+                   -> ProjectionMap+                   -> LabelMap+                   -> ItemColorMap +                   -> [(CellInfo, [Cluster])]+                   -> R s ()+plotLabelClustersR outputPlot pm lm icm clusterList = do+    let clusterListOrdered =+            sortBy (compare `on` snd) . fmap (L.over L._2 head) $ clusterList -- The first element in the list is the main cluster.+        (xs, ys, ls, cs) = unzip4+                         . catMaybes+                         . fmap (getProjectionsColor lm icm pm)+                         $ clusterListOrdered+    [r| suppressMessages(library(ggplot2))+        suppressMessages(library(cowplot))+        df = data.frame(x = xs_hs, y = ys_hs, l = ls_hs, c = cs_hs)+        colorMap = toupper(as.character(df$c))+        names(colorMap) = df$l+        # colorMap = colorMap[!duplicated(colorMap)]+        p = ggplot(df, aes(x = x, y = y, color = l)) ++                geom_point() ++                xlab("Projection 1") ++                ylab("Projection 2") ++                scale_color_manual( guide = guide_legend(title = "Label")+                                  , values = colorMap+                                  ) ++                theme(aspect.ratio = 1)++        suppressMessages(ggsave(p, file = outputPlot_hs))+    |]++    return ()++-- | Plot clusters using outputs from R.+plotClustersOnlyR :: String -> RMatObsRow s -> R.SomeSEXP s -> R s ()+plotClustersOnlyR outputPlot (RMatObsRow mat) clustering = do+    -- Plot hierarchy.+    [r| pdf(paste0(outputPlot_hs, "_hierarchy.pdf", sep = ""))+        plot(clustering_hs$hc)+        dev.off()+    |]++    -- Plot flat hierarchy.+    -- [r| pdf(paste0(outputPlot_hs, "_flat_hierarchy.pdf", sep = ""))+    --     plot(clustering_hs)+    --     dev.off()+    -- |]++    -- Plot clustering.+    [r| colors = rainbow(length(unique(clustering_hs$cluster)))+        names(colors) = unique(clustering_hs$cluster)++        pdf(paste0(outputPlot_hs, "_pca.pdf", sep = ""))++        plot( mat_hs[,c(1,2)]+            , col=clustering_hs$cluster+1+            , pch=ifelse(clustering_hs$cluster == 0, 8, 1) # Mark noise as star+            , cex=ifelse(clustering_hs$cluster == 0, 0.5, 0.75) # Decrease size of noise+            , xlab=NA+            , ylab=NA+            )+        colors = sapply(1:length(clustering_hs$cluster)+                       , function(i) adjustcolor(palette()[(clustering_hs$cluster+1)[i]], alpha.f = clustering_hs$membership_prob[i])+                       )+        points(mat_hs, col=colors, pch=20)++        dev.off()+    |]++    -- [r| library(tsne)++    --     colors = rainbow(length(unique(clustering_hs$cluster)))+    --     names(colors) = unique(clustering_hs$cluster)++    --     tsneMat = tsne(mat_hs, perplexity=50)++    --     pdf(paste0(outputPlot_hs, "_tsne.pdf", sep = ""))++    --     plot(tsneMat+    --         , col=clustering_hs$cluster+1+    --         , pch=ifelse(clustering_hs$cluster == 0, 8, 1) # Mark noise as star+    --         , cex=ifelse(clustering_hs$cluster == 0, 0.5, 0.75) # Decrease size of noise+    --         , xlab=NA+    --         , ylab=NA+    --         )+    --     colors = sapply(1:length(clustering_hs$cluster)+    --                    , function(i) adjustcolor(palette()[(clustering_hs$cluster+1)[i]], alpha.f = clustering_hs$membership_prob[i])+    --                    )+    --     points(tsneMat, col=colors, pch=20)++    --     dev.off()+    -- |]++    return ()++-- | Plot heatmap in R.+plotClumpinessHeatmapR :: String -> [(T.Text, T.Text, Double)] -> Either String (R s ())+plotClumpinessHeatmapR _ [] =+  Left "\nNo labels for leaves based on chosen clumpiness method, skipping clumpiness plot."+plotClumpinessHeatmapR outputPlot cs = Right $ do+    let xs = fmap (T.unpack . L.view L._1) cs+        ys = fmap (T.unpack . L.view L._2) cs+        vs = fmap (L.view L._3) cs++    [r| suppressMessages(library(ggplot2))+        suppressMessages(library(cowplot))+        library(scales)+        library(reshape2)++        df = data.frame(x = xs_hs, y = ys_hs, v = vs_hs)++        # Convert to wide to cluster.+        dfWide = dcast(df, x ~ y, value.var = c("v"))++        # Cluster and get order of labels.+        if (length(unique(df$x)) <= 2) {+            ord = c(1:length(unique(df$x)))+        } else {+            ord = suppressWarnings(hclust(dist(dfWide, method = "euclidean"))$order)+        }+        levels = colnames(dfWide)[-1][ord]++        df$x = factor(df$x, levels = levels)+        df$y = factor(df$y, levels = levels)++        # Plot.+        p = ggplot(df, aes(x = x, y = y, fill = v)) ++                geom_tile(color = "white") ++                coord_equal() ++                xlab("") ++                ylab("") ++                scale_fill_gradient2(guide = guide_colorbar(title = "Clumpiness"), midpoint = 0.5, low = muted("blue"), high = muted("red")) ++                theme(axis.text.x = element_text(angle = 315, hjust = 0))++        suppressMessages(ggsave(p, file = outputPlot_hs))+    |]++    return ()++-- | Plot a heatmap.+-- heatMapAxis :: [[Double]] -> Axis B V2 Double+-- heatMapAxis values = r2Axis &~ do+--     display colourBar+--     axisExtend .= noExtend++--     heatMap values $ heatMapSize .= V2 10 10
+ src/TooManyCells/MakeTree/Print.hs view
@@ -0,0 +1,137 @@+{- TooManyCells.MakeTree.Print+Gregory W. Schwartz++Collects the functions pertaining to the printing of information for the graph.+-}++{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE OverloadedStrings #-}++module TooManyCells.MakeTree.Print+    ( printClusterDiversity+    , printClusterInfo+    , printNodeInfo+    ) where++-- Remote+import BirchBeer.Types+import BirchBeer.Utility (getGraphLeaves, getGraphLeavesWithParents)+import Data.List (genericLength, intercalate)+import Data.Maybe (fromMaybe, mapMaybe, catMaybes)+import Data.Monoid ((<>))+import Safe (headMay)+import TextShow (showt)+import qualified Control.Lens as L+import qualified Data.ByteString.Lazy.Char8 as B+import qualified Data.Csv as CSV+import qualified Data.Foldable as F+import qualified Data.Graph.Inductive as G+import qualified Data.Map.Strict as Map+import qualified Data.Sequence as Seq+import qualified Data.Set as Set+import qualified Data.Text as T++-- Local+import TooManyCells.Diversity.Types+import TooManyCells.MakeTree.Types+import TooManyCells.MakeTree.Cluster++-- | Print the diversity of each leaf cluster.+printClusterDiversity :: [(Cluster, Diversity, Size)] -> B.ByteString+printClusterDiversity =+    (<>) "cluster,diversity,size\n" . CSV.encode+        . fmap ( L.over L._3 unSize+               . L.over L._2 unDiversity+               . L.over L._1 unCluster+               )++-- | Get the size and modularity path of each leaf cluster path. Modularity+-- starts from the parent of the cluster to the root for modularity.+clusterInfo :: (TreeItem a) => ClusterGraph a -> [(Cluster, [Double], [Int])]+clusterInfo (ClusterGraph gr) =+    F.toList+        . fmap (\ !x -> (Cluster . fst . snd $ x, getQs x, getSizes x))+        . getGraphLeavesWithParents gr+        $ 0+  where+    getSizes :: ([G.Node], a) -> [Int]+    getSizes = fmap getSize . fst+    getSize :: G.Node -> Int+    getSize = sum . fmap (maybe 0 Seq.length . snd) . getGraphLeaves gr+    getQs :: ([G.Node], a) -> [Double]+    getQs = mapMaybe getQ . fst+    getQ :: G.Node -> Maybe Double+    getQ  = fmap snd . headMay . G.lsuc gr++-- | Get the information of each leaf cluster path. Modularity+-- starts from the parent of the cluster to the root for modularity.+printClusterInfo :: (TreeItem a) => ClusterGraph a -> B.ByteString+printClusterInfo =+    (<>) "cluster,modularity,size\n" . CSV.encode+        . fmap ( L.over L._3 (T.intercalate "/" . fmap showt)+               . L.over L._2 (T.intercalate "/" . fmap showt)+               . L.over L._1 unCluster+               )+        . clusterInfo++-- | Get the counts and frequencies of all cell labels in a node.+getComposition ::+     (TreeItem a) => LabelMap -> ClusterGraph a -> G.Node -> LabelCompositions+getComposition (LabelMap lm) (ClusterGraph gr) n =+    LabelCompositions+        . Map.elems+        . Map.mapWithKey+            (\ !k !v -> LabelComposition k v (fromIntegral v / total))+        $ counts+  where+    counts = Map.fromListWith (+) . flip zip [1,1..] $ labels+    total  = genericLength labels+    labels = catMaybes+           . fmap (flip Map.lookup lm . getId)+           . concatMap (maybe [] F.toList . snd)+           . F.toList+           $ getGraphLeaves gr n++-- | Get various properties about the nodes in the ClusterGraph.+nodeInfo :: (TreeItem a) => Maybe LabelMap -> ClusterGraph a -> [NodeInfo]+nodeInfo lm (ClusterGraph gr) = fmap getNodeInfo . G.nodes $ gr+  where+    getNodeInfo x = NodeInfo+                        x+                        (getSize x)+                        (getProportion x)+                        (getQ x)+                        (fmap (\a -> getComposition a (ClusterGraph gr) x) lm)+                        (getNodeChildren gr x)+    getSize :: G.Node -> Int+    getSize = sum . fmap (maybe 0 Seq.length . snd) . getGraphLeaves gr+    getQ :: G.Node -> Maybe Double+    getQ  = fmap snd . headMay . G.lsuc gr+    getProportion :: G.Node -> Maybe Double+    getProportion n =+        case fmap fst $ G.lsuc gr n of+            [x, y] -> Just $ fromIntegral (getSize x) / fromIntegral (getSize y)+            []     -> Nothing+    getNodeChildren gr = Set.toAscList+                       . Set.fromList+                       . concatMap fst+                       . F.toList+                       . getGraphLeavesWithParents gr++-- | Print the node information to a string.+printNodeInfo ::+     (TreeItem a) => Maybe LabelMap -> ClusterGraph a -> B.ByteString+printNodeInfo lm =+    (<>) "node,size,proportion,modularity,composition,subtree\n"+        . CSV.encode+        . fmap (\ (NodeInfo n s p m c ch)+               -> ( n+                  , s+                  , maybe "" show p+                  , maybe "" show m+                  , maybe "" show c+                  , intercalate "/" . fmap show $ ch+                  )+               )+        . nodeInfo lm
+ src/TooManyCells/MakeTree/Types.hs view
@@ -0,0 +1,126 @@+{- TooManyCells.MakeTree.Types+Gregory W. Schwartz++Collects the types used in the program+-}++{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE StrictData #-}+{-# LANGUAGE TemplateHaskell #-}++module TooManyCells.MakeTree.Types where++-- Remote+import BirchBeer.Types+import Data.Colour (AlphaColour)+import Data.Colour.Palette.BrewerSet (Kolor)+import Data.Colour.SRGB (Colour (..), RGB (..), toSRGB)+import Data.List (intercalate)+import Data.Map.Strict (Map)+import Data.Monoid ((<>))+import Data.Text (Text)+import Data.Tree (Tree (..))+import Data.Vector (Vector)+import GHC.Generics (Generic)+import Language.R as R+import Language.R.QQ (r)+import Math.Clustering.Hierarchical.Spectral.Sparse (ShowB)+import Math.Clustering.Hierarchical.Spectral.Types (ClusteringTree, ClusteringVertex)+import Math.Modularity.Types (Q (..))+import TextShow (showt)+import qualified Control.Lens as L+import qualified Data.Aeson as A+import qualified Data.Aeson.TH as A+import qualified Data.Aeson.Types as A+import qualified Data.Clustering.Hierarchical as HC+import qualified Data.Graph.Inductive as G+import qualified Data.Sequence as Seq+import qualified Data.Sparse.Common as S+import qualified Data.Text as T+import qualified Numeric.LinearAlgebra as H++-- Local+import TooManyCells.Matrix.Types++-- Basic+newtype PreNormalization = PreNormalization+    { unPreNormalization :: Bool+    } deriving (Read,Show)+newtype IsLeaf = IsLeaf {unIsLeaf :: Bool} deriving (Eq, Ord, Read, Show)+newtype AdjacencyMat = AdjacencyMat+    { unAdjacencyMat :: H.Matrix H.R+    } deriving (Read,Show)+newtype LabelCompositions = LabelCompositions+  { unLabelCompositions :: [LabelComposition]+  }+newtype NumEigen = NumEigen+  { unNumEigen :: Int+  } deriving (Read, Show)+newtype L = L Double+newtype C = C Double+newtype H = H Double+newtype U = U Double+newtype V = V Double++-- Advanced+data ClusterResults = ClusterResults+    { _clusterList :: [(CellInfo, [Cluster])] -- Thanks to hierarchical clustering, we can have multiple clusters per cell.+    , _clusterDend :: Tree (TreeNode (Vector CellInfo))+    } deriving (Read,Show,Generic,A.FromJSON,A.ToJSON)++data ClusterResultsDend = ClusterResultsDend+    { _clusterList' :: [(CellInfo, [Cluster])] -- Thanks to hierarchical clustering, we can have multiple clusters per cell.+    , _clusterDend' :: HC.Dendrogram (Vector CellInfo)+    } deriving (Read,Show,Generic,A.FromJSON,A.ToJSON)++data ClusterInfo = ClusterInfo+    { _clusterId :: Cluster+    , _diversityPath :: [Int]+    , _sizePath :: [Double]+    }++data NodeInfo = NodeInfo+    { _nodeId   :: Int+    , _nodeSize :: Int+    , _nodeSplitProportion :: Maybe Double+    , _nodeModularity :: Maybe Double+    , _nodeLabelComposition :: Maybe LabelCompositions+    , _nodeChildren :: [G.Node]+    }++data LabelComposition = LabelComposition+    { _label :: Label+    , _count :: Int+    , _frequency :: Double+    }++instance Show LabelComposition where+    show (LabelComposition l c f) =+        (T.unpack . unLabel $ l) <> ": " <> show f <> " (" <> show c <> ")"++instance Show LabelCompositions where+    show = intercalate "/" . fmap show . unLabelCompositions++instance TreeItem CellInfo where+    getId = Id . unCell . _barcode++instance MatrixLike SingleCells where+    getMatrix   = unMatObsRow . _matrix+    getRowNames = fmap unCell . _rowNames+    getColNames = fmap unGene . _colNames++instance A.ToJSON Q where+    toEncoding = A.genericToEncoding A.defaultOptions+instance A.FromJSON Q++instance (A.ToJSON a) => A.ToJSON (ClusteringVertex a) where+    toEncoding = A.genericToEncoding A.defaultOptions+instance (A.FromJSON a) => A.FromJSON (ClusteringVertex a)++L.makeLenses ''ClusterResults+L.makeLenses ''ClusterResultsDend+-- A.deriveJSON (A.defaultOptions {A.fieldLabelModifier = drop 1}) ''ClusterResults -- So the field does not have an underscore. Unfortunately needed for backwards compatibility.
+ src/TooManyCells/Matrix/Load.hs view
@@ -0,0 +1,235 @@+{- TooManyCells.Matrix.Load+Gregory W. Schwartz++Collects the functions pertaining to loading the single cell data output from+cellranger.+-}++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE OverloadedStrings #-}++module TooManyCells.Matrix.Load+    ( matToSpMat+    , spMatToMat+    , loadCellrangerData+    , loadHMatrixData+    , loadSparseMatrixData+    , loadSparseMatrixDataStream+    , loadProjectionMap+    ) where++-- Remote+import BirchBeer.Types+import Control.DeepSeq (force)+import Control.Exception (evaluate)+import Control.Monad.Except (runExceptT, ExceptT (..))+import Control.Monad.Managed (with, liftIO, Managed (..))+import Data.Char (ord)+import Data.Matrix.MatrixMarket (readMatrix)+import Data.Maybe (fromMaybe, maybe)+import Data.Monoid ((<>))+import Data.Vector (Vector)+import Safe+import qualified Control.Lens as L+import qualified Data.ByteString.Lazy.Char8 as B+import qualified Data.ByteString.Streaming.Char8 as BS+import qualified Data.Csv as CSV+import qualified Data.Foldable as F+import qualified Data.Map as Map+import qualified Data.Sparse.Common as HS+import qualified Data.Text as T+import qualified Data.Text.Read as T+import qualified Data.Vector as V+import qualified Numeric.LinearAlgebra as H+import qualified Streaming as S+import qualified Streaming.Cassava as S+import qualified Streaming.Prelude as S+import qualified Streaming.With.Lifted as SW++-- Local+import TooManyCells.File.Types+import TooManyCells.Matrix.Types+import TooManyCells.Matrix.Utility++-- | Load output of cellranger.+loadCellrangerData+    :: GeneFile+    -> CellFile+    -> MatrixFile+    -> IO SingleCells+loadCellrangerData gf cf mf = do+    let csvOptsTabs = CSV.defaultDecodeOptions { CSV.decDelimiter = fromIntegral (ord '\t') }++    m <- fmap (MatObsRow . HS.transposeSM . matToSpMat)  -- We want observations as rows+       . readMatrix+       . unMatrixFile+       $ mf+    -- m <- fmap (MatObsRow . HS.transposeSM) . loadMatrixMarket $ mf -- We want observations as rows+    g <- fmap (\ x -> either error (fmap (Gene . fst)) ( CSV.decodeWith csvOptsTabs CSV.NoHeader x+                                       :: Either String (Vector (T.Text, T.Text))+                                        )+              )+       . B.readFile+       . unGeneFile+       $ gf+    c <- fmap (\ x -> either error (fmap (Cell . head)) ( CSV.decodeWith csvOptsTabs CSV.NoHeader x+                                       :: Either String (Vector [T.Text])+                                        )+              )+       . B.readFile+       . unCellFile+       $ cf++    return $+        SingleCells { _matrix   = m -- We want observations as rows.+                    , _rowNames = c+                    , _colNames = g+                    }++-- | Load an H Matrix in CSV format (rows were features) with row names and+-- column names.+loadHMatrixData :: Delimiter+                -> MatrixFile+                -> IO SingleCells+loadHMatrixData (Delimiter delim) mf = do+    let csvOpts = CSV.defaultDecodeOptions { CSV.decDelimiter = fromIntegral (ord delim) }++    all <- fmap (\ x -> either error id ( CSV.decodeWith csvOpts CSV.NoHeader x+                                       :: Either String (Vector (Vector T.Text))+                                        )+                )+         . B.readFile+         . unMatrixFile+         $ mf++    let c = fmap Cell . V.drop 1 . V.head $ all+        g = fmap (Gene . V.head) . V.drop 1 $ all+        m = MatObsRow+          . hToSparseMat+          . H.tr -- We want observations as rows+          . H.fromLists+          . fmap (fmap (either error fst . T.double) . drop 1 . V.toList)+          . drop 1+          . V.toList+          $ all++    return $+        SingleCells { _matrix   = m+                    , _rowNames = c+                    , _colNames = g+                    }++-- | Load a sparse matrix in CSV format (rows were features) with row names and+-- column names.+loadSparseMatrixData :: Delimiter+                     -> MatrixFile+                     -> IO SingleCells+loadSparseMatrixData (Delimiter delim) mf = do+    let csvOpts = CSV.defaultDecodeOptions+                    { CSV.decDelimiter = fromIntegral (ord delim) }+        strictRead path = (evaluate . force) =<< B.readFile path++    all <- fmap (\x -> either error id $ (CSV.decodeWith csvOpts CSV.NoHeader x :: Either String (V.Vector [T.Text])))+         . strictRead+         . unMatrixFile+         $ mf++    let c = V.fromList . fmap Cell . drop 1 . V.head $ all+        g = fmap (Gene . head) . V.drop 1 $ all+        m = MatObsRow+          . HS.sparsifySM+          . HS.fromColsV -- We want observations as rows+          . fmap (HS.vr . fmap (either error fst . T.double) . drop 1)+          . V.drop 1+          $ all++    return $+        SingleCells { _matrix   = m+                    , _rowNames = c+                    , _colNames = g+                    }++-- | Load a sparse matrix streaming in CSV format (rows were features) with row+-- names and column names.+loadSparseMatrixDataStream :: Delimiter+                           -> MatrixFile+                           -> IO SingleCells+loadSparseMatrixDataStream (Delimiter delim) mf = do+    let csvOpts = S.defaultDecodeOptions+                    { S.decDelimiter = fromIntegral (ord delim) }+        cS = fmap (S.first (fmap Cell . drop 1 . fromMaybe (error "\nNo header.")))+           . S.head+        gS = S.toList . S.map (Gene . head) . S.drop 1+        mS = S.toList+           . S.map (HS.sparsifySV . HS.vr . fmap (either error fst . T.double) . drop 1)+           . S.drop 1++    res <- flip with return $ do++        contents <- SW.withBinaryFileContents . unMatrixFile $ mf++        (c S.:> g S.:> m S.:> _) <-+            fmap (either (error . show) id)+                . runExceptT+                . cS+                . (S.store gS)+                . (S.store mS)+                . S.decode S.NoHeader+                $ (contents :: BS.ByteString (ExceptT S.CsvParseException Managed) ())++        let finalMat = MatObsRow . HS.sparsifySM . HS.fromColsL $ m -- We want observations as rows++        return $+            SingleCells { _matrix   = finalMat+                        , _rowNames = V.fromList c+                        , _colNames = V.fromList g+                        }++    return res++-- | Load a projection file to get a vector of projections.+loadProjectionFile :: ProjectionFile -> IO (Vector (X, Y))+loadProjectionFile =+    fmap (\ x -> either+                                error+                                (fmap getProjection . V.drop 1)+                                (CSV.decode CSV.NoHeader x :: Either String (Vector [T.Text]))+         )+        . B.readFile+        . unProjectionFile+  where+    getProjection [_, x, y] = ( X . either error fst . T.double $ x+                              , Y . either error fst . T.double $ y+                              )+    getProjection xs        =+        error $ "\nUnrecognized projection row: " <> show xs++-- | Load a projection file as a map.+loadProjectionMap :: ProjectionFile -> IO ProjectionMap+loadProjectionMap =+    fmap (\ x -> ProjectionMap+               . Map.fromList+               . V.toList+               . either+                  error+                  (fmap getProjection . V.drop 1)+               $ (CSV.decode CSV.NoHeader x :: Either String (Vector [T.Text]))+         )+        . B.readFile+        . unProjectionFile+  where+    getProjection [b, x, y] = ( Cell b+                              , ( X . either error fst . T.double $ x+                                , Y . either error fst . T.double $ y+                                )+                              )+    getProjection xs        =+        error $ "\nUnrecognized projection row: " <> show xs++-- | Decide to use first two values as the projection.+toPoint :: HS.SpVector Double -> (X, Y)+toPoint = (\[!x, !y] -> (X x, Y y)) . HS.toDenseListSV . HS.takeSV 2++-- | Project a matrix to first two dimensions.+projectMatrix :: MatObsRow -> Vector (X, Y)+projectMatrix = V.fromList . fmap toPoint . HS.toRowsL . unMatObsRow
+ src/TooManyCells/Matrix/Preprocess.hs view
@@ -0,0 +1,320 @@+{- TooManyCells.MakeTree.Preprocess+Gregory W. Schwartz++Collects functions pertaining to preprocessing the data.+-}++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE QuasiQuotes #-}++module TooManyCells.Matrix.Preprocess+    ( scaleRMat+    , scaleDenseMat+    , scaleSparseMat+    , uqScaleSparseMat+    , medScaleSparseMat+    , filterRMat+    , filterDenseMat+    , filterNumSparseMat+    , filterWhitelistSparseMat+    , getCellWhitelist+    , featureSelectionRandomForest+    , removeCorrelated+    , pcaRMat+    , pcaDenseMat+    ) where++-- Remote+import Data.List (sort)+import Data.Monoid ((<>))+import Data.Maybe (fromMaybe)+import H.Prelude (io)+import Language.R as R+import Language.R.QQ (r)+import MachineLearning.PCA (getDimReducer_rv)+import Statistics.Quantile (continuousBy, s)+import qualified Control.Lens as L+import qualified Data.Set as Set+import qualified Data.Sparse.Common as S+import qualified Data.Text as T+import qualified Data.Text.IO as T+import qualified Data.Vector as V+import qualified Data.Vector.Algorithms.Radix as V+import qualified Data.Vector.Storable as VS+import qualified Numeric.LinearAlgebra as H++-- Local+import TooManyCells.File.Types+import TooManyCells.Matrix.Types+import TooManyCells.Matrix.Utility++-- | Scale a matrix.+scaleRMat :: RMatObsRow s -> R s (RMatObsRow s)+scaleRMat (RMatObsRow mat) = do+    fmap+        RMatObsRow+        [r| mat = scale(t(mat_hs));+            t(mat[,colSums(!is.na(mat)) > 0])+        |]++-- | Scale a matrix based on the library size.+scaleDenseMat :: MatObsRow -> MatObsRow+scaleDenseMat (MatObsRow mat) = MatObsRow+                              . hToSparseMat+                              . H.fromColumns+                              . fmap scaleDenseMol+                              . H.toColumns+                              . H.fromRows+                              . fmap scaleDenseCell+                              . H.toRows+                              . sparseToHMat+                              $ mat++-- | Scale a matrix based on the library size.+scaleSparseMat :: MatObsRow -> MatObsRow+scaleSparseMat (MatObsRow mat) = MatObsRow+                               . S.sparsifySM+                               . S.fromColsL+                               . fmap scaleSparseMol+                               . S.toRowsL -- A bit confusing, but this returns the original columns due to the earlier fromColsL . toRowsL.+                               . S.fromColsL+                               . fmap scaleSparseCell+                               . S.toRowsL+                               $ mat++-- | Scale a matrix based on the upper quartile.+uqScaleSparseMat :: MatObsRow -> MatObsRow+uqScaleSparseMat (MatObsRow mat) = MatObsRow+                                 . S.sparsifySM+                                 . S.transposeSM+                                 . S.fromColsL+                                 . fmap uqScaleSparseCell+                                 . S.toRowsL+                                 $ mat++-- | Scale a matrix based on the median.+medScaleSparseMat :: MatObsRow -> MatObsRow+medScaleSparseMat (MatObsRow mat) = MatObsRow+                                 . S.sparsifySM+                                 . S.transposeSM+                                 . S.fromColsL+                                 . fmap medScaleSparseCell+                                 . S.toRowsL+                                 $ mat++-- | Scale a cell by the library size.+scaleDenseCell :: H.Vector H.R -> H.Vector H.R+scaleDenseCell xs = H.cmap (/ total) xs+  where+    total = H.sumElements xs++-- | Scale a cell by the library size.+scaleSparseCell :: S.SpVector Double -> S.SpVector Double+scaleSparseCell xs = fmap (/ total) xs+  where+    total = sum xs++-- | Upper quartile scale cells.+uqScaleSparseCell :: S.SpVector Double -> S.SpVector Double+uqScaleSparseCell xs = fmap (/ uq) xs+  where+    uq = continuousBy s 3 4+       . VS.fromList+       . filter (/= 0)+       . fmap snd+       . S.toListSV+       $ xs++-- | Median scale cells.+medScaleSparseCell :: S.SpVector Double -> S.SpVector Double+medScaleSparseCell xs = fmap (/ med) xs+  where+    med = continuousBy s 2 4+        . VS.fromList+        . filter (/= 0)+        . fmap snd+        . S.toListSV+        $ xs++-- | Median scale molecules across cells.+scaleDenseMol :: H.Vector H.R -> H.Vector H.R+scaleDenseMol xs = H.cmap (/ med) xs+  where+    med = continuousBy s 2 4 . VS.filter (/= 0) $ xs++-- | Median scale molecules across cells.+scaleSparseMol :: S.SpVector Double -> S.SpVector Double+scaleSparseMol xs = fmap (/ med) xs+  where+    med = continuousBy s 2 4+        . VS.fromList+        . filter (/= 0)+        . fmap snd+        . S.toListSV+        $ xs++-- | Filter a matrix to remove low count cells and genes.+filterDenseMat :: FilterThresholds -> SingleCells -> SingleCells+filterDenseMat (FilterThresholds (rowThresh, colThresh)) sc =+    SingleCells { _matrix   = m+                , _rowNames = r+                , _colNames = c+                }+  where+    m = MatObsRow . hToSparseMat $ filteredMat+    rowFilter = (>= rowThresh) . H.sumElements+    colFilter = (>= colThresh) . H.sumElements+    mat            = sparseToHMat . unMatObsRow . _matrix $ sc+    validRows = Set.fromList+              . fmap fst+              . filter (rowFilter . snd)+              . zip [0..]+              . H.toRows+              $ mat+    validCols = Set.fromList+              . fmap fst+              . filter (colFilter . snd)+              . zip [0..]+              . H.toColumns+              $ mat+    filteredMat = mat+             H.?? ( H.Pos (H.idxs (Set.toAscList validRows))+                  , H.Pos (H.idxs (Set.toAscList validCols))+                  )+    r = V.ifilter (\i _ -> Set.member i validRows)+      . _rowNames+      $ sc+    c = V.ifilter (\i _ -> Set.member i validCols)+      . _colNames+      $ sc++-- | Filter a matrix to remove low count cells and genes.+filterNumSparseMat :: FilterThresholds -> SingleCells -> SingleCells+filterNumSparseMat (FilterThresholds (rowThresh, colThresh)) sc =+    SingleCells { _matrix   = m+                , _rowNames = r+                , _colNames = c+                }+  where+    m = MatObsRow colFilteredMat+    rowFilter = (>= rowThresh) . sum+    colFilter = (>= colThresh) . sum+    mat            = unMatObsRow . _matrix $ sc+    mat'           = S.transposeSM mat+    validRows = Set.fromList+              . fmap fst+              . filter (rowFilter . snd)+              . zip [0..]+              . S.toRowsL+              $ mat+    validCols = Set.fromList+              . fmap fst+              . filter (colFilter . snd)+              . zip [0..]+              . S.toRowsL+              . S.transposeSM -- toRowsL is much faster.+              $ mat+    rowFilteredMat = S.transposeSM+                   . S.fromColsL -- fromRowsL still broken.+                   . fmap snd+                   . filter (flip Set.member validRows . fst)+                   . zip [0..]+                   . S.toRowsL+                   $ mat+    colFilteredMat = S.fromColsL+                   . fmap snd+                   . filter (flip Set.member validCols . fst)+                   . zip [0..]+                   . S.toRowsL -- Rows of transpose are faster.+                   . S.transposeSM+                   $ rowFilteredMat+    r = V.ifilter (\i _ -> Set.member i validRows)+      . _rowNames+      $ sc+    c = V.ifilter (\i _ -> Set.member i validCols)+      . _colNames+      $ sc++-- | Filter a matrix to keep whitelist cells.+filterWhitelistSparseMat :: CellWhitelist+                         -> SingleCells+                         -> SingleCells+filterWhitelistSparseMat (CellWhitelist wl) sc =+    sc { _matrix   = m+       , _rowNames = r+       }+  where+    m = MatObsRow rowFilteredMat+    mat            = unMatObsRow . _matrix $ sc+    validIdx       = V.modify V.sort+                   . V.map fst+                   . V.filter (\(_, !c) -> Set.member c wl)+                   . V.imap (\i v -> (i, v))+                   . _rowNames+                   $ sc+    rowFilteredMat = S.transposeSM+                   . S.fromColsL -- fromRowsL still broken.+                   . fmap (S.extractRow mat)+                   . V.toList+                   $ validIdx+    r = V.map (\x -> fromMaybe (error $ "\nWhitelist row index out of bounds (do the whitelist barcodes match the data?): " <> show x <> " out of " <> (show . length . _rowNames $ sc))+                   . (V.!?) (_rowNames sc)+                   $ x+              )+      $ validIdx++-- | Get a cell white list from a file.+getCellWhitelist :: CellWhitelistFile -> IO CellWhitelist+getCellWhitelist (CellWhitelistFile file) = do+    contents <- T.readFile file++    let whiteList = CellWhitelist+                  . Set.fromList+                  . fmap Cell+                  . filter (not . T.null)+                  . T.lines+                  $ contents++    return whiteList++-- | Filter a matrix to remove low count cells. R version.+filterRMat :: RMatObsRow s -> R s (RMatObsRow s)+filterRMat (RMatObsRow mat) =+    fmap RMatObsRow [r| mat = mat_hs[,colSums(mat_hs) >= 250] |]++-- | Perform feature selection on a matrix.+featureSelectionRandomForest :: RMatObsRow s -> R s (RMatObsRow s)+featureSelectionRandomForest (RMatObsRow mat) = do+    [r| suppressPackageStartupMessages(library(randomForest)) |]++    importance   <- [r| randomForest(mat_hs, na.action = na.omit)$importance |]+    importantMat <- [r| mat_hs[,importance_hs > sort(importance_hs, decreasing = TRUE)[10]] |]++    return . RMatObsRow $ importantMat++-- | Remove highly correlated (> 0.6) variables in a matrix.+removeCorrelated :: RMatObsRow s -> R s (RMatObsRow s)+removeCorrelated (RMatObsRow mat) = do+    [r| suppressPackageStartupMessages(library(caret)) |]++    cor   <- [r| cor(mat_hs) |]+    importantMat <- [r| mat_hs[,-findCorrelation(cor_hs, cutoff = 0.6, exact = FALSE)] |]++    return . RMatObsRow $ importantMat++-- | Conduct PCA on a matrix, using components > 5% of variance.+pcaRMat :: RMatObsRow s -> R s (RMatObsRow s)+pcaRMat (RMatObsRow mat) = do+    fmap+        RMatObsRow+        [r| mat = prcomp(t(mat_hs), tol = 0.95)$rotation+        |]++-- | Conduct PCA on a matrix, retaining a percentage of variance.+pcaDenseMat :: PCAVar -> MatObsRow -> MatObsRow+pcaDenseMat (PCAVar pcaVar) (MatObsRow mat) = do+    MatObsRow+        . hToSparseMat+        . L.view L._3+        . getDimReducer_rv (sparseToHMat mat)+        $ pcaVar
+ src/TooManyCells/Matrix/Types.hs view
@@ -0,0 +1,119 @@+{- TooManyCells.Matrix.Types+Gregory W. Schwartz++Collects the types used in the program concerning the matrix.+-}++{-# LANGUAGE StrictData #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE TemplateHaskell #-}++module TooManyCells.Matrix.Types where++-- Remote+import Control.DeepSeq (NFData (..))+import Data.Monoid (Monoid (..), mempty)+import Data.Colour.Palette.BrewerSet (Kolor)+import Data.Colour.SRGB (Colour (..), RGB (..), toSRGB)+import Data.Map.Strict (Map)+import Data.Text (Text)+import Data.Vector (Vector)+import GHC.Generics (Generic)+import Language.R as R+import Language.R.QQ (r)+import Math.Clustering.Hierarchical.Spectral.Sparse (ShowB)+import Math.Clustering.Hierarchical.Spectral.Types (ClusteringTree, ClusteringVertex)+import Math.Modularity.Types (Q (..))+import qualified Control.Lens as L+import qualified Data.Aeson as A+import qualified Data.Clustering.Hierarchical as HC+import qualified Data.Graph.Inductive as G+import qualified Data.Map as Map+import qualified Data.Sequence as Seq+import qualified Data.Set as Set+import qualified Data.Sparse.Common as S+import qualified Data.Vector as V+import qualified Numeric.LinearAlgebra as H++-- Local++-- Basic+newtype Cell = Cell+    { unCell :: Text+    } deriving (Eq,Ord,Read,Show,Generic,A.ToJSON, A.FromJSON)+newtype Cols            = Cols { unCols :: [Double] }+newtype Gene            = Gene { unGene :: Text } deriving (Eq, Ord, Read, Show, Generic)+instance NFData Gene+newtype CellWhitelist = CellWhitelist+    { unCellWhitelist :: Set.Set Cell+    } deriving (Eq,Ord,Read,Show)+newtype PCAVar = PCAVar+    { unPCAVar :: Double+    } deriving (Eq,Ord,Read,Show)+newtype NoFilterFlag = NoFilterFlag+    { unNoFilterFlag :: Bool+    } deriving (Read,Show)+newtype FilterThresholds = FilterThresholds+    { unFilterThresholds :: (Double, Double)+    } deriving (Read,Show)+newtype X = X+    { unX :: Double+    } deriving (Eq,Ord,Read,Show,Num,Generic,A.ToJSON,A.FromJSON)+newtype Y = Y+    { unY :: Double+    } deriving (Eq,Ord,Read,Show,Num,Generic,A.ToJSON,A.FromJSON)+newtype ProjectionMap = ProjectionMap+  { unProjectionMap :: Map.Map Cell (X, Y)+  }+newtype RMat s          = RMat { unRMat :: R.SomeSEXP s }+newtype RMatObsRow s    = RMatObsRow { unRMatObsRow :: R.SomeSEXP s }+newtype RMatFeatRow s   = RMatFeatRow { unRMatFeatRow :: R.SomeSEXP s }+newtype RMatScaled s    = RMatScaled { unRMatScaled :: R.SomeSEXP s }+newtype Row = Row+    { unRow :: Int+    } deriving (Eq,Ord,Read,Show,Generic,A.ToJSON,A.FromJSON)+newtype Rows            = Rows { unRows :: [Double] }+newtype Vals            = Vals { unVals :: [Double] }+newtype MatObsRow = MatObsRow+    { unMatObsRow :: S.SpMatrix Double+    } deriving (Show)++-- Advanced+data SingleCells = SingleCells { _matrix :: MatObsRow+                               , _rowNames :: Vector Cell+                               , _colNames :: Vector Gene+                               }+                     deriving (Show)+L.makeLenses ''SingleCells++data CellInfo = CellInfo+    { _barcode :: Cell+    , _cellRow :: Row+    } deriving (Eq,Ord,Read,Show,Generic,A.ToJSON,A.FromJSON)+L.makeLenses ''CellInfo++data NormType = TfIdfNorm | UQNorm | MedNorm | TotalMedNorm | BothNorm | NoneNorm deriving (Read, Show)++instance (Generic a) => Generic (Vector a)++instance Semigroup MatObsRow where+    (<>) (MatObsRow x) (MatObsRow y) = MatObsRow $ S.vertStackSM x y++instance Monoid MatObsRow where+    mempty  = MatObsRow $ S.zeroSM 0 0++instance Semigroup SingleCells where+    (<>) x y =+        SingleCells { _matrix      = mappend (_matrix x) (_matrix y)+                    , _rowNames    = (V.++) (_rowNames x) (_rowNames y)+                    , _colNames    = _colNames x+                    }++instance Monoid SingleCells where+    mempty  = SingleCells { _matrix = mempty+                          , _rowNames = V.empty+                          , _colNames = V.empty+                          }
+ src/TooManyCells/Matrix/Utility.hs view
@@ -0,0 +1,169 @@+{- TooManyCells.Matrix.Utility+Gregory W. Schwartz++Collects helper functions in the program.+-}++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE QuasiQuotes #-}++module TooManyCells.Matrix.Utility+    ( matToRMat+    , scToRMat+    , sparseToHMat+    , hToSparseMat+    , matToHMat+    , matToSpMat+    , spMatToMat+    , loadMatrixMarket+    , extractSc+    , writeMatrixLike+    ) where++-- Remote+import BirchBeer.Types+import Control.Monad.State (MonadState (..), State (..), evalState, execState, modify)+import Data.Function (on)+import Data.List (maximumBy)+import Data.Maybe (fromMaybe)+import Data.Matrix.MatrixMarket (Matrix(RMatrix, IntMatrix), Structure (..), writeMatrix)+import Data.Scientific (toRealFloat, Scientific)+import Language.R as R+import Language.R.QQ (r)+import System.FilePath ((</>))+import qualified Control.Lens as L+import qualified Data.Clustering.Hierarchical as HC+import qualified Data.Graph.Inductive as G+import qualified Data.Map.Strict as Map+import qualified Data.Sequence as Seq+import qualified Data.Sparse.Common as S+import qualified Data.Text as T+import qualified Data.Text.IO as T+import qualified Data.Text.Lazy as TL+import qualified Data.Text.Lazy.IO as TL+import qualified Data.Text.Lazy.Read as TL+import qualified Data.Vector as V+import qualified Numeric.LinearAlgebra as H+import qualified System.Directory as FP++-- Local+import TooManyCells.File.Types+import TooManyCells.MakeTree.Types+import TooManyCells.Matrix.Types++-- | Convert a mat to an RMatrix.+matToRMat :: MatObsRow -> R s (RMatObsRow s)+matToRMat (MatObsRow m) = do+    [r| library(jsonlite) |]++    let mString = show . H.toLists . sparseToHMat $ m++    -- We want rows as observations and columns as features.+    mat <- [r| as.matrix(fromJSON(mString_hs)) |]+    return . RMatObsRow $ mat++-- | Convert a sc structure to an RMatrix.+scToRMat :: SingleCells -> R s (RMatObsRow s)+scToRMat sc = do+    [r| library(Matrix) |]++    let rowNamesR = fmap (T.unpack . unCell) . V.toList . _rowNames $ sc+        colNamesR = fmap (T.unpack . unGene) . V.toList . _colNames $ sc++    mat <- fmap unRMatObsRow . matToRMat . _matrix $ sc++    -- namedMat <- [r| rownames(mat_hs) = rowNamesR_hs+    --                 colnames(mat_hs) = colNamesR_hs+    --             |]++    return . RMatObsRow $ mat++-- | Convert a sparse matrix to an hmatrix.+sparseToHMat :: S.SpMatrix Double -> H.Matrix H.R+sparseToHMat mat = H.assoc (S.dimSM mat) 0+                 . fmap (\(!x, !y, !z) -> ((x, y), z))+                 . S.toDenseListSM+                 $ mat++-- | Convert a sparse matrix to an hmatrix.+hToSparseMat :: H.Matrix H.R -> S.SpMatrix Double+hToSparseMat =+    S.transposeSM . S.sparsifySM . S.fromColsL . fmap S.vr . H.toLists++-- | Convert a Matrix to an hmatrix Matrix. Assumes matrix market is 1 indexed.+matToHMat :: Matrix Scientific -> H.Matrix H.R+matToHMat (RMatrix size _ _ xs) =+    H.assoc size 0+        . fmap (\(!x, !y, !z) -> ((fromIntegral x - 1, fromIntegral y - 1), toRealFloat z))+        $ xs+matToHMat (IntMatrix size _ _ xs) =+    H.assoc size 0+        . fmap (\(!x, !y, !z) -> ((fromIntegral x - 1, fromIntegral y - 1), fromIntegral z))+        $ xs+matToHMat _ = error "\nInput matrix is not a Real matrix."++-- | Convert a Matrix to a sparse matrix.+matToSpMat :: Matrix Scientific -> S.SpMatrix Double+matToSpMat (RMatrix size _ _ xs) =+    S.fromListSM size+        . fmap (\(!x, !y, !z) -> (fromIntegral x - 1, fromIntegral y - 1, toRealFloat z))+        $ xs+matToSpMat (IntMatrix size _ _ xs) =+    S.fromListSM size+        . fmap (\(!x, !y, !z) -> (fromIntegral x - 1, fromIntegral y - 1, fromIntegral z))+        $ xs+matToSpMat _ = error "\nInput matrix is not a Real matrix."++-- | Convert a sparse matrix to a Matrix.+spMatToMat :: S.SpMatrix Double -> Matrix Double+spMatToMat mat = RMatrix (S.dimSM mat) (S.nzSM mat) General+               . fmap (\(!x, !y, !z) -> (x + 1, y + 1, z)) . S.toListSM+               $ mat++-- | Load a matrix market format.+loadMatrixMarket :: MatrixFile -> IO (S.SpMatrix Double)+loadMatrixMarket (MatrixFile file) = do+    let toDouble [r, c, v] =+            ( either error fst . TL.decimal $ r+            , either error fst . TL.decimal $ c+            , either error fst . TL.double $ v+            )+        toDouble _ = error "Matrix market contains non-standard coordinate."++    (rows, cols, _):cs <- fmap+                            ( fmap (toDouble . TL.words)+                            . dropWhile ((== '%') . TL.head)+                            . TL.lines+                            )+                        . TL.readFile+                        $ file++    return+        . S.fromListSM (rows, cols)+        . fmap (\(!r, !c, !v) -> (r - 1, c - 1, v))+        $ cs++-- | Determine presence of matrix.+extractSc :: Maybe SingleCells -> SingleCells+extractSc = fromMaybe (error "Need to provide matrix in --matrix-path for this functionality.")++-- | Write a matrix to a file.+writeMatrixLike :: MatrixLike (a) => MatrixFile -> a -> IO ()+writeMatrixLike (MatrixFile folder) mat = do+  -- Where to place output files.+  FP.createDirectoryIfMissing True folder++  writeMatrix (folder </> "matrix.mtx") . spMatToMat . getMatrix $ mat+  T.writeFile (folder </> "genes.tsv")+    . T.unlines+    .  V.toList+    . getColNames+    $ mat+  T.writeFile (folder </> "barcodes.tsv")+    . T.unlines+    . V.toList+    . getRowNames+    $ mat++  return ()
+ src/TooManyCells/Paths/Distance.hs view
@@ -0,0 +1,133 @@+{- TooManyCells.Paths.Distance+Gregory W. Schwartz++Collects functions pertaining to calculating distances within the tree (a type+of "pseudotime").+-}++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE OverloadedStrings #-}++module TooManyCells.Paths.Distance+    ( linearNodeDistance+    , linearItemDistance+    , labelItemDistance+    ) where++-- Remote+import BirchBeer.Types+import BirchBeer.Utility (getGraphLeavesCycles)+import Control.Monad (join)+import Data.Function (on)+import Data.List (sortBy, genericLength)+import Data.Maybe (fromMaybe)+import Data.Tuple (swap)+import Safe (headMay, atMay)+import qualified Control.Foldl as Fold+import qualified Control.Lens as L+import qualified Data.Foldable as F+import qualified Data.Graph.Inductive as G+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import qualified Data.Sparse.Common as S+import qualified Data.Text as T++-- Local+import TooManyCells.MakeTree.Types+import TooManyCells.Paths.Types++-- | Convert path back to root.+pathBackToRoot :: (G.DynGraph gr) => G.Node -> gr a Double -> gr a Double+pathBackToRoot n gr = flip flipPath gr $ G.esp 0 n gr++-- | Flip the path of a graph.+flipPath :: (G.DynGraph gr) => [G.Node] -> gr a b -> gr a b+flipPath [] !gr         = gr+flipPath [n1] !gr       = gr+flipPath (n1:n2:ns) !gr = flipPath ns $ flipEdge n1 n2 gr++-- | Flip an edge in a graph, keeping the label.+flipEdge :: (G.DynGraph gr) => G.Node -> G.Node -> gr a b -> gr a b+flipEdge n1 n2 gr = G.insEdge (n2, n1, label) . G.delEdge (n1, n2) $ gr+  where+    label = maybe (error "No node found on path.") snd+          . F.find ((== n2) . fst)+          $ G.lsuc gr n1++-- | Flip edges.+flipEdges :: G.Node -> G.Context a Double -> G.Context a Double+flipEdges n1 (a1, 0, l, a2) = ((0, n1) : a2, 0, l, removeN a1)+  where+    removeN = filter (\(_, x) -> x /= n1)+flipEdges _ (a1, n, l, a2)  = (a2, n, l, a1)++-- | Get the start of the diameter a subtree. Can specify which node.+treeDiameterStart+    :: G.Graph gr+    => PathDistance -> G.Node -> gr (G.Node, b) Double -> G.Node+treeDiameterStart pd n gr =+    fst+        . fromMaybe (error "Empty tree when finding diameter.")+        . headMay+        . reverse+        . sortBy (compare `on` snd)+        . fmap (getDistance pd gr n . fst)+        . F.toList+        . getGraphLeavesCycles [] gr+        $ n++-- | Get the distance of each item from a starting point. Make graph undirected.+linearItemDistance+    :: (TreeItem a, Show a)+    => FlipFlag -> PathDistance -> ClusterGraph a -> [(a, Double)]+linearItemDistance direction pd (ClusterGraph gr) =+    concatMap (uncurry assignItems)+        . linearNodeDistance direction pd+        . G.undir+        $ gr+  where+    assignItems n v =+        fmap (, v)+            . fromMaybe []+            . fmap (maybe [] F.toList . snd)+            . G.lab gr+            $ n++-- | Flip the distances to reverse direction.+flipDistance :: (Fractional b, Ord b) => [(a, b)] -> [(a, b)]+flipDistance = Fold.fold subtractMaxAll+  where+    subtractMaxAll = (\m -> fmap (subtractMax m))+                 <$> Fold.premap snd Fold.maximum+                 <*> Fold.list+    subtractMax m = L.over L._2 (\x -> abs $ x - fromMaybe 0 m)++-- | Get the distance of each leaf from a starting point.+linearNodeDistance+    :: (G.Graph gr, Show a)+    => FlipFlag -> PathDistance -> gr (G.Node, a) Double -> [(G.Node, Double)]+linearNodeDistance (FlipFlag direction) pd gr =+    flipDirection direction+        . fmap (getDistance pd gr start . fst)+        . F.toList+        . getGraphLeavesCycles [] gr+        $ 0+  where+    flipDirection True  = id+    flipDirection False = flipDistance+    start               = treeDiameterStart pd 0 gr++-- | Get the distance of a base node n1 to another node n2.+getDistance+    :: (G.Graph gr)+    => PathDistance -> gr a Double -> G.Node -> G.Node -> (G.Node, Double)+getDistance PathStep gr n1 n2 = (n2, genericLength $ G.esp n1 n2 gr)+getDistance PathModularity gr n1 n2 = (n2, fromMaybe 0 $ G.spLength n1 n2 gr)++-- | Label path distances.+labelItemDistance+    :: TreeItem a+    => LabelMap -> [(a, Double)] -> [(Label, Double)]+labelItemDistance (LabelMap lm) =+    fmap (L.over L._1 (flip (Map.findWithDefault (Label "NA") . getId) lm))
+ src/TooManyCells/Paths/Plot.hs view
@@ -0,0 +1,51 @@+{- TooManyCells.Paths.Plot+Gregory W. Schwartz++Collects the functions pertaining to plotting the path distances.+-}++{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE NoMonomorphismRestriction #-}+{-# LANGUAGE GADTs #-}++module TooManyCells.Paths.Plot+    ( plotPathDistanceR+    ) where++-- Remote+import BirchBeer.Types+import Language.R as R+import Language.R.QQ (r)+import qualified Data.Graph.Inductive as G+import qualified Data.Text as T++-- Local+import TooManyCells.Paths.Types++-- | Plot clusters.+plotPathDistanceR :: String -> Bandwidth -> [(Label, Double)] -> R s ()+plotPathDistanceR outputPlot (Bandwidth b) distances = do+    let xs = fmap snd distances+        ls = fmap (T.unpack . unLabel . fst) distances++    [r| suppressMessages(library(ggplot2))+        suppressMessages(library(cowplot))+        suppressMessages(library(RColorBrewer))+        df = data.frame(x = xs_hs, l = ls_hs)++        p = ggplot(df, aes(x = x, color = l, fill = l)) ++                geom_density(adjust = b_hs, alpha = 0.1) ++                xlab("Path distance") ++                ylab("Cell density") ++                scale_color_discrete(guide = guide_legend(title = "")) ++                guides(fill = FALSE) ++                theme(aspect.ratio = 1)++        suppressMessages(ggsave(p, file = outputPlot_hs))+    |]++    return ()
+ src/TooManyCells/Paths/Types.hs view
@@ -0,0 +1,21 @@+{- TooManyCells.Paths.Types+Gregory W. Schwartz++Collects the path types used in the program.+-}++{-# LANGUAGE StrictData #-}++module TooManyCells.Paths.Types where++-- Remote++-- Local+++-- Basic+newtype FlipFlag  = FlipFlag { unFlipFlag :: Bool }+newtype Bandwidth = Bandwidth { unBandwidth :: Double }++-- Advanced+data PathDistance = PathStep | PathModularity deriving (Read, Show)
+ too-many-cells.cabal view
@@ -0,0 +1,129 @@+name:                too-many-cells+version:             0.1.0.0+synopsis:            Cluster single cells and analyze cell clade relationships.+description:         Different methods to cluster and analyze single cell data with diversity indices and differential expression.+homepage:            http://github.com/GregorySchwartz/too-many-cells#readme+license:             GPL-3+license-file:        LICENSE+author:              Gregory W. Schwartz+maintainer:          gsch@pennmedicine.upenn.edu+copyright:           2018 Gregory W. Schwartz+category:            Bioinformatics+build-type:          Simple+-- extra-source-files:+cabal-version:       >=1.10++library+  hs-source-dirs:      src+  exposed-modules:     TooManyCells.Diversity.Diversity+                     , TooManyCells.Differential.Differential+                     , TooManyCells.Differential.Types+                     , TooManyCells.Diversity.Load+                     , TooManyCells.Diversity.Plot+                     , TooManyCells.Diversity.Types+                     , TooManyCells.File.Types+                     , TooManyCells.MakeTree.Adjacency+                     , TooManyCells.MakeTree.Clumpiness+                     , TooManyCells.MakeTree.Cluster+                     , TooManyCells.MakeTree.Load+                     , TooManyCells.MakeTree.Plot+                     , TooManyCells.MakeTree.Print+                     , TooManyCells.MakeTree.Types+                     , TooManyCells.Matrix.Load+                     , TooManyCells.Matrix.Preprocess+                     , TooManyCells.Matrix.Types+                     , TooManyCells.Matrix.Utility+                     , TooManyCells.Paths.Distance+                     , TooManyCells.Paths.Plot+                     , TooManyCells.Paths.Types+  build-depends:       base >= 4.7 && < 5+                     , aeson+                     , birch-beer+                     , bytestring+                     , cassava+                     , colour+                     , containers+                     , deepseq+                     , diagrams+                     , diagrams-lib+                     , diagrams-cairo+                     , diagrams-graphviz+                     , differential+                     , directory+                     , diversity+                     , find-clumpiness+                     , filepath+                     , fgl+                     , foldl+                     , graphviz+                     , hierarchical-clustering+                     , hierarchical-spectral-clustering+                     , hmatrix+                     , inline-r+                     , lens+                     , managed+                     , matrix-market-attoparsec+                     , mltool+                     , modularity+                     , mtl+                     , palette+                     , parallel+                     , plots+                     , safe+                     , scientific+                     , sparse-linear-algebra+                     , split+                     , statistics+                     , streaming+                     , streaming-bytestring+                     , streaming-cassava+                     , streaming-with+                     , SVGFonts+                     , text+                     , text-show+                     , vector+                     , vector-algorithms+  ghc-options:         -O2+  default-language:    Haskell2010++executable too-many-cells+  hs-source-dirs:      app+  main-is:             Main.hs+  ghc-options:         -threaded -rtsopts -O2+  build-depends:       base+                     , too-many-cells+                     , aeson+                     , birch-beer+                     , bytestring+                     , cassava+                     , colour+                     , containers+                     , diagrams-lib+                     , diagrams-cairo+                     , directory+                     , fgl+                     , filepath+                     , find-clumpiness+                     , graphviz+                     , hierarchical-spectral-clustering+                     , inline-r+                     , lens+                     , matrix-market-attoparsec+                     , mtl+                     , optparse-generic+                     , palette+                     , plots+                     , spectral-clustering+                     , streaming+                     , streaming-bytestring+                     , streaming-utils+                     , terminal-progress-bar+                     , text+                     , text-show+                     , transformers+                     , vector+  default-language:    Haskell2010++source-repository head+  type:     git+  location: https://github.com/GregorySchwartz/too-many-cells