linearmap-category (empty) → 0.1.0.0
raw patch · 9 files changed
+3053/−0 lines, 9 filesdep +basedep +constrained-categoriesdep +containerssetup-changed
Dependencies added: base, constrained-categories, containers, free-vector-spaces, ieee754, lens, linear, semigroups, vector, vector-space
Files
- LICENSE +674/−0
- Math/LinearMap/Asserted.hs +147/−0
- Math/LinearMap/Category.hs +590/−0
- Math/LinearMap/Category/Class.hs +660/−0
- Math/LinearMap/Category/Instances.hs +228/−0
- Math/VectorSpace/Docile.hs +637/−0
- Math/VectorSpace/ZeroDimensional.hs +58/−0
- Setup.hs +2/−0
- linearmap-category.cabal +57/−0
+ 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:++ <program> Copyright (C) <year> <name of author>+ 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>.
+ Math/LinearMap/Asserted.hs view
@@ -0,0 +1,147 @@+-- |+-- Module : Math.LinearMap.Asserted+-- Copyright : (c) Justus Sagemüller 2016+-- License : GPL v3+-- +-- Maintainer : (@) sagemueller $ geo.uni-koeln.de+-- Stability : experimental+-- Portability : portable+-- +{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE UnicodeSyntax #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE StandaloneDeriving #-}++module Math.LinearMap.Asserted where++import Data.VectorSpace+import Data.Basis++import Prelude ()+import qualified Prelude as Hask++import Control.Category.Constrained.Prelude+import Control.Arrow.Constrained+import Data.Traversable.Constrained++import Data.Coerce+import Data.Type.Coercion++import Data.VectorSpace.Free+import qualified Linear.Matrix as Mat+import qualified Linear.Vector as Mat+import Math.VectorSpace.ZeroDimensional+++++-- | A linear map, represented simply as a Haskell function tagged with+-- the type of scalar with respect to which it is linear. Many (sparse)+-- linear mappings can actually be calculated much more efficiently+-- if you don't represent them with any kind of matrix, but+-- just as a function (which is after all, mathematically speaking,+-- what a linear map foremostly is).+-- +-- However, if you sum up many 'LinearFunction's – which you can+-- simply do with the 'VectorSpace' instance – they will become ever+-- slower to calculate, because the summand-functions are actually computed+-- individually and only the results summed. That's where+-- 'Math.LinearMap.Category.LinearMap' is generally preferrable.+-- You can always convert between these equivalent categories using 'arr'.+newtype LinearFunction s v w = LinearFunction { getLinearFunction :: v -> w }+++++linearFunction :: VectorSpace w => (v->w) -> LinearFunction (Scalar v) v w+linearFunction = LinearFunction++scaleWith :: (VectorSpace v, Scalar v ~ s) => s -> LinearFunction s v v+scaleWith μ = LinearFunction (μ*^)++scaleV :: (VectorSpace v, Scalar v ~ s) => v -> LinearFunction s s v+scaleV v = LinearFunction (*^v)++const0 :: AdditiveGroup w => LinearFunction s v w+const0 = LinearFunction (const zeroV)++lNegateV :: AdditiveGroup w => LinearFunction s w w+lNegateV = LinearFunction negateV++addV :: AdditiveGroup w => LinearFunction s (w,w) w+addV = LinearFunction $ uncurry (^+^)++instance AdditiveGroup w => AdditiveGroup (LinearFunction s v w) where+ zeroV = const0+ LinearFunction f ^+^ LinearFunction g = LinearFunction $ \x -> f x ^+^ g x+ LinearFunction f ^-^ LinearFunction g = LinearFunction $ \x -> f x ^-^ g x+ negateV (LinearFunction f) = LinearFunction $ negateV . f+instance VectorSpace w => VectorSpace (LinearFunction s v w) where+ type Scalar (LinearFunction s v w) = Scalar w+ μ *^ LinearFunction f = LinearFunction $ (μ*^) . f++instance Functor (LinearFunction s v) Coercion Coercion where+ fmap Coercion = Coercion++fmapScale :: ( VectorSpace w, Scalar w ~ s, VectorSpace s, Scalar s ~ s+ , Functor f (LinearFunction s) (LinearFunction s)+ , Object (LinearFunction s) s+ , Object (LinearFunction s) w+ , Object (LinearFunction s) (f s)+ , Object (LinearFunction s) (f w)+ , EnhancedCat (->) (LinearFunction s)+ , VectorSpace (f w), Scalar (f w) ~ s+ , VectorSpace (f s), Scalar (f s) ~ s )+ => f s -> LinearFunction s w (f w)+fmapScale v = LinearFunction $ \w -> fmap (scaleV w) $ v++lCoFst :: (AdditiveGroup w) => LinearFunction s v (v,w)+lCoFst = LinearFunction (,zeroV)+lCoSnd :: (AdditiveGroup v) => LinearFunction s w (v,w)+lCoSnd = LinearFunction (zeroV,)++++-- | Infix synonym of 'LinearFunction', without explicit mention of the scalar type.+type v-+>w = LinearFunction (Scalar w) v w++-- | A bilinear function is a linear function mapping to a linear function,+-- or equivalently a 2-argument function that's linear in each argument+-- independently.+-- Note that this can /not/ be uncurried to a linear function with a tuple+-- argument (this would not be linear but quadratic).+type Bilinear v w y = LinearFunction (Scalar v) v (LinearFunction (Scalar v) w y)++bilinearFunction :: (v -> w -> y) -> Bilinear v w y+bilinearFunction f = LinearFunction $ LinearFunction . f++flipBilin :: Bilinear v w y -> Bilinear w v y+flipBilin (LinearFunction f) = LinearFunction+ $ \w -> LinearFunction $ f >>> \(LinearFunction g) -> g w++scale :: VectorSpace v => Bilinear (Scalar v) v v+scale = LinearFunction $ \μ -> LinearFunction (μ*^)++-- | @elacs ≡ 'flipBilin' 'scale'@.+elacs :: VectorSpace v => Bilinear v (Scalar v) v+elacs = LinearFunction $ \v -> LinearFunction (*^v)++inner :: InnerSpace v => Bilinear v v (Scalar v)+inner = LinearFunction $ \v -> LinearFunction (v<.>)++biConst0 :: AdditiveGroup v => Bilinear a b v+biConst0 = LinearFunction $ const const0++lApply :: Bilinear (v-+>w) v w+lApply = bilinearFunction $ \(LinearFunction f) v -> f v
+ Math/LinearMap/Category.hs view
@@ -0,0 +1,590 @@+-- |+-- Module : Math.LinearMap.Category+-- Copyright : (c) Justus Sagemüller 2016+-- License : GPL v3+-- +-- Maintainer : (@) sagemueller $ geo.uni-koeln.de+-- Stability : experimental+-- Portability : portable+-- +++{-# LANGUAGE CPP #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE UnicodeSyntax #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE ConstraintKinds #-}++module Math.LinearMap.Category (+ -- * Linear maps+ -- $linmapIntro++ -- ** Function implementation+ LinearFunction (..), (-+>)(), Bilinear+ -- ** Tensor implementation+ , LinearMap (..), (+>)()+ , (⊕), (>+<)+ , adjoint+ -- ** Dual vectors+ -- $dualVectorIntro+ , (<.>^)+ -- * Tensor spaces+ , Tensor (..), (⊗)(), (⊗)+ -- * Norms+ -- $metricIntro+ , Norm(..), Seminorm+ , spanNorm+ , euclideanNorm+ , (|$|)+ , normSq+ , (<$|)+ , scaleNorm+ , normSpanningSystem+ , normSpanningSystem'+ -- ** Variances+ , Variance, spanVariance, dualNorm+ , dependence+ -- ** Utility+ , densifyNorm+ -- * Solving linear equations+ , (\$), pseudoInverse, roughDet+ -- * Eigenvalue problems+ , eigen+ , constructEigenSystem+ , roughEigenSystem+ , finishEigenSystem+ , Eigenvector(..)+ -- * The classes of suitable vector spaces+ , LSpace+ , TensorSpace (..)+ , LinearSpace (..)+ -- ** Orthonormal systems+ , SemiInner (..), cartesianDualBasisCandidates+ -- ** Finite baseis+ , FiniteDimensional (..)+ -- * Utility+ -- ** Linear primitives+ , addV, scale, inner, flipBilin, bilinearFunction+ -- ** Hilbert space operations+ , DualSpace, riesz, coRiesz, showsPrecAsRiesz, (.<)+ -- ** Constraint synonyms+ , HilbertSpace, SimpleSpace+ , Num', Num'', Num'''+ , Fractional', Fractional''+ , RealFrac', RealFloat'+ -- ** Misc+ , relaxNorm, transformNorm, transformVariance+ , findNormalLength, normalLength+ , summandSpaceNorms, sumSubspaceNorms, sharedNormSpanningSystem+ ) where++import Math.LinearMap.Category.Class+import Math.LinearMap.Category.Instances+import Math.LinearMap.Asserted+import Math.VectorSpace.Docile++import Data.Tree (Tree(..), Forest)+import Data.List (sortBy, foldl')+import qualified Data.Set as Set+import Data.Set (Set)+import Data.Ord (comparing)+import Data.List (maximumBy)+import Data.Foldable (toList)+import Data.Semigroup++import Data.VectorSpace+import Data.Basis++import Prelude ()+import qualified Prelude as Hask++import Control.Category.Constrained.Prelude hiding ((^))+import Control.Arrow.Constrained++import Linear ( V0(V0), V1(V1), V2(V2), V3(V3), V4(V4)+ , _x, _y, _z, _w )+import Data.VectorSpace.Free+import Math.VectorSpace.ZeroDimensional+import qualified Linear.Matrix as Mat+import qualified Linear.Vector as Mat+import Control.Lens ((^.))++import Numeric.IEEE++-- $linmapIntro+-- This library deals with linear functions, i.e. functions @f :: v -> w@+-- that fulfill+-- +-- @+-- f $ μ 'Data.VectorSpace.^*' u 'Data.AdditiveGroup.^+^' v ≡ μ ^* f u ^+^ f v ∀ u,v :: v; μ :: 'Scalar' v+-- @+-- +-- Such functions form a cartesian monoidal category (in maths called +-- <https://en.wikipedia.org/wiki/Category_of_modules#Example:_the_category_of_vector_spaces VectK>).+-- This is implemented by 'Control.Arrow.Constrained.PreArrow', which is the+-- preferred interface for dealing with these mappings. The basic+-- “matrix operations” are then:+-- +-- * Identity matrix: 'Control.Category.Constrained.id'+-- * Matrix addition: 'Data.AdditiveGroup.^+^' (linear maps form an ordinary vector space)+-- * Matrix-matrix multiplication: 'Control.Category.Constrained.<<<'+-- (or '>>>' or 'Control.Category.Constrained..')+-- * Matrix-vector multiplication: 'Control.Arrow.Constrained.$'+-- * Vertical matrix concatenation: 'Control.Arrow.Constrained.&&&'+-- * Horizontal matrix concatenation: '⊕' (aka '>+<')+-- +-- But linear mappings need not necessarily be implemented as matrices:+++-- $dualVectorIntro+-- A @'DualVector' v@ is a linear functional or+-- <https://en.wikipedia.org/wiki/Linear_form linear form> on the vector space @v@,+-- i.e. it is a linear function from the vector space into its scalar field.+-- However, these functions form themselves a vector space, known as the dual space.+-- In particular, the dual space of any 'InnerSpace' is isomorphic to the+-- space itself.+-- +-- (More precisely: the continuous dual space of a+-- <https://en.wikipedia.org/wiki/Hilbert_space Hilbert space> is isomorphic to+-- that Hilbert space itself; see the 'riesz' isomorphism.)+-- +-- As a matter of fact, in many applications, no distinction is made between a+-- space and its dual. Indeed, we have for the basic 'LinearSpace' instances+-- @'DualVector' v ~ v@, and '<.>^' is simply defined as a scalar product.+-- In this case, a general 'LinearMap' is just a tensor product / matrix.+-- +-- However, scalar products are often not as natural as they are made to look:+-- +-- * A scalar product is only preserved under orthogonal transformations.+-- It is not preserved under scalings, and certainly not under general linear+-- transformations. This is very important in applications such as relativity+-- theory (here, people talk about /covariant/ vs /contravariant/ tensors),+-- but also relevant for more mundane+-- <http://hackage.haskell.org/package/manifolds manifolds> like /sphere surfaces/:+-- on such a surface, the natural symmetry transformations do generally+-- not preserve a scalar product you might define.+-- +-- * There may be more than one meaningful scalar product. For instance,+-- the <https://en.wikipedia.org/wiki/Sobolev_space Sobolev space> of weakly+-- differentiable functions also permits the+-- <https://en.wikipedia.org/wiki/Square-integrable_function 𝐿²> scalar product+-- – each has different and useful properties.+-- +-- Neither of this is a problem if we keep the dual space a separate type.+-- Effectively, this enables the type system to prevent you from writing code that+-- does not behave natural (i.e. that depends on a concrete choice of basis / scalar+-- product).+-- +-- For cases when you do have some given notion of orientation/scale in a vector space+-- and need it for an algorithm, you can always provide a 'Norm', which is essentially+-- a reified scalar product.+-- +-- Note that @DualVector (DualVector v) ~ v@ in any 'LSpace': the /double-dual/+-- space is /naturally/ isomorphic to the original space, by way of+-- +-- @+-- v '<.>^' dv ≡ dv '<.>^' v+-- @++++++-- | For real matrices, this boils down to 'transpose'.+-- For free complex spaces it also incurs complex conjugation.+-- +-- The signature can also be understood as+--+-- @+-- adjoint :: (v +> w) -> (DualVector w +> DualVector v)+-- @+-- +-- Or+--+-- @+-- adjoint :: (DualVector v +> DualVector w) -> (w +> v)+-- @+-- +-- But /not/ @(v+>w) -> (w+>v)@, in general (though in a Hilbert space, this too is+-- equivalent, via 'riesz' isomorphism).+adjoint :: (LSpace v, LSpace w, Scalar v ~ Scalar w)+ => (v +> DualVector w) -+> (w +> DualVector v)+adjoint = arr fromTensor . transposeTensor . arr asTensor+++++-- $metricIntro+-- A norm is a way to quantify the magnitude/length of different vectors,+-- even if they point in different directions.+-- +-- In an 'InnerSpace', a norm is always given by the scalar product,+-- but there are spaces without a canonical scalar product (or situations+-- in which this scalar product does not give the metric you want). Hence,+-- we let the functions like 'constructEigenSystem', which depend on a norm+-- for orthonormalisation, accept a 'Norm' as an extra argument instead of+-- requiring 'InnerSpace'.++-- | A seminorm defined by+-- +-- @+-- ‖v‖ = √(∑ᵢ ⟨dᵢ|v⟩²)+-- @+-- +-- for some dual vectors @dᵢ@. If given a complete basis of the dual space,+-- this generates a proper 'Norm'.+-- +-- If the @dᵢ@ are a complete orthonormal system, you get the 'euclideanNorm'+-- (in an inefficient form).+spanNorm :: LSpace v => [DualVector v] -> Seminorm v+spanNorm dvs = Norm . LinearFunction $ \v -> sumV [dv ^* (dv<.>^v) | dv <- dvs]++spanVariance :: LSpace v => [v] -> Variance v+spanVariance = spanNorm++-- | Modify a norm in such a way that the given vectors lie within its unit ball.+-- (Not /optimally/ – the unit ball may be bigger than necessary.)+relaxNorm :: SimpleSpace v => Norm v -> [v] -> Norm v+relaxNorm me = \vs -> dualNorm . spanVariance $ vs' ++ vs+ where vs' = normSpanningSystem' me++-- | Scale the result of a norm with the absolute of the given number.+-- +-- @+-- scaleNorm μ n |$| v = abs μ * (n|$|v)+-- @+-- +-- Equivalently, this scales the norm's unit ball by the reciprocal of that factor.+scaleNorm :: LSpace v => Scalar v -> Norm v -> Norm v+scaleNorm μ (Norm n) = Norm $ μ^2 *^ n++-- | A positive (semi)definite symmetric bilinear form. This gives rise+-- to a <https://en.wikipedia.org/wiki/Norm_(mathematics) norm> thus:+-- +-- @+-- 'Norm' n '|$|' v = √(n v '<.>^' v)+-- @+-- +-- Strictly speaking, this type is neither strong enough nor general enough to+-- deserve the name 'Norm': it includes proper 'Seminorm's (i.e. @m|$|v ≡ 0@ does+-- not guarantee @v == zeroV@), but not actual norms such as the ℓ₁-norm on ℝⁿ+-- (Taxcab norm) or the supremum norm.+-- However, 𝐿₂-like norms are the only ones that can really be formulated without+-- any basis reference; and guaranteeing positive definiteness through the type+-- system is scarcely practical.+newtype Norm v = Norm {+ applyNorm :: v -+> DualVector v+ }++-- | A “norm” that may explicitly be degenerate, with @m|$|v ⩵ 0@ for some @v ≠ zeroV@.+type Seminorm v = Norm v++-- | @(m<>n|$|v)^2 ⩵ (m|$|v)^2 + (n|$|v)^2@+instance LSpace v => Semigroup (Norm v) where+ Norm m <> Norm n = Norm $ m^+^n+-- | @mempty|$|v ≡ 0@+instance LSpace v => Monoid (Seminorm v) where+ mempty = Norm zeroV+ mappend = (<>)++-- | A multidimensional variance of points @v@ with some distribution can be+-- considered a norm on the dual space, quantifying for a dual vector @dv@ the+-- expectation value of @(dv<.>^v)^2@.+type Variance v = Norm (DualVector v)++-- | The canonical standard norm (2-norm) on inner-product / Hilbert spaces.+euclideanNorm :: HilbertSpace v => Norm v+euclideanNorm = Norm id++-- | The norm induced from the (arbitrary) choice of basis in a finite space.+-- Only use this in contexts where you merely need /some/ norm, but don't+-- care if it might be biased in some unnatural way.+adhocNorm :: FiniteDimensional v => Norm v+adhocNorm = Norm uncanonicallyToDual++-- | A proper norm induces a norm on the dual space – the “reciprocal norm”.+-- (The orthonormal systems of the norm and its dual are mutually conjugate.)+-- The dual norm of a seminorm is undefined.+dualNorm :: SimpleSpace v => Norm v -> Variance v+dualNorm (Norm m) = Norm . arr . pseudoInverse $ arr m++transformNorm :: (LSpace v, LSpace w, Scalar v~Scalar w) => (v+>w) -> Norm w -> Norm v+transformNorm f (Norm m) = Norm . arr $ (adjoint $ f) . (fmap m $ f)++transformVariance :: (LSpace v, LSpace w, Scalar v~Scalar w)+ => (v+>w) -> Variance v -> Variance w+transformVariance f (Norm m) = Norm . arr $ f . (fmap m $ adjoint $ f)++infixl 6 ^%+(^%) :: (LSpace v, Floating (Scalar v)) => v -> Norm v -> v+v ^% Norm m = v ^/ sqrt ((m$v)<.>^v)++-- | The unique positive number whose norm is 1 (if the norm is not constant zero).+findNormalLength :: RealFrac' s => Norm s -> Maybe s+findNormalLength (Norm m) = case m $ 1 of+ o | o > 0 -> Just . sqrt $ recip o+ | otherwise -> Nothing++-- | Unsafe version of 'findNormalLength', only works reliable if the norm+-- is actually positive definite.+normalLength :: RealFrac' s => Norm s -> s+normalLength (Norm m) = case m $ 1 of+ o | o >= 0 -> sqrt $ recip o+ | o < 0 -> error "Norm fails to be positive semidefinite."+ | otherwise -> error "Norm yields NaN."++infixr 0 <$|, |$|+-- | “Partially apply” a norm, yielding a dual vector+-- (i.e. a linear form that accepts the second argument of the scalar product).+-- +-- @+-- ('euclideanNorm' '<$|' v) '<.>^' w ≡ v '<.>' w+-- @+(<$|) :: LSpace v => Norm v -> v -> DualVector v+Norm m <$| v = m $ v++-- | The squared norm. More efficient than '|$|' because that needs to take+-- the square root.+normSq :: LSpace v => Seminorm v -> v -> Scalar v+normSq (Norm m) v = (m$v)<.>^v++-- | Use a 'Norm' to measure the length / norm of a vector.+-- +-- @+-- 'euclideanNorm' |$| v ≡ √(v '<.>' v)+-- @+(|$|) :: (LSpace v, Floating (Scalar v)) => Seminorm v -> v -> Scalar v+(|$|) m = sqrt . normSq m++-- | 'spanNorm' / 'spanVariance' are inefficient if the number of vectors+-- is similar to the dimension of the space, or even larger than it.+-- Use this function to optimise the underlying operator to a dense+-- matrix representation.+densifyNorm :: LSpace v => Norm v -> Norm v+densifyNorm (Norm m) = Norm . arr $ sampleLinearFunction $ m++data OrthonormalSystem v = OrthonormalSystem {+ orthonormalityNorm :: Norm v+ , orthonormalVectors :: [v]+ }++orthonormaliseFussily :: (LSpace v, RealFloat (Scalar v))+ => Scalar v -> Norm v -> [v] -> [v]+orthonormaliseFussily fuss me = go []+ where go _ [] = []+ go ws (v₀:vs)+ | mvd > fuss = let μ = 1/sqrt mvd+ v = vd^*μ+ in v : go ((v,dvd^*μ):ws) vs+ | otherwise = go ws vs+ where vd = orthogonalComplementProj' ws $ v₀+ dvd = applyNorm me $ vd+ mvd = dvd<.>^vd++orthogonalComplementProj' :: LSpace v => [(v, DualVector v)] -> (v-+>v)+orthogonalComplementProj' ws = LinearFunction $ \v₀+ -> foldl' (\v (w,dw) -> v ^-^ w^*(dw<.>^v)) v₀ ws++orthogonalComplementProj :: LSpace v => Norm v -> [v] -> (v-+>v)+orthogonalComplementProj (Norm m)+ = orthogonalComplementProj' . map (id &&& (m$))++++data Eigenvector v = Eigenvector {+ ev_Eigenvalue :: Scalar v -- ^ The estimated eigenvalue @λ@.+ , ev_Eigenvector :: v -- ^ Normalised vector @v@ that gets mapped to a multiple, namely:+ , ev_FunctionApplied :: v -- ^ @f $ v ≡ λ *^ v @.+ , ev_Deviation :: v -- ^ Deviation of these two supposedly equivalent expressions.+ , ev_Badness :: Scalar v -- ^ Squared norm of the deviation, normalised by the eigenvalue.+ }+deriving instance (Show v, Show (Scalar v)) => Show (Eigenvector v)++-- | Lazily compute the eigenbasis of a linear map. The algorithm is essentially+-- a hybrid of Lanczos/Arnoldi style Krylov-spanning and QR-diagonalisation,+-- which we don't do separately but /interleave/ at each step.+-- +-- The size of the eigen-subbasis increases with each step until the space's+-- dimension is reached. (But the algorithm can also be used for+-- infinite-dimensional spaces.)+constructEigenSystem :: (LSpace v, RealFloat (Scalar v))+ => Norm v -- ^ The notion of orthonormality.+ -> Scalar v -- ^ Error bound for deviations from eigen-ness.+ -> (v-+>v) -- ^ Operator to calculate the eigensystem of.+ -- Must be Hermitian WRT the scalar product+ -- defined by the given metric.+ -> [v] -- ^ Starting vector(s) for the power method.+ -> [[Eigenvector v]] -- ^ Infinite sequence of ever more accurate approximations+ -- to the eigensystem of the operator.+constructEigenSystem me@(Norm m) ε₀ f = iterate (+ sortBy (comparing $+ negate . abs . ev_Eigenvalue)+ . map asEV+ . orthonormaliseFussily (1/4) (Norm m)+ . newSys)+ . map (asEV . (^%me))+ where newSys [] = []+ newSys (Eigenvector λ v fv dv ε : evs)+ | ε>ε₀ = case newSys evs of+ [] -> [fv^/λ, dv^*(sqrt $ λ^2/ε)]+ vn:vns -> fv^/λ : vn : dv^*(sqrt $ λ^2/ε) : vns+ | ε>=0 = v : newSys evs+ | otherwise = newSys evs+ asEV v = Eigenvector λ v fv dv ε+ where λ = v'<.>^fv+ ε = normSq me dv / (λ^2 + ε₀)+ fv = f $ v+ dv = v^*λ ^-^ fv+ v' = m $ v+++finishEigenSystem :: (LSpace v, RealFloat (Scalar v))+ => Norm v -> [Eigenvector v] -> [Eigenvector v]+finishEigenSystem me = go . sortBy (comparing $ negate . ev_Eigenvalue)+ where go [] = []+ go [v] = [v]+ go vs@[Eigenvector λ₀ v₀ fv₀ _dv₀ _ε₀, Eigenvector λ₁ v₁ fv₁ _dv₁ _ε₁]+ | λ₀>λ₁ = [ asEV v₀' fv₀', asEV v₁' fv₁' ]+ | otherwise = vs+ where+ v₀' = v₀^*μ₀₀ ^+^ v₁^*μ₀₁+ fv₀' = fv₀^*μ₀₀ ^+^ fv₁^*μ₀₁+ + v₁' = v₀^*μ₁₀ ^+^ v₁^*μ₁₁+ fv₁' = fv₀^*μ₁₀ ^+^ fv₁^*μ₁₁+ + fShift₁v₀ = fv₀ ^-^ λ₁*^v₀+ + (μ₀₀,μ₀₁) = normalized ( λ₀ - λ₁+ , (me <$| fShift₁v₀)<.>^v₁ )+ (μ₁₀,μ₁₁) = (-μ₀₁, μ₀₀)+ + go evs = lo'' ++ upper'+ where l = length evs+ lChunk = l`quot`3+ (loEvs, (midEvs, hiEvs)) = second (splitAt $ l - 2*lChunk)+ $ splitAt lChunk evs+ (lo',hi') = splitAt lChunk . go $ loEvs++hiEvs+ (lo'',mid') = splitAt lChunk . go $ lo'++midEvs+ upper' = go $ mid'++hi'+ + asEV v fv = Eigenvector λ v fv dv ε+ where λ = (me<$|v)<.>^fv+ dv = v^*λ ^-^ fv+ ε = normSq me dv / λ^2+++-- | Find a system of vectors that approximate the eigensytem, in the sense that:+-- each true eigenvalue is represented by an approximate one, and that is closer+-- to the true value than all the other approximate EVs.+-- +-- This function does not make any guarantees as to how well a single eigenvalue+-- is approximated, though.+roughEigenSystem :: (FiniteDimensional v, IEEE (Scalar v))+ => Norm v+ -> (v+>v)+ -> [Eigenvector v]+roughEigenSystem me f = go fBas 0 [[]]+ where go [] _ (_:evs:_) = evs+ go [] _ (evs:_) = evs+ go (v:vs) oldDim (evs:evss)+ | normSq me vPerp > fpε = case evss of+ evs':_ | length evs' > oldDim+ -> go (v:vs) (length evs) evss+ _ -> let evss' = constructEigenSystem me fpε (arr f)+ $ map ev_Eigenvector (head $ evss++[evs]) ++ [vPerp]+ in go vs (length evs) evss'+ | otherwise = go vs oldDim (evs:evss)+ where vPerp = orthogonalComplementProj me (ev_Eigenvector<$>evs) $ v+ fBas = (^%me) <$> snd (decomposeLinMap id) []+ fpε = epsilon * 8++-- | Simple automatic finding of the eigenvalues and -vectors+-- of a Hermitian operator, in reasonable approximation.+-- +-- This works by spanning a QR-stabilised Krylov basis with 'constructEigenSystem'+-- until it is complete ('roughEigenSystem'), and then properly decoupling the+-- system with 'finishEigenSystem' (based on two iterations of shifted Givens rotations).+-- +-- This function is a tradeoff in performance vs. accuracy. Use 'constructEigenSystem'+-- and 'finishEigenSystem' directly for more quickly computing a (perhaps incomplete)+-- approximation, or for more precise results.+eigen :: (FiniteDimensional v, HilbertSpace v, IEEE (Scalar v))+ => (v+>v) -> [(Scalar v, v)]+eigen f = map (ev_Eigenvalue &&& ev_Eigenvector)+ $ iterate (finishEigenSystem euclideanNorm) (roughEigenSystem euclideanNorm f) !! 2+++-- | Approximation of the determinant.+roughDet :: (FiniteDimensional v, IEEE (Scalar v)) => (v+>v) -> Scalar v+roughDet = roughEigenSystem adhocNorm >>> map ev_Eigenvalue >>> product+++orthonormalityError :: LSpace v => Norm v -> [v] -> Scalar v+orthonormalityError me vs = normSq me $ orthogonalComplementProj me vs $ sumV vs+++normSpanningSystem :: SimpleSpace v+ => Norm v -> [DualVector v]+normSpanningSystem = dualBasis . normSpanningSystem'++normSpanningSystem' :: (FiniteDimensional v, IEEE (Scalar v))+ => Norm v -> [v]+normSpanningSystem' me = orthonormaliseFussily 0 me $ enumerateSubBasis entireBasis+++-- | For any two norms, one can find a system of co-vectors that, with suitable+-- coefficients, spans /either/ of them: if @shSys = sharedNormSpanningSystem n₀ n₁@,+-- then+-- +-- @+-- n₀ = 'spanNorm' $ fst<$>shSys+-- @+-- +-- and+-- +-- @+-- n₁ = 'spanNorm' [dv^*η | (dv,η)<-shSys]+-- @+sharedNormSpanningSystem :: SimpleSpace v+ => Norm v -> Norm v -> [(DualVector v, Scalar v)]+sharedNormSpanningSystem (Norm n) (Norm m)+ = sep =<< roughEigenSystem (Norm n) (pseudoInverse (arr n) . arr m)+ where sep (Eigenvector λ _ λv _ _)+ | λ>0 = [(n$v, sqrt λ)]+ | otherwise = []+ where v = λv ^/ λ+++-- | Interpret a variance as a covariance between two subspaces, and+-- normalise it by the variance on @u@. The result is effectively+-- the linear regression coefficient of a simple regression of the vectors+-- spanning the variance.+dependence :: (SimpleSpace u, SimpleSpace v, Scalar u~Scalar v)+ => Variance (u,v) -> (u+>v)+dependence (Norm m) = fmap ( snd . m . (id&&&zeroV) )+ $ pseudoInverse (arr $ fst . m . (id&&&zeroV))+++summandSpaceNorms :: (SimpleSpace u, SimpleSpace v, Scalar u ~ Scalar v)+ => Norm (u,v) -> (Norm u, Norm v)+summandSpaceNorms nuv = ( densifyNorm $ spanNorm (fst<$>spanSys)+ , densifyNorm $ spanNorm (snd<$>spanSys) )+ where spanSys = normSpanningSystem nuv++sumSubspaceNorms :: (LSpace u, LSpace v, Scalar u~Scalar v)+ => Norm u -> Norm v -> Norm (u,v)+sumSubspaceNorms (Norm nu) (Norm nv) = Norm $ nu *** nv++++++instance (SimpleSpace v, Show (DualVector v)) => Show (Norm v) where+ showsPrec p n = showParen (p>9) $ ("spanNorm "++) . shows (normSpanningSystem n)
+ Math/LinearMap/Category/Class.hs view
@@ -0,0 +1,660 @@+-- |+-- Module : Math.LinearMap.Category.Class+-- Copyright : (c) Justus Sagemüller 2016+-- License : GPL v3+-- +-- Maintainer : (@) sagemueller $ geo.uni-koeln.de+-- Stability : experimental+-- Portability : portable+-- +{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE UnicodeSyntax #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE StandaloneDeriving #-}++module Math.LinearMap.Category.Class where++import Data.VectorSpace++import Prelude ()+import qualified Prelude as Hask++import Control.Category.Constrained.Prelude+import Control.Arrow.Constrained++import Data.Coerce+import Data.Type.Coercion++import Math.LinearMap.Asserted+import Math.VectorSpace.ZeroDimensional++type Num' s = (Num s, VectorSpace s, Scalar s ~ s)+type Num'' s = (Num' s, LinearSpace s)+type Num''' s = (Num s, InnerSpace s, Scalar s ~ s, LSpace' s, DualVector s ~ s)+ +class (VectorSpace v) => TensorSpace v where+ -- | The internal representation of a 'Tensor' product.+ -- + -- For euclidean spaces, this is generally constructed by replacing each @s@+ -- scalar field in the @v@ vector with an entire @w@ vector. I.e., you have+ -- then a “nested vector” or, if @v@ is a @DualVector@ / “row vector”, a matrix.+ type TensorProduct v w :: *+ zeroTensor :: (LSpace w, Scalar w ~ Scalar v)+ => v ⊗ w+ toFlatTensor :: v -+> (v ⊗ Scalar v)+ fromFlatTensor :: (v ⊗ Scalar v) -+> v+ addTensors :: (LSpace w, Scalar w ~ Scalar v)+ => (v ⊗ w) -> (v ⊗ w) -> v ⊗ w+ subtractTensors :: (LSpace v, LSpace w, Num''' (Scalar v), Scalar w ~ Scalar v)+ => (v ⊗ w) -> (v ⊗ w) -> v ⊗ w+ subtractTensors m n = addTensors m (negateTensor $ n)+ scaleTensor :: (LSpace w, Scalar w ~ Scalar v)+ => Bilinear (Scalar v) (v ⊗ w) (v ⊗ w)+ negateTensor :: (LSpace w, Scalar w ~ Scalar v)+ => (v ⊗ w) -+> (v ⊗ w)+ tensorProduct :: (LSpace w, Scalar w ~ Scalar v)+ => Bilinear v w (v ⊗ w)+ transposeTensor :: (LSpace w, Scalar w ~ Scalar v)+ => (v ⊗ w) -+> (w ⊗ v)+ fmapTensor :: (LSpace w, LSpace x, Scalar w ~ Scalar v, Scalar x ~ Scalar v)+ => Bilinear (w -+> x) (v⊗w) (v⊗x)+ fzipTensorWith :: ( LSpace u, LSpace w, LSpace x+ , Scalar u ~ Scalar v, Scalar w ~ Scalar v, Scalar x ~ Scalar v )+ => Bilinear ((w,x) -+> u) (v⊗w, v⊗x) (v⊗u)+ coerceFmapTensorProduct :: Hask.Functor p+ => p v -> Coercion a b -> Coercion (TensorProduct v a) (TensorProduct v b)++infixl 7 ⊗++-- | Infix version of 'tensorProduct'.+(⊗) :: (LSpace v, LSpace w, Scalar w ~ Scalar v)+ => v -> w -> v ⊗ w+v⊗w = (tensorProduct $ v) $ w++-- | The class of vector spaces @v@ for which @'LinearMap' s v w@ is well-implemented.+class ( TensorSpace v, TensorSpace (DualVector v)+ , Num' (Scalar v), Scalar (DualVector v) ~ Scalar v )+ => LinearSpace v where+ -- | Suitable representation of a linear map from the space @v@ to its field.+ -- + -- For the usual euclidean spaces, you can just define @'DualVector' v = v@.+ -- (In this case, a dual vector will be just a “row vector” if you consider+ -- @v@-vectors as “column vectors”. 'LinearMap' will then effectively have+ -- a matrix layout.)+ type DualVector v :: *+ + linearId :: v +> v+ + idTensor :: LSpace v => v ⊗ DualVector v+ idTensor = transposeTensor $ asTensor $ linearId+ + sampleLinearFunction :: (LSpace v, LSpace w, Scalar v ~ Scalar w)+ => (v-+>w) -+> (v+>w)+ sampleLinearFunction = LinearFunction $ \f -> fmap f $ id+ + toLinearForm :: LSpace v => DualVector v -+> (v+>Scalar v)+ toLinearForm = toFlatTensor >>> arr fromTensor+ + fromLinearForm :: LSpace v => (v+>Scalar v) -+> DualVector v+ fromLinearForm = arr asTensor >>> fromFlatTensor+ + coerceDoubleDual :: Coercion v (DualVector (DualVector v))+ + blockVectSpan :: (LSpace w, Scalar w ~ Scalar v)+ => w -+> (v⊗(v+>w))+ blockVectSpan' :: (LSpace v, LSpace w, Num''' (Scalar v), Scalar v ~ Scalar w)+ => w -+> (v+>(v⊗w))+ blockVectSpan' = LinearFunction $ \w -> fmap (flipBilin tensorProduct $ w) $ id+ + trace :: LSpace v => (v+>v) -+> Scalar v+ trace = flipBilin contractLinearMapAgainst $ id+ + contractTensorMap :: (LSpace w, Scalar w ~ Scalar v)+ => (v+>(v⊗w)) -+> w+ contractMapTensor :: (LSpace w, Scalar w ~ Scalar v)+ => (v⊗(v+>w)) -+> w+ contractFnTensor :: (LSpace v, LSpace w, Scalar w ~ Scalar v)+ => (v⊗(v-+>w)) -+> w+ contractFnTensor = fmap sampleLinearFunction >>> contractMapTensor+ contractTensorFn :: (LSpace v, LSpace w, Scalar w ~ Scalar v)+ => (v-+>(v⊗w)) -+> w+ contractTensorFn = sampleLinearFunction >>> contractTensorMap+ contractTensorWith :: (LSpace v, LSpace w, Scalar w ~ Scalar v)+ => Bilinear (v⊗w) (DualVector w) v+ contractTensorWith = flipBilin $ LinearFunction+ (\dw -> fromFlatTensor . fmap (flipBilin applyDualVector$dw))+ contractLinearMapAgainst :: (LSpace w, Scalar w ~ Scalar v)+ => Bilinear (v+>w) (w-+>v) (Scalar v)+ + applyDualVector :: LSpace v+ => Bilinear (DualVector v) v (Scalar v)+ + applyLinear :: (LSpace w, Scalar w ~ Scalar v)+ => Bilinear (v+>w) v w+ composeLinear :: ( LSpace w, LSpace x+ , Scalar w ~ Scalar v, Scalar x ~ Scalar v )+ => Bilinear (w+>x) (v+>w) (v+>x)+++instance Num''' s => TensorSpace (ZeroDim s) where+ type TensorProduct (ZeroDim s) v = ZeroDim s+ zeroTensor = Tensor Origin+ toFlatTensor = LinearFunction $ \Origin -> Tensor Origin+ fromFlatTensor = LinearFunction $ \(Tensor Origin) -> Origin+ negateTensor = const0+ scaleTensor = biConst0+ addTensors (Tensor Origin) (Tensor Origin) = Tensor Origin+ subtractTensors (Tensor Origin) (Tensor Origin) = Tensor Origin+ tensorProduct = biConst0+ transposeTensor = const0+ fmapTensor = biConst0+ fzipTensorWith = biConst0+ coerceFmapTensorProduct _ Coercion = Coercion+instance Num''' s => LinearSpace (ZeroDim s) where+ type DualVector (ZeroDim s) = ZeroDim s+ linearId = LinearMap Origin+ idTensor = Tensor Origin+ fromLinearForm = const0+ coerceDoubleDual = Coercion+ contractTensorMap = const0+ contractMapTensor = const0+ contractTensorWith = biConst0+ contractLinearMapAgainst = biConst0+ blockVectSpan = const0+ applyDualVector = biConst0+ applyLinear = biConst0+ composeLinear = biConst0+++-- | The tensor product between one space's dual space and another space is the+-- space spanned by vector–dual-vector pairs, in+-- <https://en.wikipedia.org/wiki/Bra%E2%80%93ket_notationa bra-ket notation>+-- written as+-- +-- @+-- m = ∑ |w⟩⟨v|+-- @+-- +-- Any linear mapping can be written as such a (possibly infinite) sum. The+-- 'TensorProduct' data structure only stores the linear independent parts+-- though; for simple finite-dimensional spaces this means e.g. @'LinearMap' ℝ ℝ³ ℝ³@+-- effectively boils down to an ordinary matrix type, namely an array of+-- column-vectors @|w⟩@.+-- +-- (The @⟨v|@ dual-vectors are then simply assumed to come from the canonical basis.)+-- +-- For bigger spaces, the tensor product may be implemented in a more efficient+-- sparse structure; this can be defined in the 'TensorSpace' instance.+newtype LinearMap s v w = LinearMap {getLinearMap :: TensorProduct (DualVector v) w}++-- | Tensor products are most interesting because they can be used to implement+-- linear mappings, but they also form a useful vector space on their own right.+newtype Tensor s v w = Tensor {getTensorProduct :: TensorProduct v w}++asTensor :: Coercion (LinearMap s v w) (Tensor s (DualVector v) w)+asTensor = Coercion+fromTensor :: Coercion (Tensor s (DualVector v) w) (LinearMap s v w)+fromTensor = Coercion++asLinearMap :: ∀ s v w . (LSpace v, Scalar v ~ s)+ => Coercion (Tensor s v w) (LinearMap s (DualVector v) w)+asLinearMap = Coercion+fromLinearMap :: ∀ s v w . (LSpace v, Scalar v ~ s)+ => Coercion (LinearMap s (DualVector v) w) (Tensor s v w)+fromLinearMap = Coercion++-- | Infix synonym for 'LinearMap', without explicit mention of the scalar type.+type v +> w = LinearMap (Scalar v) v w++-- | Infix synonym for 'Tensor', without explicit mention of the scalar type.+type v ⊗ w = Tensor (Scalar v) v w++type LSpace' v = ( LinearSpace v, LinearSpace (Scalar v)+ , LinearSpace (DualVector v), DualVector (DualVector v) ~ v )++-- | The workhorse of this package: most functions here work on vector+-- spaces that fulfill the @'LSpace' v@ constraint. In summary, this is:+-- +-- * A 'VectorSpace' whose 'Scalar' is a 'Num'''' (i.e. a number type that+-- has itself all the vector-space instances).+-- * You have an implementation for @'TensorProduct' v w@, for any other space @w@.+-- * You have a 'DualVector' space that fulfills @'DualVector' ('DualVector' v) ~ v@.+-- +-- To make a new space of yours an 'LSpace', you must define instances of+-- 'TensorSpace' and 'LinearSpace'.+type LSpace v = (LSpace' v, Num''' (Scalar v))++instance (LSpace v, LSpace w, Scalar v~s, Scalar w~s)+ => AdditiveGroup (LinearMap s v w) where+ zeroV = fromTensor $ zeroTensor+ m^+^n = fromTensor $ (asTensor$m) ^+^ (asTensor$n)+ m^-^n = fromTensor $ (asTensor$m) ^-^ (asTensor$n)+ negateV = (fromTensor$) . negateV . (asTensor$)+instance (LSpace v, LSpace w, Scalar v~s, Scalar w~s)+ => VectorSpace (LinearMap s v w) where+ type Scalar (LinearMap s v w) = s+ μ*^v = arr fromTensor . (scaleTensor$μ) . arr asTensor $ v++instance (LSpace v, LSpace w, Scalar v~s, Scalar w~s)+ => AdditiveGroup (Tensor s v w) where+ zeroV = zeroTensor+ (^+^) = addTensors+ (^-^) = subtractTensors+ negateV = arr negateTensor+instance (LSpace v, LSpace w, Scalar v~s, Scalar w~s)+ => VectorSpace (Tensor s v w) where+ type Scalar (Tensor s v w) = s+ μ*^t = (scaleTensor $ μ) $ t+ +infixr 6 ⊕, >+<, <⊕++(<⊕) :: (u⊗w) -> (v⊗w) -> (u,v)⊗w+m <⊕ n = Tensor $ (m, n)++-- | The dual operation to the tuple constructor, or rather to the+-- '&&&' fanout operation: evaluate two (linear) functions in parallel+-- and sum up the results.+-- The typical use is to concatenate “row vectors” in a matrix definition.+(⊕) :: (u+>w) -> (v+>w) -> (u,v)+>w+LinearMap m ⊕ LinearMap n = LinearMap $ (Tensor m, Tensor n)++-- | ASCII version of '⊕'+(>+<) :: (u+>w) -> (v+>w) -> (u,v)+>w+(>+<) = (⊕)+++instance Category (LinearMap s) where+ type Object (LinearMap s) v = (LSpace v, Scalar v ~ s)+ id = linearId+ (.) = arr . arr composeLinear+instance Num''' s => Cartesian (LinearMap s) where+ type UnitObject (LinearMap s) = ZeroDim s+ swap = (fmap (const0&&&id) $ id) ⊕ (fmap (id&&&const0) $ id)+ attachUnit = fmap (id&&&const0) $ id+ detachUnit = fst+ regroup = sampleLinearFunction $ LinearFunction regroup+ regroup' = sampleLinearFunction $ LinearFunction regroup'+instance Num''' s => Morphism (LinearMap s) where+ f *** g = (fmap (id&&&const0) $ f) ⊕ (fmap (const0&&&id) $ g)+instance Num''' s => PreArrow (LinearMap s) where+ f &&& g = fromTensor $ (fzipTensorWith$id) $ (asTensor $ f, asTensor $ g)+ terminal = zeroV+ fst = sampleLinearFunction $ fst+ snd = sampleLinearFunction $ snd+instance Num''' s => EnhancedCat (->) (LinearMap s) where+ arr m = arr $ applyLinear $ m+instance Num''' s => EnhancedCat (LinearFunction s) (LinearMap s) where+ arr m = applyLinear $ m+instance Num''' s => EnhancedCat (LinearMap s) (LinearFunction s) where+ arr m = sampleLinearFunction $ m++++++ +instance ∀ u v . ( Num''' (Scalar v), LSpace u, LSpace v, Scalar u ~ Scalar v )+ => TensorSpace (u,v) where+ type TensorProduct (u,v) w = (u⊗w, v⊗w)+ zeroTensor = zeroTensor <⊕ zeroTensor+ scaleTensor = scaleTensor&&&scaleTensor >>> LinearFunction (+ uncurry (***) >>> pretendLike Tensor )+ negateTensor = pretendLike Tensor $ negateTensor *** negateTensor+ addTensors (Tensor (fu, fv)) (Tensor (fu', fv')) = (fu ^+^ fu') <⊕ (fv ^+^ fv')+ subtractTensors (Tensor (fu, fv)) (Tensor (fu', fv'))+ = (fu ^-^ fu') <⊕ (fv ^-^ fv')+ toFlatTensor = follow Tensor <<< toFlatTensor *** toFlatTensor+ fromFlatTensor = flout Tensor >>> fromFlatTensor *** fromFlatTensor+ tensorProduct = LinearFunction $ \(u,v) ->+ (tensorProduct$u) &&& (tensorProduct$v) >>> follow Tensor+ transposeTensor = flout Tensor >>> transposeTensor *** transposeTensor >>> fzip+ fmapTensor = LinearFunction $+ \f -> pretendLike Tensor $ (fmapTensor$f) *** (fmapTensor$f)+ fzipTensorWith = bilinearFunction+ $ \f (Tensor (uw, vw), Tensor (ux, vx))+ -> Tensor ( (fzipTensorWith$f)$(uw,ux)+ , (fzipTensorWith$f)$(vw,vx) )+ coerceFmapTensorProduct p cab = case+ ( coerceFmapTensorProduct (fst<$>p) cab+ , coerceFmapTensorProduct (snd<$>p) cab ) of+ (Coercion, Coercion) -> Coercion+instance ∀ u v . ( LinearSpace u, LinearSpace (DualVector u), DualVector (DualVector u) ~ u+ , LinearSpace v, LinearSpace (DualVector v), DualVector (DualVector v) ~ v+ , Scalar u ~ Scalar v, Num''' (Scalar u) )+ => LinearSpace (u,v) where+ type DualVector (u,v) = (DualVector u, DualVector v)+ linearId = (fmap (id&&&const0) $ id) ⊕ (fmap (const0&&&id) $ id)+ -- idTensor = fmapTensor linearCoFst idTensor <⊕ fmapTensor linearCoSnd idTensor+ sampleLinearFunction = LinearFunction $ \f -> (sampleLinearFunction $ f . lCoFst)+ ⊕ (sampleLinearFunction $ f . lCoSnd)+ coerceDoubleDual = Coercion+ blockVectSpan = (blockVectSpan >>> fmap lfstBlock) &&& (blockVectSpan >>> fmap lsndBlock)+ >>> follow Tensor+ contractTensorMap = flout LinearMap+ >>> contractTensorMap . fmap (fst . flout Tensor) . arr fromTensor+ ***contractTensorMap . fmap (snd . flout Tensor) . arr fromTensor+ >>> addV+ contractMapTensor = flout Tensor+ >>> contractMapTensor . fmap (arr fromTensor . fst . flout LinearMap)+ ***contractMapTensor . fmap (arr fromTensor . snd . flout LinearMap)+ >>> addV+ contractTensorWith = LinearFunction $ \(Tensor (fu, fv))+ -> (contractTensorWith$fu) &&& (contractTensorWith$fv)+ contractLinearMapAgainst = flout LinearMap >>> bilinearFunction+ (\(mu,mv) f -> ((contractLinearMapAgainst$fromTensor$mu)$(fst.f))+ + ((contractLinearMapAgainst$fromTensor$mv)$(snd.f)) )+ applyDualVector = LinearFunction $ \(du,dv)+ -> (applyDualVector$du) *** (applyDualVector$dv) >>> addV+ applyLinear = LinearFunction $ \(LinearMap (fu, fv)) ->+ (applyLinear $ (asLinearMap $ fu)) *** (applyLinear $ (asLinearMap $ fv))+ >>> addV+ composeLinear = bilinearFunction $ \f (LinearMap (fu, fv))+ -> f . (asLinearMap $ fu) ⊕ f . (asLinearMap $ fv)++lfstBlock :: ( LSpace u, LSpace v, LSpace w+ , Scalar u ~ Scalar v, Scalar v ~ Scalar w )+ => (u+>w) -+> ((u,v)+>w)+lfstBlock = LinearFunction (⊕zeroV)+lsndBlock :: ( LSpace u, LSpace v, LSpace w+ , Scalar u ~ Scalar v, Scalar v ~ Scalar w )+ => (v+>w) -+> ((u,v)+>w)+lsndBlock = LinearFunction (zeroV⊕)+++-- | @(u+>(v⊗w)) -> (u+>v)⊗w@+deferLinearMap :: Coercion (LinearMap s u (Tensor s v w)) (Tensor s (LinearMap s u v) w)+deferLinearMap = Coercion++-- | @(u+>v)⊗w -> u+>(v⊗w)@+hasteLinearMap :: Coercion (Tensor s (LinearMap s u v) w) (LinearMap s u (Tensor s v w))+hasteLinearMap = Coercion+++lassocTensor :: Coercion (Tensor s u (Tensor s v w)) (Tensor s (Tensor s u v) w)+lassocTensor = Coercion+rassocTensor :: Coercion (Tensor s (Tensor s u v) w) (Tensor s u (Tensor s v w))+rassocTensor = Coercion++instance ∀ s u v . ( Num''' s, LSpace u, LSpace v, Scalar u ~ s, Scalar v ~ s )+ => TensorSpace (LinearMap s u v) where+ type TensorProduct (LinearMap s u v) w = TensorProduct (DualVector u) (Tensor s v w)+ zeroTensor = deferLinearMap $ zeroV+ toFlatTensor = arr deferLinearMap . fmap toFlatTensor+ fromFlatTensor = fmap fromFlatTensor . arr hasteLinearMap+ addTensors t₁ t₂ = deferLinearMap $ (hasteLinearMap$t₁) ^+^ (hasteLinearMap$t₂)+ subtractTensors t₁ t₂ = deferLinearMap $ (hasteLinearMap$t₁) ^-^ (hasteLinearMap$t₂)+ scaleTensor = LinearFunction $ \μ -> arr deferLinearMap . scaleWith μ . arr hasteLinearMap+ negateTensor = arr deferLinearMap . lNegateV . arr hasteLinearMap+ transposeTensor -- t :: (u +> v) ⊗ w+ = arr hasteLinearMap -- u +> (v ⊗ w)+ >>> fmap transposeTensor -- u +> (w ⊗ v)+ >>> arr asTensor -- u' ⊗ (w ⊗ v)+ >>> transposeTensor -- (w ⊗ v) ⊗ u'+ >>> arr rassocTensor -- w ⊗ (v ⊗ u')+ >>> fmap transposeTensor -- w ⊗ (u' ⊗ v)+ >>> arr (fmap fromTensor) -- w ⊗ (u +> v)+ tensorProduct = LinearFunction $ \t -> arr deferLinearMap+ . (flipBilin composeLinear $ t) . blockVectSpan'+ fmapTensor = LinearFunction $ \f+ -> arr deferLinearMap <<< fmap (fmap f) <<< arr hasteLinearMap+ fzipTensorWith = LinearFunction $ \f+ -> arr deferLinearMap <<< fzipWith (fzipWith f)+ <<< arr hasteLinearMap *** arr hasteLinearMap+ coerceFmapTensorProduct = cftlp+ where cftlp :: ∀ a b p . p (LinearMap s u v) -> Coercion a b+ -> Coercion (TensorProduct (DualVector u) (Tensor s v a))+ (TensorProduct (DualVector u) (Tensor s v b))+ cftlp _ c = coerceFmapTensorProduct ([]::[DualVector u])+ (fmap c :: Coercion (v⊗a) (v⊗b))++-- | @((u+>v)+>w) -> v+>(u⊗w)@+coCurryLinearMap :: Coercion (LinearMap s (LinearMap s u v) w) (LinearMap s v (Tensor s u w))+coCurryLinearMap = Coercion++-- | @(u+>(v⊗w)) -> (v+>u)+>w@+coUncurryLinearMap :: Coercion (LinearMap s u (Tensor s v w)) (LinearMap s (LinearMap s v u) w)+coUncurryLinearMap = Coercion++curryLinearMap :: (Num''' s, LSpace u, Scalar u ~ s)+ => Coercion (LinearMap s (Tensor s u v) w) (LinearMap s u (LinearMap s v w))+curryLinearMap = fmap fromTensor . fromTensor . rassocTensor . asTensor++uncurryLinearMap :: (Num''' s, LSpace u, Scalar u ~ s)+ => Coercion (LinearMap s u (LinearMap s v w)) (LinearMap s (Tensor s u v) w)+uncurryLinearMap = fromTensor . lassocTensor . asTensor . fmap asTensor++uncurryLinearFn :: ( Num''' s, LSpace u, LSpace v, LSpace w+ , Scalar u ~ s, Scalar v ~ s, Scalar w ~ s )+ => LinearFunction s u (LinearMap s v w) -+> LinearFunction s (Tensor s u v) w+uncurryLinearFn = bilinearFunction+ $ \f t -> contractMapTensor . fmap f . transposeTensor $ t++instance ∀ s u v . (Num''' s, LSpace u, LSpace v, Scalar u ~ s, Scalar v ~ s)+ => LinearSpace (LinearMap s u v) where+ type DualVector (LinearMap s u v) = LinearMap s v u+ linearId = coUncurryLinearMap $ fmap blockVectSpan $ id+ coerceDoubleDual = Coercion+ blockVectSpan = arr deferLinearMap+ . fmap (arr (fmap coUncurryLinearMap) . blockVectSpan)+ . blockVectSpan'+ applyLinear = bilinearFunction $ \f g -> contractTensorMap $ (coCurryLinearMap$f) . g+ applyDualVector = contractLinearMapAgainst >>> LinearFunction (. applyLinear)+ composeLinear = bilinearFunction $ \f g+ -> coUncurryLinearMap $ fmap (fmap $ applyLinear $ f) $ (coCurryLinearMap$g)+ contractTensorMap = contractTensorMap . fmap (contractMapTensor . arr (fmap hasteLinearMap))+ . arr coCurryLinearMap+ contractMapTensor = contractTensorMap . fmap (contractMapTensor . arr (fmap coCurryLinearMap))+ . arr hasteLinearMap+ contractTensorWith = arr hasteLinearMap >>> bilinearFunction (\l dw+ -> fmap (flipBilin contractTensorWith $ dw) $ l )+ contractLinearMapAgainst = arr coCurryLinearMap >>> bilinearFunction (\l f+ -> (contractLinearMapAgainst . fmap transposeTensor $ l)+ . uncurryLinearFn $f )++instance ∀ s u v . (Num''' s, LSpace u, LSpace v, Scalar u ~ s, Scalar v ~ s)+ => TensorSpace (Tensor s u v) where+ type TensorProduct (Tensor s u v) w = TensorProduct u (Tensor s v w)+ zeroTensor = lassocTensor $ zeroTensor+ toFlatTensor = arr lassocTensor . fmap toFlatTensor+ fromFlatTensor = fmap fromFlatTensor . arr rassocTensor+ addTensors t₁ t₂ = lassocTensor $ (rassocTensor$t₁) ^+^ (rassocTensor$t₂)+ subtractTensors t₁ t₂ = lassocTensor $ (rassocTensor$t₁) ^-^ (rassocTensor$t₂)+ scaleTensor = LinearFunction $ \μ -> arr lassocTensor . scaleWith μ . arr rassocTensor+ negateTensor = arr lassocTensor . lNegateV . arr rassocTensor+ tensorProduct = flipBilin $ LinearFunction $ \w+ -> arr lassocTensor . fmap (flipBilin tensorProduct $ w)+ transposeTensor = fmap transposeTensor . arr rassocTensor+ . transposeTensor . fmap transposeTensor . arr rassocTensor+ fmapTensor = LinearFunction $ \f+ -> arr lassocTensor <<< fmap (fmap f) <<< arr rassocTensor+ fzipTensorWith = LinearFunction $ \f+ -> arr lassocTensor <<< fzipWith (fzipWith f)+ <<< arr rassocTensor *** arr rassocTensor+ coerceFmapTensorProduct = cftlp+ where cftlp :: ∀ a b p . p (Tensor s u v) -> Coercion a b+ -> Coercion (TensorProduct u (Tensor s v a))+ (TensorProduct u (Tensor s v b))+ cftlp _ c = coerceFmapTensorProduct ([]::[u])+ (fmap c :: Coercion (v⊗a) (v⊗b))+instance ∀ s u v . (Num''' s, LSpace u, LSpace v, Scalar u ~ s, Scalar v ~ s)+ => LinearSpace (Tensor s u v) where+ type DualVector (Tensor s u v) = Tensor s (DualVector u) (DualVector v)+ linearId = uncurryLinearMap $ fmap (fmap transposeTensor . blockVectSpan') $ id+ coerceDoubleDual = Coercion+ blockVectSpan = arr lassocTensor . arr (fmap $ fmap uncurryLinearMap)+ . fmap (transposeTensor . arr deferLinearMap) . blockVectSpan+ . arr deferLinearMap . fmap transposeTensor . blockVectSpan'+ applyLinear = LinearFunction $ \f -> contractMapTensor+ . fmap (applyLinear$curryLinearMap$f) . transposeTensor+ applyDualVector = bilinearFunction $ \f t+ -> (contractLinearMapAgainst $ (fromTensor$f))+ . contractTensorWith $ t+ composeLinear = bilinearFunction $ \f g+ -> uncurryLinearMap $ fmap (fmap $ applyLinear $ f) $ (curryLinearMap$g)+ contractTensorMap = contractTensorMap+ . fmap (transposeTensor . contractTensorMap+ . fmap (arr rassocTensor . transposeTensor . arr rassocTensor))+ . arr curryLinearMap+ contractMapTensor = contractTensorMap . fmap transposeTensor . contractMapTensor+ . fmap (arr (curryLinearMap . hasteLinearMap) . transposeTensor)+ . arr rassocTensor+ contractTensorWith = arr rassocTensor >>> bilinearFunction (\l dw+ -> fmap (flipBilin contractTensorWith $ dw) $ l )+ contractLinearMapAgainst = arr curryLinearMap >>> bilinearFunction (\l f+ -> (contractLinearMapAgainst $ l)+ $ contractTensorMap . fmap (transposeTensor . f) )++++type DualSpace v = v+>Scalar v++type Fractional' s = (Fractional s, Eq s, VectorSpace s, Scalar s ~ s)+type Fractional'' s = (Fractional' s, LSpace s)++++instance (Num''' s, LSpace v, Scalar v ~ s)+ => Functor (Tensor s v) (LinearFunction s) (LinearFunction s) where+ fmap f = fmapTensor $ f+instance (Num''' s, LSpace v, Scalar v ~ s)+ => Monoidal (Tensor s v) (LinearFunction s) (LinearFunction s) where+ pureUnit = const0+ fzipWith f = fzipTensorWith $ f++instance (Num''' s, LSpace v, Scalar v ~ s)+ => Functor (LinearMap s v) (LinearFunction s) (LinearFunction s) where+ fmap f = arr fromTensor . fmap f . arr asTensor+instance (Num''' s, LSpace v, Scalar v ~ s)+ => Monoidal (LinearMap s v) (LinearFunction s) (LinearFunction s) where+ pureUnit = const0+ fzipWith f = arr asTensor *** arr asTensor >>> fzipWith f >>> arr fromTensor++instance (Num''' s, TensorSpace v, Scalar v ~ s)+ => Functor (Tensor s v) Coercion Coercion where+ fmap = crcFmap+ where crcFmap :: ∀ s v a b . (TensorSpace v, Scalar v ~ s)+ => Coercion a b -> Coercion (Tensor s v a) (Tensor s v b)+ crcFmap f = case coerceFmapTensorProduct ([]::[v]) f of+ Coercion -> Coercion++instance (LSpace v, Num''' s, Scalar v ~ s)+ => Functor (LinearMap s v) Coercion Coercion where+ fmap = crcFmap+ where crcFmap :: ∀ s v a b . (LSpace v, Num''' s, Scalar v ~ s)+ => Coercion a b -> Coercion (LinearMap s v a) (LinearMap s v b)+ crcFmap f = case coerceFmapTensorProduct ([]::[DualVector v]) f of+ Coercion -> Coercion++instance Category (LinearFunction s) where+ type Object (LinearFunction s) v = (LSpace v, Scalar v ~ s)+ id = LinearFunction id+ LinearFunction f . LinearFunction g = LinearFunction $ f.g+instance Num''' s => Cartesian (LinearFunction s) where+ type UnitObject (LinearFunction s) = ZeroDim s+ swap = LinearFunction swap+ attachUnit = LinearFunction (, Origin)+ detachUnit = LinearFunction fst+ regroup = LinearFunction regroup+ regroup' = LinearFunction regroup'+instance Num''' s => Morphism (LinearFunction s) where+ LinearFunction f***LinearFunction g = LinearFunction $ f***g+instance Num''' s => PreArrow (LinearFunction s) where+ LinearFunction f&&&LinearFunction g = LinearFunction $ f&&&g+ fst = LinearFunction fst; snd = LinearFunction snd+ terminal = const0+instance EnhancedCat (->) (LinearFunction s) where+ arr = getLinearFunction+instance EnhancedCat (LinearFunction s) Coercion where+ arr = LinearFunction . coerceWith++instance (LSpace w, Scalar w ~ s)+ => Functor (LinearFunction s w) (LinearFunction s) (LinearFunction s) where+ fmap f = LinearFunction (f.)+++deferLinearFn :: Coercion (LinearFunction s u (Tensor s v w))+ (Tensor s (LinearFunction s u v) w)+deferLinearFn = Coercion++hasteLinearFn :: Coercion (Tensor s (LinearFunction s u v) w)+ (LinearFunction s u (Tensor s v w))+hasteLinearFn = Coercion+++instance (LSpace u, LSpace v, Scalar u ~ s, Scalar v ~ s)+ => TensorSpace (LinearFunction s u v) where+ type TensorProduct (LinearFunction s u v) w = LinearFunction s u (Tensor s v w)+ zeroTensor = deferLinearFn $ const0+ toFlatTensor = arr deferLinearFn . fmap toFlatTensor+ fromFlatTensor = fmap fromFlatTensor . arr hasteLinearFn+ addTensors t s = deferLinearFn $ (hasteLinearFn$t)^+^(hasteLinearFn$s)+ subtractTensors t s = deferLinearFn $ (hasteLinearFn$t)^-^(hasteLinearFn$s)+ scaleTensor = LinearFunction $ \μ -> arr deferLinearFn . scaleWith μ . arr hasteLinearFn+ negateTensor = arr deferLinearFn . lNegateV . arr hasteLinearFn+ tensorProduct = flipBilin $ LinearFunction $+ \w -> arr deferLinearFn . fmap (flipBilin tensorProduct $ w)+ transposeTensor = arr hasteLinearFn >>> LinearFunction tp+ where tp f = fmap (LinearFunction $ \dw -> (flipBilin contractTensorWith$dw) . f)+ $ idTensor+ fmapTensor = bilinearFunction $ \f g+ -> deferLinearFn $ fmap f . (hasteLinearFn$g)+ fzipTensorWith = bilinearFunction $ \f (g,h)+ -> deferLinearFn $ fzipWith f+ <<< (hasteLinearFn$g)&&&(hasteLinearFn$h)+ coerceFmapTensorProduct = cftpLf+ where cftpLf :: ∀ s u v a b p . TensorSpace v+ => p (LinearFunction s u v) -> Coercion a b+ -> Coercion (LinearFunction s u (Tensor s v a))+ (LinearFunction s u (Tensor s v b))+ cftpLf p c = case coerceFmapTensorProduct ([]::[v]) c of+ Coercion -> Coercion++coCurryLinearFn :: Coercion (LinearMap s (LinearFunction s u v) w)+ (LinearFunction s v (Tensor s u w))+coCurryLinearFn = Coercion++coUncurryLinearFn :: Coercion (LinearFunction s u (Tensor s v w))+ (LinearMap s (LinearFunction s v u) w)+coUncurryLinearFn = Coercion++instance (LSpace u, LSpace v, Scalar u ~ s, Scalar v ~ s)+ => LinearSpace (LinearFunction s u v) where+ type DualVector (LinearFunction s u v) = LinearFunction s v u+ linearId = coUncurryLinearFn $ LinearFunction $+ \v -> fmap (fmap (scaleV v) . applyDualVector) $ idTensor+ coerceDoubleDual = Coercion+ blockVectSpan = arr deferLinearFn . bilinearFunction (\w u+ -> fmap ( arr coUncurryLinearFn+ . fmap (flipBilin tensorProduct$w) . applyLinear )+ $ (blockVectSpan$u) )+ contractTensorMap = arr coCurryLinearFn+ >>> arr (fmap (fmap hasteLinearFn))+ >>> sampleLinearFunction+ >>> fmap contractFnTensor+ >>> contractTensorMap+ contractMapTensor = arr hasteLinearFn+ >>> arr (fmap (fmap coCurryLinearFn))+ >>> sampleLinearFunction+ >>> fmap contractFnTensor+ >>> contractTensorMap+ contractLinearMapAgainst = arr coCurryLinearFn+ >>> bilinearFunction (\v2uw w2uv+ -> trace . fmap (contractTensorFn . fmap v2uw)+ . sampleLinearFunction $ w2uv )+ applyDualVector = sampleLinearFunction >>> contractLinearMapAgainst+ applyLinear = arr coCurryLinearFn >>> LinearFunction (\f+ -> contractTensorFn . fmap f)+ composeLinear = LinearFunction $ \f+ -> arr coCurryLinearFn >>> fmap (fmap $ applyLinear $ f)+ >>> arr coUncurryLinearFn+
+ Math/LinearMap/Category/Instances.hs view
@@ -0,0 +1,228 @@+-- |+-- Module : Math.LinearMap.Category.Instances+-- Copyright : (c) Justus Sagemüller 2016+-- License : GPL v3+-- +-- Maintainer : (@) sagemueller $ geo.uni-koeln.de+-- Stability : experimental+-- Portability : portable+-- +{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE UnicodeSyntax #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE TupleSections #-}++module Math.LinearMap.Category.Instances where++import Math.LinearMap.Category.Class++import Data.VectorSpace+import Data.Basis++import Prelude ()+import qualified Prelude as Hask++import Control.Category.Constrained.Prelude+import Control.Arrow.Constrained++import Data.Coerce+import Data.Type.Coercion++import Data.Foldable (foldl')++import Data.VectorSpace.Free+import qualified Linear.Matrix as Mat+import qualified Linear.Vector as Mat+import qualified Linear.Metric as Mat+import Linear ( V0(V0), V1(V1), V2(V2), V3(V3), V4(V4)+ , _x, _y, _z, _w )+import Control.Lens ((^.))++import Math.LinearMap.Asserted+import Math.VectorSpace.ZeroDimensional+++type ℝ = Double++instance TensorSpace ℝ where+ type TensorProduct ℝ w = w+ zeroTensor = Tensor zeroV+ scaleTensor = LinearFunction (pretendLike Tensor) . scale+ addTensors (Tensor v) (Tensor w) = Tensor $ v ^+^ w+ subtractTensors (Tensor v) (Tensor w) = Tensor $ v ^-^ w+ negateTensor = pretendLike Tensor lNegateV+ toFlatTensor = follow Tensor+ fromFlatTensor = flout Tensor+ tensorProduct = LinearFunction $ \μ -> follow Tensor . scaleWith μ+ transposeTensor = toFlatTensor . flout Tensor+ fmapTensor = LinearFunction $ pretendLike Tensor+ fzipTensorWith = LinearFunction+ $ \f -> follow Tensor <<< f <<< flout Tensor *** flout Tensor+ coerceFmapTensorProduct _ Coercion = Coercion+instance LinearSpace ℝ where+ type DualVector ℝ = ℝ+ linearId = LinearMap 1+ idTensor = Tensor 1+ fromLinearForm = flout LinearMap+ coerceDoubleDual = Coercion+ contractTensorMap = flout Tensor . flout LinearMap+ contractMapTensor = flout LinearMap . flout Tensor+ contractTensorWith = flout Tensor >>> applyDualVector+ contractLinearMapAgainst = flout LinearMap >>> flipBilin lApply+ blockVectSpan = follow Tensor . follow LinearMap+ applyDualVector = scale+ applyLinear = elacs . flout LinearMap+ composeLinear = LinearFunction $ \f -> follow LinearMap . arr f . flout LinearMap++#define FreeLinearSpace(V, LV, tp, bspan, tenspl, dspan, contraction, contraaction) \+instance Num''' s => TensorSpace (V s) where { \+ type TensorProduct (V s) w = V w; \+ zeroTensor = Tensor $ pure zeroV; \+ addTensors (Tensor m) (Tensor n) = Tensor $ liftA2 (^+^) m n; \+ subtractTensors (Tensor m) (Tensor n) = Tensor $ liftA2 (^-^) m n; \+ negateTensor = LinearFunction $ Tensor . fmap negateV . getTensorProduct; \+ scaleTensor = bilinearFunction \+ $ \μ -> Tensor . fmap (μ*^) . getTensorProduct; \+ toFlatTensor = follow Tensor; \+ fromFlatTensor = flout Tensor; \+ tensorProduct = bilinearFunction $ \w v -> Tensor $ fmap (*^v) w; \+ transposeTensor = LinearFunction (tp); \+ fmapTensor = bilinearFunction $ \+ \(LinearFunction f) -> pretendLike Tensor $ fmap f; \+ fzipTensorWith = bilinearFunction $ \+ \(LinearFunction f) (Tensor vw, Tensor vx) \+ -> Tensor $ liftA2 (curry f) vw vx; \+ coerceFmapTensorProduct _ Coercion = Coercion }; \+instance Num''' s => LinearSpace (V s) where { \+ type DualVector (V s) = V s; \+ linearId = LV Mat.identity; \+ idTensor = Tensor Mat.identity; \+ coerceDoubleDual = Coercion; \+ fromLinearForm = flout LinearMap; \+ blockVectSpan = LinearFunction $ Tensor . (bspan); \+ contractTensorMap = LinearFunction $ (contraction) . coerce . getLinearMap; \+ contractMapTensor = LinearFunction $ (contraction) . coerce . getTensorProduct; \+ contractTensorWith = bilinearFunction $ \+ \(Tensor wv) dw -> fmap (arr $ applyDualVector $ dw) wv; \+ contractLinearMapAgainst = bilinearFunction $ getLinearMap >>> (contraaction); \+ applyDualVector = bilinearFunction Mat.dot; \+ applyLinear = bilinearFunction $ \(LV m) \+ -> foldl' (^+^) zeroV . liftA2 (^*) m; \+ composeLinear = bilinearFunction $ \+ \f (LinearMap g) -> LinearMap $ fmap (f$) g }+FreeLinearSpace( V0+ , LinearMap+ , \(Tensor V0) -> zeroV+ , \_ -> V0+ , \_ -> LinearMap V0+ , LinearMap V0+ , \V0 -> zeroV+ , \V0 _ -> 0 )+FreeLinearSpace( V1+ , LinearMap+ , \(Tensor (V1 w₀)) -> w₀⊗V1 1+ , \w -> V1 (LinearMap $ V1 w)+ , \w -> LinearMap $ V1 (Tensor $ V1 w)+ , LinearMap . V1 . blockVectSpan $ V1 1+ , \(V1 (V1 w)) -> w+ , \(V1 x) f -> (f$x)^._x )+FreeLinearSpace( V2+ , LinearMap+ , \(Tensor (V2 w₀ w₁)) -> w₀⊗V2 1 0+ ^+^ w₁⊗V2 0 1+ , \w -> V2 (LinearMap $ V2 w zeroV)+ (LinearMap $ V2 zeroV w)+ , \w -> LinearMap $ V2 (Tensor $ V2 w zeroV)+ (Tensor $ V2 zeroV w)+ , LinearMap $ V2 (blockVectSpan $ V2 1 0)+ (blockVectSpan $ V2 0 1)+ , \(V2 (V2 w₀ _)+ (V2 _ w₁)) -> w₀^+^w₁+ , \(V2 x y) f -> (f$x)^._x + (f$y)^._y )+FreeLinearSpace( V3+ , LinearMap+ , \(Tensor (V3 w₀ w₁ w₂)) -> w₀⊗V3 1 0 0+ ^+^ w₁⊗V3 0 1 0+ ^+^ w₂⊗V3 0 0 1+ , \w -> V3 (LinearMap $ V3 w zeroV zeroV)+ (LinearMap $ V3 zeroV w zeroV)+ (LinearMap $ V3 zeroV zeroV w)+ , \w -> LinearMap $ V3 (Tensor $ V3 w zeroV zeroV)+ (Tensor $ V3 zeroV w zeroV)+ (Tensor $ V3 zeroV zeroV w)+ , LinearMap $ V3 (blockVectSpan $ V3 1 0 0)+ (blockVectSpan $ V3 0 1 0)+ (blockVectSpan $ V3 0 0 1)+ , \(V3 (V3 w₀ _ _)+ (V3 _ w₁ _)+ (V3 _ _ w₂)) -> w₀^+^w₁^+^w₂+ , \(V3 x y z) f -> (f$x)^._x + (f$y)^._y + (f$z)^._z )+FreeLinearSpace( V4+ , LinearMap+ , \(Tensor (V4 w₀ w₁ w₂ w₃)) -> w₀⊗V4 1 0 0 0+ ^+^ w₁⊗V4 0 1 0 0+ ^+^ w₂⊗V4 0 0 1 0+ ^+^ w₃⊗V4 0 0 0 1+ , \w -> V4 (LinearMap $ V4 w zeroV zeroV zeroV)+ (LinearMap $ V4 zeroV w zeroV zeroV)+ (LinearMap $ V4 zeroV zeroV w zeroV)+ (LinearMap $ V4 zeroV zeroV zeroV w)+ , \w -> LinearMap $ V4 (Tensor $ V4 w zeroV zeroV zeroV)+ (Tensor $ V4 zeroV w zeroV zeroV)+ (Tensor $ V4 zeroV zeroV w zeroV)+ (Tensor $ V4 zeroV zeroV zeroV w)+ , LinearMap $ V4 (blockVectSpan $ V4 1 0 0 0)+ (blockVectSpan $ V4 0 1 0 0)+ (blockVectSpan $ V4 0 0 1 0)+ (blockVectSpan $ V4 0 0 0 1)+ , \(V4 (V4 w₀ _ _ _)+ (V4 _ w₁ _ _)+ (V4 _ _ w₂ _)+ (V4 _ _ _ w₃)) -> w₀^+^w₁^+^w₂^+^w₃+ , \(V4 x y z w) f -> (f$x)^._x + (f$y)^._y + (f$z)^._z + (f$w)^._w )++++instance (Num''' n, TensorProduct (DualVector n) n ~ n) => Num (LinearMap n n n) where+ LinearMap n + LinearMap m = LinearMap $ n + m+ LinearMap n - LinearMap m = LinearMap $ n - m+ LinearMap n * LinearMap m = LinearMap $ n * m+ abs (LinearMap n) = LinearMap $ abs n+ signum (LinearMap n) = LinearMap $ signum n+ fromInteger = LinearMap . fromInteger+ +instance (Fractional'' n, TensorProduct (DualVector n) n ~ n)+ => Fractional (LinearMap n n n) where+ LinearMap n / LinearMap m = LinearMap $ n / m+ recip (LinearMap n) = LinearMap $ recip n+ fromRational = LinearMap . fromRational+++++++instance (LSpace u, LSpace v, s~Scalar u, s~Scalar v)+ => AffineSpace (Tensor s u v) where+ type Diff (Tensor s u v) = Tensor s u v+ (.-.) = (^-^)+ (.+^) = (^+^)+instance (LSpace u, LSpace v, s~Scalar u, s~Scalar v)+ => AffineSpace (LinearMap s u v) where+ type Diff (LinearMap s u v) = LinearMap s u v+ (.-.) = (^-^)+ (.+^) = (^+^)+instance (LSpace u, LSpace v, s~Scalar u, s~Scalar v)+ => AffineSpace (LinearFunction s u v) where+ type Diff (LinearFunction s u v) = LinearFunction s u v+ (.-.) = (^-^)+ (.+^) = (^+^)++ +
+ Math/VectorSpace/Docile.hs view
@@ -0,0 +1,637 @@+-- |+-- Module : Math.VectorSpace.Docile+-- Copyright : (c) Justus Sagemüller 2016+-- License : GPL v3+-- +-- Maintainer : (@) sagemueller $ geo.uni-koeln.de+-- Stability : experimental+-- Portability : portable+-- +++{-# LANGUAGE CPP #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE UnicodeSyntax #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ConstraintKinds #-}++module Math.VectorSpace.Docile where++import Math.LinearMap.Category.Class+import Math.LinearMap.Category.Instances+import Math.LinearMap.Asserted++import Data.Tree (Tree(..), Forest)+import Data.List (sortBy, foldl')+import qualified Data.Set as Set+import Data.Set (Set)+import Data.Ord (comparing)+import Data.List (maximumBy, unfoldr)+import Data.Foldable (toList)+import Data.Semigroup++import Data.VectorSpace+import Data.Basis++import Prelude ()+import qualified Prelude as Hask++import Control.Category.Constrained.Prelude hiding ((^))+import Control.Arrow.Constrained++import Linear ( V0(V0), V1(V1), V2(V2), V3(V3), V4(V4)+ , _x, _y, _z, _w )+import qualified Data.Vector.Unboxed as UArr+import Data.VectorSpace.Free+import Math.VectorSpace.ZeroDimensional+import qualified Linear.Matrix as Mat+import qualified Linear.Vector as Mat+import Control.Lens ((^.))+import Data.Coerce++import Numeric.IEEE+++++-- | 'SemiInner' is the class of vector spaces with finite subspaces in which+-- you can define a basis that can be used to project from the whole space+-- into the subspace. The usual application is for using a kind of+-- <https://en.wikipedia.org/wiki/Galerkin_method Galerkin method> to+-- give an approximate solution (see '\$') to a linear equation in a possibly+-- infinite-dimensional space.+-- +-- Of course, this also works for spaces which are already finite-dimensional themselves.+class LSpace v => SemiInner v where+ -- | Lazily enumerate choices of a basis of functionals that can be made dual+ -- to the given vectors, in order of preference (which roughly means, large in+ -- the normal direction.) I.e., if the vector @𝑣@ is assigned early to the+ -- dual vector @𝑣'@, then @(𝑣' $ 𝑣)@ should be large and all the other products+ -- comparably small.+ -- + -- The purpose is that we should be able to make this basis orthonormal+ -- with a ~Gaussian-elimination approach, in a way that stays numerically+ -- stable. This is otherwise known as the /choice of a pivot element/.+ -- + -- For simple finite-dimensional array-vectors, you can easily define this+ -- method using 'cartesianDualBasisCandidates'.+ dualBasisCandidates :: [(Int,v)] -> Forest (Int, DualVector v)++cartesianDualBasisCandidates+ :: [DualVector v] -- ^ Set of canonical basis functionals.+ -> (v -> [ℝ]) -- ^ Decompose a vector in /absolute value/ components.+ -- the list indices should correspond to those in+ -- the functional list.+ -> ([(Int,v)] -> Forest (Int, DualVector v))+ -- ^ Suitable definition of 'dualBasisCandidates'.+cartesianDualBasisCandidates dvs abss vcas = go 0 sorted+ where sorted = sortBy (comparing $ negate . snd . snd)+ [ (i, (av, maximum av)) | (i,v)<-vcas, let av = abss v ]+ go k ((i,(av,_)):scs)+ | k<n = Node (i, dv) (go (k+1) [(i',(zeroAt j av',m)) | (i',(av',m))<-scs])+ : go k scs+ where (j,_) = maximumBy (comparing snd) $ zip jfus av+ dv = dvs !! j+ go _ _ = []+ + jfus = [0 .. n-1]+ n = length dvs+ + zeroAt :: Int -> [ℝ] -> [ℝ]+ zeroAt _ [] = []+ zeroAt 0 (_:l) = (-1/0):l+ zeroAt j (e:l) = e : zeroAt (j-1) l++instance (Fractional'' s, SemiInner s) => SemiInner (ZeroDim s) where+ dualBasisCandidates _ = []+instance (Fractional'' s, SemiInner s) => SemiInner (V0 s) where+ dualBasisCandidates _ = []++(<.>^) :: LSpace v => DualVector v -> v -> Scalar v+f<.>^v = (applyDualVector$f)$v++orthonormaliseDuals :: (SemiInner v, LSpace v, Fractional'' (Scalar v))+ => [(v, DualVector v)] -> [(v,DualVector v)]+orthonormaliseDuals [] = []+orthonormaliseDuals ((v,v'₀):ws)+ = (v,v') : [(w, w' ^-^ (w'<.>^v)*^v') | (w,w')<-wssys]+ where wssys = orthonormaliseDuals ws+ v'₁ = foldl' (\v'i (w,w') -> v'i ^-^ (v'i<.>^w)*^w') v'₀ wssys+ v' = v'₁ ^/ (v'₁<.>^v)++dualBasis :: (SemiInner v, LSpace v, Fractional'' (Scalar v)) => [v] -> [DualVector v]+dualBasis vs = snd <$> orthonormaliseDuals (zip' vsIxed candidates)+ where zip' ((i,v):vs) ((j,v'):ds)+ | i<j = zip' vs ((j,v'):ds)+ | i==j = (v,v') : zip' vs ds+ zip' _ _ = []+ candidates = sortBy (comparing fst) . findBest+ $ dualBasisCandidates vsIxed+ where findBest [] = []+ findBest (Node iv' bv' : _) = iv' : findBest bv'+ vsIxed = zip [0..] vs++instance SemiInner ℝ where+ dualBasisCandidates = fmap ((`Node`[]) . second recip)+ . sortBy (comparing $ negate . abs . snd)+ . filter ((/=0) . snd)++instance (Fractional'' s, Ord s, SemiInner s) => SemiInner (V1 s) where+ dualBasisCandidates = fmap ((`Node`[]) . second recip)+ . sortBy (comparing $ negate . abs . snd)+ . filter ((/=0) . snd)++#define FreeSemiInner(V, sabs) \+instance SemiInner (V) where { \+ dualBasisCandidates \+ = cartesianDualBasisCandidates Mat.basis (fmap sabs . toList) }+FreeSemiInner(V2 ℝ, abs)+FreeSemiInner(V3 ℝ, abs)+FreeSemiInner(V4 ℝ, abs)++instance ∀ u v . ( SemiInner u, SemiInner v, Scalar u ~ Scalar v ) => SemiInner (u,v) where+ dualBasisCandidates = fmap (\(i,(u,v))->((i,u),(i,v))) >>> unzip+ >>> dualBasisCandidates *** dualBasisCandidates+ >>> combineBaseis False mempty+ where combineBaseis :: Bool -> Set Int+ -> ( Forest (Int, DualVector u)+ , Forest (Int, DualVector v) )+ -> Forest (Int, (DualVector u, DualVector v))+ combineBaseis _ _ ([], []) = []+ combineBaseis False forbidden (Node (i,du) bu' : abu, bv)+ | i`Set.member`forbidden = combineBaseis False forbidden (abu, bv)+ | otherwise+ = Node (i, (du, zeroV))+ (combineBaseis True (Set.insert i forbidden) (bu', bv))+ : combineBaseis False forbidden (abu, bv)+ combineBaseis True forbidden (bu, Node (i,dv) bv' : abv)+ | i`Set.member`forbidden = combineBaseis True forbidden (bu, abv)+ | otherwise+ = Node (i, (zeroV, dv))+ (combineBaseis False (Set.insert i forbidden) (bu, bv'))+ : combineBaseis True forbidden (bu, abv)+ combineBaseis _ forbidden (bu, []) = combineBaseis False forbidden (bu,[])+ combineBaseis _ forbidden ([], bv) = combineBaseis True forbidden ([],bv)+++instance ∀ s u v . ( LSpace u, FiniteDimensional (DualVector u), SemiInner (DualVector u)+ , SemiInner v, FiniteDimensional v+ , Scalar u ~ s, Scalar v ~ s, RealFrac' s )+ => SemiInner (Tensor s u v) where+ dualBasisCandidates = map (fmap (second $ arr transposeTensor . arr asTensor))+ . dualBasisCandidates+ . map (second $ arr asLinearMap)++instance ∀ s u v . ( SemiInner u, FiniteDimensional u, Scalar u ~ s+ , SemiInner v, FiniteDimensional v, Scalar v ~ s, RealFrac' s )+ => SemiInner (LinearMap s u v) where+ dualBasisCandidates = sequenceForest+ . map (second pseudoInverse) -- this is not efficient+ where sequenceForest [] = []+ sequenceForest (x:xs) = [Node x $ sequenceForest xs]+ +(^/^) :: (InnerSpace v, Eq (Scalar v), Fractional (Scalar v)) => v -> v -> Scalar v+v^/^w = case (v<.>w) of+ 0 -> 0+ vw -> vw / (w<.>w)++type DList x = [x]->[x]++class (LSpace v, LSpace (Scalar v)) => FiniteDimensional v where+ -- | Whereas 'Basis'-values refer to a single basis vector, a single+ -- 'SubBasis' value represents a collection of such basis vectors,+ -- which can be used to associate a vector with a list of coefficients.+ -- + -- For spaces with a canonical finite basis, 'SubBasis' does not actually+ -- need to contain any information, it can simply have the full finite+ -- basis as its only value. Even for large sparse spaces, it should only+ -- have a very coarse structure that can be shared by many vectors.+ data SubBasis v :: *+ + entireBasis :: SubBasis v+ + enumerateSubBasis :: SubBasis v -> [v]+ + subbasisDimension :: SubBasis v -> Int+ subbasisDimension = length . enumerateSubBasis+ + -- | Split up a linear map in “column vectors” WRT some suitable basis.+ decomposeLinMap :: (LSpace w, Scalar w ~ Scalar v) => (v+>w) -> (SubBasis v, DList w)+ + -- | Expand in the given basis, if possible. Else yield a superbasis of the given+ -- one, in which this /is/ possible, and the decomposition therein.+ decomposeLinMapWithin :: (LSpace w, Scalar w ~ Scalar v)+ => SubBasis v -> (v+>w) -> Either (SubBasis v, DList w) (DList w)+ + -- | Assemble a vector from coefficients in some basis. Return any excess coefficients.+ recomposeSB :: SubBasis v -> [Scalar v] -> (v, [Scalar v])+ + recomposeSBTensor :: (FiniteDimensional w, Scalar w ~ Scalar v)+ => SubBasis v -> SubBasis w -> [Scalar v] -> (v⊗w, [Scalar v])+ + recomposeLinMap :: (LSpace w, Scalar w~Scalar v) => SubBasis v -> [w] -> (v+>w, [w])+ + -- | Given a function that interprets a coefficient-container as a vector representation,+ -- build a linear function mapping to that space.+ recomposeContraLinMap :: (LinearSpace w, Scalar w ~ Scalar v, Hask.Functor f)+ => (f (Scalar w) -> w) -> f (DualVector v) -> v+>w+ + recomposeContraLinMapTensor+ :: ( FiniteDimensional u, LinearSpace w+ , Scalar u ~ Scalar v, Scalar w ~ Scalar v, Hask.Functor f )+ => (f (Scalar w) -> w) -> f (DualVector v⊗DualVector u) -> (v⊗u)+>w+ + -- | The existance of a finite basis gives us an isomorphism between a space+ -- and its dual space. Note that this isomorphism is not natural (i.e. it+ -- depends on the actual choice of basis, unlike everything else in this+ -- library).+ uncanonicallyFromDual :: DualVector v -+> v+ uncanonicallyToDual :: v -+> DualVector v+ +++instance (Num''' s) => FiniteDimensional (ZeroDim s) where+ data SubBasis (ZeroDim s) = ZeroBasis+ entireBasis = ZeroBasis+ enumerateSubBasis ZeroBasis = []+ subbasisDimension ZeroBasis = 0+ recomposeSB ZeroBasis l = (Origin, l)+ recomposeSBTensor ZeroBasis _ l = (Tensor Origin, l)+ recomposeLinMap ZeroBasis l = (LinearMap Origin, l)+ decomposeLinMap _ = (ZeroBasis, id)+ decomposeLinMapWithin ZeroBasis _ = pure id+ recomposeContraLinMap _ _ = LinearMap Origin+ recomposeContraLinMapTensor _ _ = LinearMap Origin+ uncanonicallyFromDual = id+ uncanonicallyToDual = id+ +instance (Num''' s, LinearSpace s) => FiniteDimensional (V0 s) where+ data SubBasis (V0 s) = V0Basis+ entireBasis = V0Basis+ enumerateSubBasis V0Basis = []+ subbasisDimension V0Basis = 0+ recomposeSB V0Basis l = (V0, l)+ recomposeSBTensor V0Basis _ l = (Tensor V0, l)+ recomposeLinMap V0Basis l = (LinearMap V0, l)+ decomposeLinMap _ = (V0Basis, id)+ decomposeLinMapWithin V0Basis _ = pure id+ recomposeContraLinMap _ _ = LinearMap V0+ recomposeContraLinMapTensor _ _ = LinearMap V0+ uncanonicallyFromDual = id+ uncanonicallyToDual = id+ +instance FiniteDimensional ℝ where+ data SubBasis ℝ = RealsBasis+ entireBasis = RealsBasis+ enumerateSubBasis RealsBasis = [1]+ subbasisDimension RealsBasis = 1+ recomposeSB RealsBasis [] = (0, [])+ recomposeSB RealsBasis (μ:cs) = (μ, cs)+ recomposeSBTensor RealsBasis bw = first Tensor . recomposeSB bw+ recomposeLinMap RealsBasis (w:ws) = (LinearMap w, ws)+ decomposeLinMap (LinearMap v) = (RealsBasis, (v:))+ decomposeLinMapWithin RealsBasis (LinearMap v) = pure (v:)+ recomposeContraLinMap fw = LinearMap . fw+ recomposeContraLinMapTensor fw = arr uncurryLinearMap . LinearMap+ . recomposeContraLinMap fw . fmap getTensorProduct+ uncanonicallyFromDual = id+ uncanonicallyToDual = id++#define FreeFiniteDimensional(V, VB, dimens, take, give) \+instance (Num''' s, LSpace s) \+ => FiniteDimensional (V s) where { \+ data SubBasis (V s) = VB; \+ entireBasis = VB; \+ enumerateSubBasis VB = toList $ Mat.identity; \+ subbasisDimension VB = dimens; \+ uncanonicallyFromDual = id; \+ uncanonicallyToDual = id; \+ recomposeSB _ (take:cs) = (give, cs); \+ recomposeSB b cs = recomposeSB b $ cs ++ [0]; \+ recomposeSBTensor VB bw cs = case recomposeMultiple bw dimens cs of \+ {(take:[], cs') -> (Tensor (give), cs')}; \+ recomposeLinMap VB (take:ws') = (LinearMap (give), ws'); \+ decomposeLinMap (LinearMap m) = (VB, (toList m ++)); \+ decomposeLinMapWithin VB (LinearMap m) = pure (toList m ++); \+ recomposeContraLinMap fw mv \+ = LinearMap $ (\v -> fw $ fmap (<.>^v) mv) <$> Mat.identity; \+ recomposeContraLinMapTensor fw mv = LinearMap $ \+ (\v -> fromLinearMap $ recomposeContraLinMap fw \+ $ fmap (\(Tensor q) -> foldl' (^+^) zeroV $ liftA2 (*^) v q) mv) \+ <$> Mat.identity }+FreeFiniteDimensional(V1, V1Basis, 1, c₀ , V1 c₀ )+FreeFiniteDimensional(V2, V2Basis, 2, c₀:c₁ , V2 c₀ c₁ )+FreeFiniteDimensional(V3, V3Basis, 3, c₀:c₁:c₂ , V3 c₀ c₁ c₂ )+FreeFiniteDimensional(V4, V4Basis, 4, c₀:c₁:c₂:c₃, V4 c₀ c₁ c₂ c₃)++recomposeMultiple :: FiniteDimensional w+ => SubBasis w -> Int -> [Scalar w] -> ([w], [Scalar w])+recomposeMultiple bw n dc+ | n<1 = ([], dc)+ | otherwise = case recomposeSB bw dc of+ (w, dc') -> first (w:) $ recomposeMultiple bw (n-1) dc'+ +deriving instance Show (SubBasis ℝ)+ +instance ( FiniteDimensional u, FiniteDimensional v+ , Scalar u ~ Scalar v )+ => FiniteDimensional (u,v) where+ data SubBasis (u,v) = TupleBasis !(SubBasis u) !(SubBasis v)+ entireBasis = TupleBasis entireBasis entireBasis+ enumerateSubBasis (TupleBasis bu bv)+ = ((,zeroV)<$>enumerateSubBasis bu) ++ ((zeroV,)<$>enumerateSubBasis bv)+ subbasisDimension (TupleBasis bu bv) = subbasisDimension bu + subbasisDimension bv+ decomposeLinMap (LinearMap (fu, fv))+ = case (decomposeLinMap (asLinearMap$fu), decomposeLinMap (asLinearMap$fv)) of+ ((bu, du), (bv, dv)) -> (TupleBasis bu bv, du . dv)+ decomposeLinMapWithin (TupleBasis bu bv) (LinearMap (fu, fv))+ = case ( decomposeLinMapWithin bu (asLinearMap$fu)+ , decomposeLinMapWithin bv (asLinearMap$fv) ) of+ (Left (bu', du), Left (bv', dv)) -> Left (TupleBasis bu' bv', du . dv)+ (Left (bu', du), Right dv) -> Left (TupleBasis bu' bv, du . dv)+ (Right du, Left (bv', dv)) -> Left (TupleBasis bu bv', du . dv)+ (Right du, Right dv) -> Right $ du . dv+ recomposeSB (TupleBasis bu bv) coefs = case recomposeSB bu coefs of+ (u, coefs') -> case recomposeSB bv coefs' of+ (v, coefs'') -> ((u,v), coefs'')+ recomposeSBTensor (TupleBasis bu bv) bw cs = case recomposeSBTensor bu bw cs of+ (tuw, cs') -> case recomposeSBTensor bv bw cs' of+ (tvw, cs'') -> (Tensor (tuw, tvw), cs'')+ recomposeLinMap (TupleBasis bu bv) ws = case recomposeLinMap bu ws of+ (lmu, ws') -> first (lmu⊕) $ recomposeLinMap bv ws'+ recomposeContraLinMap fw dds+ = recomposeContraLinMap fw (fst<$>dds)+ ⊕ recomposeContraLinMap fw (snd<$>dds)+ recomposeContraLinMapTensor fw dds+ = uncurryLinearMap+ $ LinearMap ( fromLinearMap . curryLinearMap+ $ recomposeContraLinMapTensor fw (fmap (\(Tensor(tu,_))->tu) dds)+ , fromLinearMap . curryLinearMap+ $ recomposeContraLinMapTensor fw (fmap (\(Tensor(_,tv))->tv) dds) )+ uncanonicallyFromDual = uncanonicallyFromDual *** uncanonicallyFromDual+ uncanonicallyToDual = uncanonicallyToDual *** uncanonicallyToDual+ +deriving instance (Show (SubBasis u), Show (SubBasis v))+ => Show (SubBasis (u,v))+++instance ∀ s u v .+ ( FiniteDimensional u, FiniteDimensional v+ , Scalar u~s, Scalar v~s, Fractional' (Scalar v) )+ => FiniteDimensional (Tensor s u v) where+ data SubBasis (Tensor s u v) = TensorBasis !(SubBasis u) !(SubBasis v)+ entireBasis = TensorBasis entireBasis entireBasis+ enumerateSubBasis (TensorBasis bu bv)+ = [ u⊗v | u <- enumerateSubBasis bu, v <- enumerateSubBasis bv ]+ subbasisDimension (TensorBasis bu bv) = subbasisDimension bu * subbasisDimension bv+ decomposeLinMap muvw = case decomposeLinMap $ curryLinearMap $ muvw of+ (bu, mvwsg) -> first (TensorBasis bu) . go id $ mvwsg []+ where (go, _) = tensorLinmapDecompositionhelpers+ decomposeLinMapWithin (TensorBasis bu bv) muvw+ = case decomposeLinMapWithin bu $ curryLinearMap $ muvw of+ Left (bu', mvwsg) -> let (_, (bv', ws)) = goWith bv id (mvwsg []) id+ in Left (TensorBasis bu' bv', ws)+ where (_, goWith) = tensorLinmapDecompositionhelpers+ recomposeSB (TensorBasis bu bv) = recomposeSBTensor bu bv+ recomposeSBTensor (TensorBasis bu bv) bw+ = first (arr lassocTensor) . recomposeSBTensor bu (TensorBasis bv bw)+ recomposeLinMap (TensorBasis bu bv) ws =+ ( uncurryLinearMap $ fst . recomposeLinMap bu $ unfoldr (pure . recomposeLinMap bv) ws+ , drop (subbasisDimension bu * subbasisDimension bv) ws )+ recomposeContraLinMap = recomposeContraLinMapTensor+ recomposeContraLinMapTensor fw dds+ = uncurryLinearMap . uncurryLinearMap . fmap (curryLinearMap) . curryLinearMap+ $ recomposeContraLinMapTensor fw $ fmap (arr rassocTensor) dds+ uncanonicallyToDual = fmap uncanonicallyToDual + >>> transposeTensor >>> fmap uncanonicallyToDual+ >>> transposeTensor+ uncanonicallyFromDual = fmap uncanonicallyFromDual + >>> transposeTensor >>> fmap uncanonicallyFromDual+ >>> transposeTensor++tensorLinmapDecompositionhelpers+ :: ( FiniteDimensional v, LSpace w , Scalar v~s, Scalar w~s )+ => ( DList w -> [v+>w] -> (SubBasis v, DList w)+ , SubBasis v -> DList w -> [v+>w] -> DList (v+>w)+ -> (Bool, (SubBasis v, DList w)) )+tensorLinmapDecompositionhelpers = (go, goWith)+ where go _ [] = decomposeLinMap zeroV+ go prevdc (mvw:mvws) = case decomposeLinMap mvw of+ (bv, cfs) -> snd (goWith bv prevdc mvws (mvw:))+ goWith bv prevdc [] prevs = (False, (bv, prevdc))+ goWith bv prevdc (mvw:mvws) prevs = case decomposeLinMapWithin bv mvw of+ Right cfs -> goWith bv (prevdc . cfs) mvws (prevs . (mvw:))+ Left (bv', cfs) -> first (const True)+ ( goWith bv' (regoWith bv' (prevs[]) . cfs)+ mvws (prevs . (mvw:)) )+ regoWith _ [] = id+ regoWith bv (mvw:mvws) = case decomposeLinMapWithin bv mvw of+ Right cfs -> cfs . regoWith bv mvws+ Left _ -> error $+ "Misbehaved FiniteDimensional instance: `decomposeLinMapWithin` should,\+ \\nif it cannot decompose in the given basis, do so in a proper\+ \\nsuperbasis of the given one (so that any vector that could be\+ \\ndecomposed in the old basis can also be decomposed in the new one)."+++instance ∀ s u v .+ ( LSpace u, FiniteDimensional (DualVector u), FiniteDimensional v+ , Scalar u~s, Scalar v~s, Fractional' (Scalar v) )+ => FiniteDimensional (LinearMap s u v) where+ data SubBasis (LinearMap s u v) = LinMapBasis !(SubBasis (DualVector u)) !(SubBasis v)+ entireBasis = case entireBasis of TensorBasis bu bv -> LinMapBasis bu bv+ enumerateSubBasis (LinMapBasis bu bv)+ = arr (fmap asLinearMap) . enumerateSubBasis $ TensorBasis bu bv+ subbasisDimension (LinMapBasis bu bv) = subbasisDimension bu * subbasisDimension bv+ decomposeLinMap = first (\(TensorBasis bv bu)->LinMapBasis bu bv)+ . decomposeLinMap . coerce+ decomposeLinMapWithin (LinMapBasis bu bv) m+ = case decomposeLinMapWithin (TensorBasis bv bu) (coerce m) of+ Right ws -> Right ws+ Left (TensorBasis bv' bu', ws) -> Left (LinMapBasis bu' bv', ws)+ recomposeSB (LinMapBasis bu bv)+ = recomposeSB (TensorBasis bu bv) >>> first (arr fromTensor)+ recomposeSBTensor (LinMapBasis bu bv) bw+ = recomposeSBTensor (TensorBasis bu bv) bw >>> first coerce+ recomposeLinMap (LinMapBasis bu bv) ws =+ ( coUncurryLinearMap . fmap asTensor $ fst . recomposeLinMap bv+ $ unfoldr (pure . recomposeLinMap bu) ws+ , drop (subbasisDimension bu * subbasisDimension bv) ws )+ recomposeContraLinMap fw dds = coUncurryLinearMap . fmap fromLinearMap . curryLinearMap+ $ recomposeContraLinMapTensor fw $ fmap (arr asTensor) dds+ recomposeContraLinMapTensor fw dds+ = uncurryLinearMap . coUncurryLinearMap+ . fmap (fromLinearMap . curryLinearMap) . curryLinearMap+ $ recomposeContraLinMapTensor fw $ fmap (arr $ asTensor . hasteLinearMap) dds+ uncanonicallyToDual = fmap uncanonicallyToDual >>> arr asTensor+ >>> transposeTensor >>> arr fromTensor >>> fmap uncanonicallyToDual+ uncanonicallyFromDual = fmap uncanonicallyFromDual >>> arr asTensor+ >>> transposeTensor >>> arr fromTensor >>> fmap uncanonicallyFromDual+ ++infixr 0 \$++-- | Inverse function application, aka solving of a linear system:+-- +-- @+-- f '\$' f '$' v ≡ v+-- +-- f '$' f '\$' u ≡ u+-- @+-- +-- If @f@ does not have full rank, the behaviour is undefined (but we expect+-- it to be reasonably well-behaved or even give a least-squares solution).+-- +-- If you want to solve for multiple RHS vectors, be sure to partially+-- apply this operator to the linear map, like+-- +-- @+-- map (f '\$') [v₁, v₂, ...]+-- @+-- +-- Since most of the work is actually done in triangularising the operator,+-- this may be much faster than+-- +-- @+-- [f '\$' v₁, f '\$' v₂, ...]+-- @+(\$) :: ( FiniteDimensional u, FiniteDimensional v, SemiInner v+ , Scalar u ~ Scalar v, Fractional' (Scalar v) )+ => (u+>v) -> v -> u+(\$) m = fst . \v -> recomposeSB mbas [v'<.>^v | v' <- v's]+ where v's = dualBasis $ mdecomp []+ (mbas, mdecomp) = decomposeLinMap m+ ++pseudoInverse :: ( FiniteDimensional u, FiniteDimensional v, SemiInner v+ , Scalar u ~ Scalar v, Fractional' (Scalar v) )+ => (u+>v) -> v+>u+pseudoInverse m = recomposeContraLinMap (fst . recomposeSB mbas) v's+ where v's = dualBasis $ mdecomp []+ (mbas, mdecomp) = decomposeLinMap m+++-- | The <https://en.wikipedia.org/wiki/Riesz_representation_theorem Riesz representation theorem>+-- provides an isomorphism between a Hilbert space and its (continuous) dual space.+riesz :: (FiniteDimensional v, InnerSpace v) => DualVector v -+> v+riesz = LinearFunction $ \dv ->+ let (bas, compos) = decomposeLinMap $ sampleLinearFunction $ applyDualVector $ dv+ in fst . recomposeSB bas $ compos []++sRiesz :: (FiniteDimensional v, InnerSpace v) => DualSpace v -+> v+sRiesz = LinearFunction $ \dv ->+ let (bas, compos) = decomposeLinMap $ dv+ in fst . recomposeSB bas $ compos []++coRiesz :: (LSpace v, Num''' (Scalar v), InnerSpace v) => v -+> DualVector v+coRiesz = fromFlatTensor . arr asTensor . sampleLinearFunction . inner++-- | Functions are generally a pain to display, but since linear functionals+-- in a Hilbert space can be represented by /vectors/ in that space,+-- this can be used for implementing a 'Show' instance.+showsPrecAsRiesz :: ( FiniteDimensional v, InnerSpace v, Show v+ , HasBasis (Scalar v), Basis (Scalar v) ~ () )+ => Int -> DualSpace v -> ShowS+showsPrecAsRiesz p dv = showParen (p>0) $ ("().<"++)+ . showsPrec 7 (sRiesz$dv)++instance Show (LinearMap ℝ (V0 ℝ) ℝ) where showsPrec = showsPrecAsRiesz+instance Show (LinearMap ℝ (V1 ℝ) ℝ) where showsPrec = showsPrecAsRiesz+instance Show (LinearMap ℝ (V2 ℝ) ℝ) where showsPrec = showsPrecAsRiesz+instance Show (LinearMap ℝ (V3 ℝ) ℝ) where showsPrec = showsPrecAsRiesz+instance Show (LinearMap ℝ (V4 ℝ) ℝ) where showsPrec = showsPrecAsRiesz+++infixl 7 .<++-- | Outer product of a general @v@-vector and a basis element from @w@.+-- Note that this operation is in general pretty inefficient; it is+-- provided mostly to lay out matrix definitions neatly.+(.<) :: ( FiniteDimensional v, Num''' (Scalar v)+ , InnerSpace v, LSpace w, HasBasis w, Scalar v ~ Scalar w )+ => Basis w -> v -> v+>w+bw .< v = sampleLinearFunction $ LinearFunction $ \v' -> recompose [(bw, v<.>v')]++instance Show (LinearMap s v (V0 s)) where+ show _ = "zeroV"+instance (FiniteDimensional v, InnerSpace v, Scalar v ~ ℝ, Show v)+ => Show (LinearMap ℝ v (V1 ℝ)) where+ showsPrec p m = showParen (p>6) $ ("ex .< "++)+ . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._x)) $ m)+instance (FiniteDimensional v, InnerSpace v, Scalar v ~ ℝ, Show v)+ => Show (LinearMap ℝ v (V2 ℝ)) where+ showsPrec p m = showParen (p>6)+ $ ("ex.<"++) . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._x)) $ m)+ . (" ^+^ ey.<"++) . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._y)) $ m)+instance (FiniteDimensional v, InnerSpace v, Scalar v ~ ℝ, Show v)+ => Show (LinearMap ℝ v (V3 ℝ)) where+ showsPrec p m = showParen (p>6)+ $ ("ex.<"++) . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._x)) $ m)+ . (" ^+^ ey.<"++) . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._y)) $ m)+ . (" ^+^ ez.<"++) . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._z)) $ m)+instance (FiniteDimensional v, InnerSpace v, Scalar v ~ ℝ, Show v)+ => Show (LinearMap ℝ v (V4 ℝ)) where+ showsPrec p m = showParen (p>6)+ $ ("ex.<"++) . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._x)) $ m)+ . (" ^+^ ey.<"++) . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._y)) $ m)+ . (" ^+^ ez.<"++) . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._z)) $ m)+ . (" ^+^ ew.<"++) . showsPrec 7 (sRiesz $ fmap (LinearFunction (^._w)) $ m)++++++(^) :: Num a => a -> Int -> a+(^) = (Hask.^)+ ++type HilbertSpace v = (LSpace v, InnerSpace v, DualVector v ~ v)++type RealFrac' s = (IEEE s, HilbertSpace s, Scalar s ~ s)+type RealFloat' s = (RealFrac' s, Floating s)++type SimpleSpace v = ( FiniteDimensional v, FiniteDimensional (DualVector v)+ , SemiInner v, SemiInner (DualVector v)+ , RealFrac' (Scalar v) )+++instance ∀ s u v .+ ( FiniteDimensional u, LSpace v, FiniteFreeSpace v+ , Scalar u~s, Scalar v~s ) => FiniteFreeSpace (LinearMap s u v) where+ freeDimension _ = subbasisDimension (entireBasis :: SubBasis u)+ * freeDimension ([]::[v])+ toFullUnboxVect = decomposeLinMapWithin entireBasis >>> \case+ Right l -> UArr.concat $ toFullUnboxVect <$> l []+ unsafeFromFullUnboxVect arrv = fst . recomposeLinMap entireBasis+ $ [unsafeFromFullUnboxVect $ UArr.slice (dv*j) dv arrv | j <- [0 .. du-1]]+ where du = subbasisDimension (entireBasis :: SubBasis u)+ dv = freeDimension ([]::[v])++instance ∀ s u v .+ ( LSpace u, FiniteDimensional (DualVector u), LSpace v, FiniteFreeSpace v+ , Scalar u~s, Scalar v~s ) => FiniteFreeSpace (Tensor s u v) where+ freeDimension _ = subbasisDimension (entireBasis :: SubBasis (DualVector u))+ * freeDimension ([]::[v])+ toFullUnboxVect = arr asLinearMap >>> decomposeLinMapWithin entireBasis >>> \case+ Right l -> UArr.concat $ toFullUnboxVect <$> l []+ unsafeFromFullUnboxVect arrv = fromLinearMap $ fst . recomposeLinMap entireBasis+ $ [unsafeFromFullUnboxVect $ UArr.slice (dv*j) dv arrv | j <- [0 .. du-1]]+ where du = subbasisDimension (entireBasis :: SubBasis (DualVector u))+ dv = freeDimension ([]::[v])+ +instance ∀ s u v .+ ( FiniteDimensional u, LSpace v, FiniteFreeSpace v+ , Scalar u~s, Scalar v~s ) => FiniteFreeSpace (LinearFunction s u v) where+ freeDimension _ = subbasisDimension (entireBasis :: SubBasis u)+ * freeDimension ([]::[v])+ toFullUnboxVect f = toFullUnboxVect (arr f :: LinearMap s u v)+ unsafeFromFullUnboxVect arrv = arr (unsafeFromFullUnboxVect arrv :: LinearMap s u v)+ +
+ Math/VectorSpace/ZeroDimensional.hs view
@@ -0,0 +1,58 @@+-- |+-- Module : Math.VectorSpace.ZeroDimensional+-- Copyright : (c) Justus Sagemüller 2016+-- License : GPL v3+-- +-- Maintainer : (@) sagemueller $ geo.uni-koeln.de+-- Stability : experimental+-- Portability : portable+-- +{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE UnicodeSyntax #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE StandaloneDeriving #-}++module Math.VectorSpace.ZeroDimensional (+ ZeroDim (..)+ ) where++import Data.AffineSpace+import Data.VectorSpace+import Data.Basis+import Data.Void++++data ZeroDim s = Origin++instance Monoid (ZeroDim s) where+ mempty = Origin+ mappend Origin Origin = Origin++instance AffineSpace (ZeroDim s) where+ type Diff (ZeroDim s) = ZeroDim s+ Origin .+^ Origin = Origin+ Origin .-. Origin = Origin+instance AdditiveGroup (ZeroDim s) where+ zeroV = Origin+ Origin ^+^ Origin = Origin+ negateV Origin = Origin+instance VectorSpace (ZeroDim s) where+ type Scalar (ZeroDim s) = s+ _ *^ Origin = Origin+instance HasBasis (ZeroDim s) where+ type Basis (ZeroDim k) = Void+ basisValue = absurd+ decompose Origin = []+ decompose' Origin = absurd
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ linearmap-category.cabal view
@@ -0,0 +1,57 @@+-- Initial linearmap-family.cabal generated by cabal init. For further +-- documentation, see http://haskell.org/cabal/users-guide/++name: linearmap-category+version: 0.1.0.0+synopsis: Native, complete, matrix-free linear algebra.+description: The term /numerical linear algebra/ is often used almost+ synonymous with /matrix modifications/. However, what's interesting+ for most applications are really just /points in some vector space/+ and linear mappings between them, not matrices (which represent+ points or mappings, but inherently depend on a particular choice+ of basis / coordinate system).+ .+ This library implements the crucial LA operations like solving+ linear equations and eigenvalue problems, without requiring+ that the vectors are represented in some particular basis. Apart+ from conceptual elegance (only operations that are actually+ geometrically sensible will typecheck – this is far stronger than+ just confirming that the dimensions match, as some other libraries+ do), this also opens up good optimisation possibilities: the+ vectors can be unboxed, use dedicated sparse compression, possibly+ carry out the computations on accelerated hardware (GPU etc.).+ The spaces can even be infinite-dimensional (e.g. function spaces).+ .+ The linear algebra algorithms in this package only require the+ vectors to support fundamental operations like addition, scalar+ products, double-dual-space coercion and tensor products; none of+ this requires a basis representation.+homepage: https://github.com/leftaroundabout/linearmap-family+license: GPL-3+license-file: LICENSE+author: Justus Sagemüller+maintainer: (@) sagemueller $ geo.uni-koeln.de+-- copyright: +category: Math+build-type: Simple+-- extra-source-files: +cabal-version: >=1.10++library+ exposed-modules: Math.LinearMap.Category+ Math.VectorSpace.ZeroDimensional+ other-modules: Math.LinearMap.Category.Class+ Math.LinearMap.Asserted+ Math.LinearMap.Category.Instances+ Math.VectorSpace.Docile+ other-extensions: FlexibleInstances, UndecidableInstances, FunctionalDependencies, TypeOperators, TypeFamilies+ build-depends: base >=4.8 && <4.9,+ vector-space >=0.10 && <0.11,+ constrained-categories >=0.3 && <0.4,+ containers, vector,+ free-vector-spaces >= 0.1.1 && < 0.2,+ linear, lens,+ semigroups,+ ieee754 >= 0.7 && < 0.9+ -- hs-source-dirs: + default-language: Haskell2010