packages feed

multilinear 0.2.1 → 0.2.2

raw patch · 19 files changed

+3335/−3372 lines, 19 filesdep ~containersdep ~criteriondep ~deepseqsetup-changed

Dependency ranges changed: containers, criterion, deepseq, mwc-random, primitive, statistics, vector

Files

+ ChangeLog.md view
@@ -0,0 +1,6 @@+# 0.2.2, 2018-11-01
+## Dependencies update
+- ported to LTS-12.16 resolver
+
+# 0.2.1, 2018-10-31
+Initial release
LICENSE view
@@ -1,674 +1,674 @@-                    GNU GENERAL PUBLIC LICENSE-                       Version 3, 29 June 2007-- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>- Everyone is permitted to copy and distribute verbatim copies- of this license document, but changing it is not allowed.--                            Preamble--  The GNU General Public License is a free, copyleft license for-software and other kinds of works.--  The licenses for most software and other practical works are designed-to take away your freedom to share and change the works.  By contrast,-the GNU General Public License is intended to guarantee your freedom to-share and change all versions of a program--to make sure it remains free-software for all its users.  We, the Free Software Foundation, use the-GNU General Public License for most of our software; it applies also to-any other work released this way by its authors.  You can apply it to-your programs, too.--  When we speak of free software, we are referring to freedom, not-price.  Our General Public Licenses are designed to make sure that you-have the freedom to distribute copies of free software (and charge for-them if you wish), that you receive source code or can get it if you-want it, that you can change the software or use pieces of it in new-free programs, and that you know you can do these things.--  To protect your rights, we need to prevent others from denying you-these rights or asking you to surrender the rights.  Therefore, you have-certain responsibilities if you distribute copies of the software, or if-you modify it: responsibilities to respect the freedom of others.--  For example, if you distribute copies of such a program, whether-gratis or for a fee, you must pass on to the recipients the same-freedoms that you received.  You must make sure that they, too, receive-or can get the source code.  And you must show them these terms so they-know their rights.--  Developers that use the GNU GPL protect your rights with two steps:-(1) assert copyright on the software, and (2) offer you this License-giving you legal permission to copy, distribute and/or modify it.--  For the developers' and authors' protection, the GPL clearly explains-that there is no warranty for this free software.  For both users' and-authors' sake, the GPL requires that modified versions be marked as-changed, so that their problems will not be attributed erroneously to-authors of previous versions.--  Some devices are designed to deny users access to install or run-modified versions of the software inside them, although the manufacturer-can do so.  This is fundamentally incompatible with the aim of-protecting users' freedom to change the software.  The systematic-pattern of such abuse occurs in the area of products for individuals to-use, which is precisely where it is most unacceptable.  Therefore, we-have designed this version of the GPL to prohibit the practice for those-products.  If such problems arise substantially in other domains, we-stand ready to extend this provision to those domains in future versions-of the GPL, as needed to protect the freedom of users.--  Finally, every program is threatened constantly by software patents.-States should not allow patents to restrict development and use of-software on general-purpose computers, but in those that do, we wish to-avoid the special danger that patents applied to a free program could-make it effectively proprietary.  To prevent this, the GPL assures that-patents cannot be used to render the program non-free.--  The precise terms and conditions for copying, distribution and-modification follow.--                       TERMS AND CONDITIONS--  0. Definitions.--  "This License" refers to version 3 of the GNU General Public License.--  "Copyright" also means copyright-like laws that apply to other kinds of-works, such as semiconductor masks.--  "The Program" refers to any copyrightable work licensed under this-License.  Each licensee is addressed as "you".  "Licensees" and-"recipients" may be individuals or organizations.--  To "modify" a work means to copy from or adapt all or part of the work-in a fashion requiring copyright permission, other than the making of an-exact copy.  The resulting work is called a "modified version" of the-earlier work or a work "based on" the earlier work.--  A "covered work" means either the unmodified Program or a work based-on the Program.--  To "propagate" a work means to do anything with it that, without-permission, would make you directly or secondarily liable for-infringement under applicable copyright law, except executing it on a-computer or modifying a private copy.  Propagation includes copying,-distribution (with or without modification), making available to the-public, and in some countries other activities as well.--  To "convey" a work means any kind of propagation that enables other-parties to make or receive copies.  Mere interaction with a user through-a computer network, with no transfer of a copy, is not conveying.--  An interactive user interface displays "Appropriate Legal Notices"-to the extent that it includes a convenient and prominently visible-feature that (1) displays an appropriate copyright notice, and (2)-tells the user that there is no warranty for the work (except to the-extent that warranties are provided), that licensees may convey the-work under this License, and how to view a copy of this License.  If-the interface presents a list of user commands or options, such as a-menu, a prominent item in the list meets this criterion.--  1. Source Code.--  The "source code" for a work means the preferred form of the work-for making modifications to it.  "Object code" means any non-source-form of a work.--  A "Standard Interface" means an interface that either is an official-standard defined by a recognized standards body, or, in the case of-interfaces specified for a particular programming language, one that-is widely used among developers working in that language.--  The "System Libraries" of an executable work include anything, other-than the work as a whole, that (a) is included in the normal form of-packaging a Major Component, but which is not part of that Major-Component, and (b) serves only to enable use of the work with that-Major Component, or to implement a Standard Interface for which an-implementation is available to the public in source code form.  A-"Major Component", in this context, means a major essential component-(kernel, window system, and so on) of the specific operating system-(if any) on which the executable work runs, or a compiler used to-produce the work, or an object code interpreter used to run it.--  The "Corresponding Source" for a work in object code form means all-the source code needed to generate, install, and (for an executable-work) run the object code and to modify the work, including scripts to-control those activities.  However, it does not include the work's-System Libraries, or general-purpose tools or generally available free-programs which are used unmodified in performing those activities but-which are not part of the work.  For example, Corresponding Source-includes interface definition files associated with source files for-the work, and the source code for shared libraries and dynamically-linked subprograms that the work is specifically designed to require,-such as by intimate data communication or control flow between those-subprograms and other parts of the work.--  The Corresponding Source need not include anything that users-can regenerate automatically from other parts of the Corresponding-Source.--  The Corresponding Source for a work in source code form is that-same work.--  2. Basic Permissions.--  All rights granted under this License are granted for the term of-copyright on the Program, and are irrevocable provided the stated-conditions are met.  This License explicitly affirms your unlimited-permission to run the unmodified Program.  The output from running a-covered work is covered by this License only if the output, given its-content, constitutes a covered work.  This License acknowledges your-rights of fair use or other equivalent, as provided by copyright law.--  You may make, run and propagate covered works that you do not-convey, without conditions so long as your license otherwise remains-in force.  You may convey covered works to others for the sole purpose-of having them make modifications exclusively for you, or provide you-with facilities for running those works, provided that you comply with-the terms of this License in conveying all material for which you do-not control copyright.  Those thus making or running the covered works-for you must do so exclusively on your behalf, under your direction-and control, on terms that prohibit them from making any copies of-your copyrighted material outside their relationship with you.--  Conveying under any other circumstances is permitted solely under-the conditions stated below.  Sublicensing is not allowed; section 10-makes it unnecessary.--  3. Protecting Users' Legal Rights From Anti-Circumvention Law.--  No covered work shall be deemed part of an effective technological-measure under any applicable law fulfilling obligations under article-11 of the WIPO copyright treaty adopted on 20 December 1996, or-similar laws prohibiting or restricting circumvention of such-measures.--  When you convey a covered work, you waive any legal power to forbid-circumvention of technological measures to the extent such circumvention-is effected by exercising rights under this License with respect to-the covered work, and you disclaim any intention to limit operation or-modification of the work as a means of enforcing, against the work's-users, your or third parties' legal rights to forbid circumvention of-technological measures.--  4. Conveying Verbatim Copies.--  You may convey verbatim copies of the Program's source code as you-receive it, in any medium, provided that you conspicuously and-appropriately publish on each copy an appropriate copyright notice;-keep intact all notices stating that this License and any-non-permissive terms added in accord with section 7 apply to the code;-keep intact all notices of the absence of any warranty; and give all-recipients a copy of this License along with the Program.--  You may charge any price or no price for each copy that you convey,-and you may offer support or warranty protection for a fee.--  5. Conveying Modified Source Versions.--  You may convey a work based on the Program, or the modifications to-produce it from the Program, in the form of source code under the-terms of section 4, provided that you also meet all of these conditions:--    a) The work must carry prominent notices stating that you modified-    it, and giving a relevant date.--    b) The work must carry prominent notices stating that it is-    released under this License and any conditions added under section-    7.  This requirement modifies the requirement in section 4 to-    "keep intact all notices".--    c) You must license the entire work, as a whole, under this-    License to anyone who comes into possession of a copy.  This-    License will therefore apply, along with any applicable section 7-    additional terms, to the whole of the work, and all its parts,-    regardless of how they are packaged.  This License gives no-    permission to license the work in any other way, but it does not-    invalidate such permission if you have separately received it.--    d) If the work has interactive user interfaces, each must display-    Appropriate Legal Notices; however, if the Program has interactive-    interfaces that do not display Appropriate Legal Notices, your-    work need not make them do so.--  A compilation of a covered work with other separate and independent-works, which are not by their nature extensions of the covered work,-and which are not combined with it such as to form a larger program,-in or on a volume of a storage or distribution medium, is called an-"aggregate" if the compilation and its resulting copyright are not-used to limit the access or legal rights of the compilation's users-beyond what the individual works permit.  Inclusion of a covered work-in an aggregate does not cause this License to apply to the other-parts of the aggregate.--  6. Conveying Non-Source Forms.--  You may convey a covered work in object code form under the terms-of sections 4 and 5, provided that you also convey the-machine-readable Corresponding Source under the terms of this License,-in one of these ways:--    a) Convey the object code in, or embodied in, a physical product-    (including a physical distribution medium), accompanied by the-    Corresponding Source fixed on a durable physical medium-    customarily used for software interchange.--    b) Convey the object code in, or embodied in, a physical product-    (including a physical distribution medium), accompanied by a-    written offer, valid for at least three years and valid for as-    long as you offer spare parts or customer support for that product-    model, to give anyone who possesses the object code either (1) a-    copy of the Corresponding Source for all the software in the-    product that is covered by this License, on a durable physical-    medium customarily used for software interchange, for a price no-    more than your reasonable cost of physically performing this-    conveying of source, or (2) access to copy the-    Corresponding Source from a network server at no charge.--    c) Convey individual copies of the object code with a copy of the-    written offer to provide the Corresponding Source.  This-    alternative is allowed only occasionally and noncommercially, and-    only if you received the object code with such an offer, in accord-    with subsection 6b.--    d) Convey the object code by offering access from a designated-    place (gratis or for a charge), and offer equivalent access to the-    Corresponding Source in the same way through the same place at no-    further charge.  You need not require recipients to copy the-    Corresponding Source along with the object code.  If the place to-    copy the object code is a network server, the Corresponding Source-    may be on a different server (operated by you or a third party)-    that supports equivalent copying facilities, provided you maintain-    clear directions next to the object code saying where to find the-    Corresponding Source.  Regardless of what server hosts the-    Corresponding Source, you remain obligated to ensure that it is-    available for as long as needed to satisfy these requirements.--    e) Convey the object code using peer-to-peer transmission, provided-    you inform other peers where the object code and Corresponding-    Source of the work are being offered to the general public at no-    charge under subsection 6d.--  A separable portion of the object code, whose source code is excluded-from the Corresponding Source as a System Library, need not be-included in conveying the object code work.--  A "User Product" is either (1) a "consumer product", which means any-tangible personal property which is normally used for personal, family,-or household purposes, or (2) anything designed or sold for incorporation-into a dwelling.  In determining whether a product is a consumer product,-doubtful cases shall be resolved in favor of coverage.  For a particular-product received by a particular user, "normally used" refers to a-typical or common use of that class of product, regardless of the status-of the particular user or of the way in which the particular user-actually uses, or expects or is expected to use, the product.  A product-is a consumer product regardless of whether the product has substantial-commercial, industrial or non-consumer uses, unless such uses represent-the only significant mode of use of the product.--  "Installation Information" for a User Product means any methods,-procedures, authorization keys, or other information required to install-and execute modified versions of a covered work in that User Product from-a modified version of its Corresponding Source.  The information must-suffice to ensure that the continued functioning of the modified object-code is in no case prevented or interfered with solely because-modification has been made.--  If you convey an object code work under this section in, or with, or-specifically for use in, a User Product, and the conveying occurs as-part of a transaction in which the right of possession and use of the-User Product is transferred to the recipient in perpetuity or for a-fixed term (regardless of how the transaction is characterized), the-Corresponding Source conveyed under this section must be accompanied-by the Installation Information.  But this requirement does not apply-if neither you nor any third party retains the ability to install-modified object code on the User Product (for example, the work has-been installed in ROM).--  The requirement to provide Installation Information does not include a-requirement to continue to provide support service, warranty, or updates-for a work that has been modified or installed by the recipient, or for-the User Product in which it has been modified or installed.  Access to a-network may be denied when the modification itself materially and-adversely affects the operation of the network or violates the rules and-protocols for communication across the network.--  Corresponding Source conveyed, and Installation Information provided,-in accord with this section must be in a format that is publicly-documented (and with an implementation available to the public in-source code form), and must require no special password or key for-unpacking, reading or copying.--  7. Additional Terms.--  "Additional permissions" are terms that supplement the terms of this-License by making exceptions from one or more of its conditions.-Additional permissions that are applicable to the entire Program shall-be treated as though they were included in this License, to the extent-that they are valid under applicable law.  If additional permissions-apply only to part of the Program, that part may be used separately-under those permissions, but the entire Program remains governed by-this License without regard to the additional permissions.--  When you convey a copy of a covered work, you may at your option-remove any additional permissions from that copy, or from any part of-it.  (Additional permissions may be written to require their own-removal in certain cases when you modify the work.)  You may place-additional permissions on material, added by you to a covered work,-for which you have or can give appropriate copyright permission.--  Notwithstanding any other provision of this License, for material you-add to a covered work, you may (if authorized by the copyright holders of-that material) supplement the terms of this License with terms:--    a) Disclaiming warranty or limiting liability differently from the-    terms of sections 15 and 16 of this License; or--    b) Requiring preservation of specified reasonable legal notices or-    author attributions in that material or in the Appropriate Legal-    Notices displayed by works containing it; or--    c) Prohibiting misrepresentation of the origin of that material, or-    requiring that modified versions of such material be marked in-    reasonable ways as different from the original version; or--    d) Limiting the use for publicity purposes of names of licensors or-    authors of the material; or--    e) Declining to grant rights under trademark law for use of some-    trade names, trademarks, or service marks; or--    f) Requiring indemnification of licensors and authors of that-    material by anyone who conveys the material (or modified versions of-    it) with contractual assumptions of liability to the recipient, for-    any liability that these contractual assumptions directly impose on-    those licensors and authors.--  All other non-permissive additional terms are considered "further-restrictions" within the meaning of section 10.  If the Program as you-received it, or any part of it, contains a notice stating that it is-governed by this License along with a term that is a further-restriction, you may remove that term.  If a license document contains-a further restriction but permits relicensing or conveying under this-License, you may add to a covered work material governed by the terms-of that license document, provided that the further restriction does-not survive such relicensing or conveying.--  If you add terms to a covered work in accord with this section, you-must place, in the relevant source files, a statement of the-additional terms that apply to those files, or a notice indicating-where to find the applicable terms.--  Additional terms, permissive or non-permissive, may be stated in the-form of a separately written license, or stated as exceptions;-the above requirements apply either way.--  8. Termination.--  You may not propagate or modify a covered work except as expressly-provided under this License.  Any attempt otherwise to propagate or-modify it is void, and will automatically terminate your rights under-this License (including any patent licenses granted under the third-paragraph of section 11).--  However, if you cease all violation of this License, then your-license from a particular copyright holder is reinstated (a)-provisionally, unless and until the copyright holder explicitly and-finally terminates your license, and (b) permanently, if the copyright-holder fails to notify you of the violation by some reasonable means-prior to 60 days after the cessation.--  Moreover, your license from a particular copyright holder is-reinstated permanently if the copyright holder notifies you of the-violation by some reasonable means, this is the first time you have-received notice of violation of this License (for any work) from that-copyright holder, and you cure the violation prior to 30 days after-your receipt of the notice.--  Termination of your rights under this section does not terminate the-licenses of parties who have received copies or rights from you under-this License.  If your rights have been terminated and not permanently-reinstated, you do not qualify to receive new licenses for the same-material under section 10.--  9. Acceptance Not Required for Having Copies.--  You are not required to accept this License in order to receive or-run a copy of the Program.  Ancillary propagation of a covered work-occurring solely as a consequence of using peer-to-peer transmission-to receive a copy likewise does not require acceptance.  However,-nothing other than this License grants you permission to propagate or-modify any covered work.  These actions infringe copyright if you do-not accept this License.  Therefore, by modifying or propagating a-covered work, you indicate your acceptance of this License to do so.--  10. Automatic Licensing of Downstream Recipients.--  Each time you convey a covered work, the recipient automatically-receives a license from the original licensors, to run, modify and-propagate that work, subject to this License.  You are not responsible-for enforcing compliance by third parties with this License.--  An "entity transaction" is a transaction transferring control of an-organization, or substantially all assets of one, or subdividing an-organization, or merging organizations.  If propagation of a covered-work results from an entity transaction, each party to that-transaction who receives a copy of the work also receives whatever-licenses to the work the party's predecessor in interest had or could-give under the previous paragraph, plus a right to possession of the-Corresponding Source of the work from the predecessor in interest, if-the predecessor has it or can get it with reasonable efforts.--  You may not impose any further restrictions on the exercise of the-rights granted or affirmed under this License.  For example, you may-not impose a license fee, royalty, or other charge for exercise of-rights granted under this License, and you may not initiate litigation-(including a cross-claim or counterclaim in a lawsuit) alleging that-any patent claim is infringed by making, using, selling, offering for-sale, or importing the Program or any portion of it.--  11. Patents.--  A "contributor" is a copyright holder who authorizes use under this-License of the Program or a work on which the Program is based.  The-work thus licensed is called the contributor's "contributor version".--  A contributor's "essential patent claims" are all patent claims-owned or controlled by the contributor, whether already acquired or-hereafter acquired, that would be infringed by some manner, permitted-by this License, of making, using, or selling its contributor version,-but do not include claims that would be infringed only as a-consequence of further modification of the contributor version.  For-purposes of this definition, "control" includes the right to grant-patent sublicenses in a manner consistent with the requirements of-this License.--  Each contributor grants you a non-exclusive, worldwide, royalty-free-patent license under the contributor's essential patent claims, to-make, use, sell, offer for sale, import and otherwise run, modify and-propagate the contents of its contributor version.--  In the following three paragraphs, a "patent license" is any express-agreement or commitment, however denominated, not to enforce a patent-(such as an express permission to practice a patent or covenant not to-sue for patent infringement).  To "grant" such a patent license to a-party means to make such an agreement or commitment not to enforce a-patent against the party.--  If you convey a covered work, knowingly relying on a patent license,-and the Corresponding Source of the work is not available for anyone-to copy, free of charge and under the terms of this License, through a-publicly available network server or other readily accessible means,-then you must either (1) cause the Corresponding Source to be so-available, or (2) arrange to deprive yourself of the benefit of the-patent license for this particular work, or (3) arrange, in a manner-consistent with the requirements of this License, to extend the patent-license to downstream recipients.  "Knowingly relying" means you have-actual knowledge that, but for the patent license, your conveying the-covered work in a country, or your recipient's use of the covered work-in a country, would infringe one or more identifiable patents in that-country that you have reason to believe are valid.--  If, pursuant to or in connection with a single transaction or-arrangement, you convey, or propagate by procuring conveyance of, a-covered work, and grant a patent license to some of the parties-receiving the covered work authorizing them to use, propagate, modify-or convey a specific copy of the covered work, then the patent license-you grant is automatically extended to all recipients of the covered-work and works based on it.--  A patent license is "discriminatory" if it does not include within-the scope of its coverage, prohibits the exercise of, or is-conditioned on the non-exercise of one or more of the rights that are-specifically granted under this License.  You may not convey a covered-work if you are a party to an arrangement with a third party that is-in the business of distributing software, under which you make payment-to the third party based on the extent of your activity of conveying-the work, and under which the third party grants, to any of the-parties who would receive the covered work from you, a discriminatory-patent license (a) in connection with copies of the covered work-conveyed by you (or copies made from those copies), or (b) primarily-for and in connection with specific products or compilations that-contain the covered work, unless you entered into that arrangement,-or that patent license was granted, prior to 28 March 2007.--  Nothing in this License shall be construed as excluding or limiting-any implied license or other defenses to infringement that may-otherwise be available to you under applicable patent law.--  12. No Surrender of Others' Freedom.--  If conditions are imposed on you (whether by court order, agreement or-otherwise) that contradict the conditions of this License, they do not-excuse you from the conditions of this License.  If you cannot convey a-covered work so as to satisfy simultaneously your obligations under this-License and any other pertinent obligations, then as a consequence you may-not convey it at all.  For example, if you agree to terms that obligate you-to collect a royalty for further conveying from those to whom you convey-the Program, the only way you could satisfy both those terms and this-License would be to refrain entirely from conveying the Program.--  13. Use with the GNU Affero General Public License.--  Notwithstanding any other provision of this License, you have-permission to link or combine any covered work with a work licensed-under version 3 of the GNU Affero General Public License into a single-combined work, and to convey the resulting work.  The terms of this-License will continue to apply to the part which is the covered work,-but the special requirements of the GNU Affero General Public License,-section 13, concerning interaction through a network will apply to the-combination as such.--  14. Revised Versions of this License.--  The Free Software Foundation may publish revised and/or new versions of-the GNU General Public License from time to time.  Such new versions will-be similar in spirit to the present version, but may differ in detail to-address new problems or concerns.--  Each version is given a distinguishing version number.  If the-Program specifies that a certain numbered version of the GNU General-Public License "or any later version" applies to it, you have the-option of following the terms and conditions either of that numbered-version or of any later version published by the Free Software-Foundation.  If the Program does not specify a version number of the-GNU General Public License, you may choose any version ever published-by the Free Software Foundation.--  If the Program specifies that a proxy can decide which future-versions of the GNU General Public License can be used, that proxy's-public statement of acceptance of a version permanently authorizes you-to choose that version for the Program.--  Later license versions may give you additional or different-permissions.  However, no additional obligations are imposed on any-author or copyright holder as a result of your choosing to follow a-later version.--  15. Disclaimer of Warranty.--  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY-APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM-IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.--  16. Limitation of Liability.--  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF-SUCH DAMAGES.--  17. Interpretation of Sections 15 and 16.--  If the disclaimer of warranty and limitation of liability provided-above cannot be given local legal effect according to their terms,-reviewing courts shall apply local law that most closely approximates-an absolute waiver of all civil liability in connection with the-Program, unless a warranty or assumption of liability accompanies a-copy of the Program in return for a fee.--                     END OF TERMS AND CONDITIONS--            How to Apply These Terms to Your New Programs--  If you develop a new program, and you want it to be of the greatest-possible use to the public, the best way to achieve this is to make it-free software which everyone can redistribute and change under these terms.--  To do so, attach the following notices to the program.  It is safest-to attach them to the start of each source file to most effectively-state the exclusion of warranty; and each file should have at least-the "copyright" line and a pointer to where the full notice is found.--    {one line to give the program's name and a brief idea of what it does.}-    Copyright (C) {year}  {name of author}--    This program is free software: you can redistribute it and/or modify-    it under the terms of the GNU General Public License as published by-    the Free Software Foundation, either version 3 of the License, or-    (at your option) any later version.--    This program is distributed in the hope that it will be useful,-    but WITHOUT ANY WARRANTY; without even the implied warranty of-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the-    GNU General Public License for more details.--    You should have received a copy of the GNU General Public License-    along with this program.  If not, see <http://www.gnu.org/licenses/>.--Also add information on how to contact you by electronic and paper mail.--  If the program does terminal interaction, make it output a short-notice like this when it starts in an interactive mode:--    {project}  Copyright (C) {year}  {fullname}-    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.-    This is free software, and you are welcome to redistribute it-    under certain conditions; type `show c' for details.--The hypothetical commands `show w' and `show c' should show the appropriate-parts of the General Public License.  Of course, your program's commands-might be different; for a GUI interface, you would use an "about box".--  You should also get your employer (if you work as a programmer) or school,-if any, to sign a "copyright disclaimer" for the program, if necessary.-For more information on this, and how to apply and follow the GNU GPL, see-<http://www.gnu.org/licenses/>.--  The GNU General Public License does not permit incorporating your program-into proprietary programs.  If your program is a subroutine library, you-may consider it more useful to permit linking proprietary applications with-the library.  If this is what you want to do, use the GNU Lesser General-Public License instead of this License.  But first, please read-<http://www.gnu.org/philosophy/why-not-lgpl.html>.+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    {one line to give the program's name and a brief idea of what it does.}
+    Copyright (C) {year}  {name of author}
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    {project}  Copyright (C) {year}  {fullname}
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
README.md view
@@ -1,32 +1,32 @@-# README #--[![Build Status](https://travis-ci.org/ArturB/Multilinear.svg?branch=master)](https://travis-ci.org/ArturB/Multilinear)--Multilinear is general - purpose linear algebra and multi-dimensional array library for Haskell. It provides generic and efficient implementation of linear algebra operations on vectors, linear functionals, matrices and its higher - rank analoges: tensors. It can also be used as simply a miltidimensional arrays for everyone. --### AS FOR NOW, THE LIBRARY IS IN PRODUCTION PHASE  - DO NOT USE IT FOR PRODUCTION!! ###--## Scripting ##--Multilinear is optimized to being used from GHCi. It uses easy and concise notation of Einstein summation convention to calculate complex tasks. Using this, you are able to write for example a deep learnin neural network from scratch in just a few lines of interpreter code. If you want to know more about Einstein convention, see the Wikipedia: https://en.wikipedia.org/wiki/Einstein_notation--## Machine learning ##--Multi-dimensional algebra is especially useful to quickly write machine learning algorithms (eg. neural networks) from scratch. When library will be stable, some examples will be available. --### Installation ###--Installation using Stack. Invoke this command in library folder:--```-stack build-```--### Contribution guidelines ###--If you want to contribute to this library, contact with me. --### Who do I talk to? ###--All copyrights to Artur M. Brodzki.-Contact mail: artur@brodzki.org+# README #
+
+[![Build Status](https://travis-ci.org/ArturB/Multilinear.svg?branch=master)](https://travis-ci.org/ArturB/Multilinear)
+
+Multilinear is general - purpose linear algebra and multi-dimensional array library for Haskell. It provides generic and efficient implementation of linear algebra operations on vectors, linear functionals, matrices and its higher - rank analoges: tensors. It can also be used as simply a miltidimensional arrays for everyone. 
+
+### AS FOR NOW, THE LIBRARY IS IN PRODUCTION PHASE  - DO NOT USE IT FOR PRODUCTION!! ###
+
+## Scripting ##
+
+Multilinear is optimized to being used from GHCi. It uses easy and concise notation of Einstein summation convention to calculate complex tasks. Using this, you are able to write for example a deep learnin neural network from scratch in just a few lines of interpreter code. If you want to know more about Einstein convention, see the Wikipedia: https://en.wikipedia.org/wiki/Einstein_notation
+
+## Machine learning ##
+
+Multi-dimensional algebra is especially useful to quickly write machine learning algorithms (eg. neural networks) from scratch. When library will be stable, some examples will be available. 
+
+### Installation ###
+
+Installation using Stack. Invoke this command in library folder:
+
+```
+stack build
+```
+
+### Contribution guidelines ###
+
+If you want to contribute to this library, contact with me. 
+
+### Who do I talk to? ###
+
+All copyrights to Artur M. Brodzki.
+Contact mail: artur@brodzki.org
Setup.hs view
@@ -1,2 +1,2 @@-import Distribution.Simple-main = defaultMain+import Distribution.Simple
+main = defaultMain
benchmark/Bench.hs view
@@ -1,35 +1,35 @@-{-|-Module      : Bench-Description : Benchmark of Multilinear library-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX---}--module Main (-    main-) where--import           Control.DeepSeq-import           Criterion.Main-import           Criterion.Measurement               as Meas-import           Criterion.Types-import           Multilinear.Generic-import qualified Multilinear.Matrix                  as Matrix--m1 :: Tensor Double-m1 = Matrix.fromIndices "ij" 1000 1000 $ \i j -> fromIntegral (2*i) - exp (fromIntegral j)--m2 :: Tensor Double-m2 = Matrix.fromIndices "jk" 1000 1000 $ \i j -> sin (fromIntegral i) + cos (fromIntegral j)--main :: IO ()-main = do-    putStrLn "Two matrices 1000x1000 multiplying..."-    (meas,_)  <- Meas.measure ( nfIO $ (m1 * m2) `deepseq` putStrLn "End!" ) 1-    putStrLn $ "Measured time: " ++ show (measCpuTime meas) ++ " s."-    return ()-+{-|
+Module      : Bench
+Description : Benchmark of Multilinear library
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+-}
+
+module Main (
+    main
+) where
+
+import           Control.DeepSeq
+import           Criterion.Main
+import           Criterion.Measurement               as Meas
+import           Criterion.Types
+import           Multilinear.Generic
+import qualified Multilinear.Matrix                  as Matrix
+
+m1 :: Tensor Double
+m1 = Matrix.fromIndices "ij" 1000 1000 $ \i j -> fromIntegral (2*i) - exp (fromIntegral j)
+
+m2 :: Tensor Double
+m2 = Matrix.fromIndices "jk" 1000 1000 $ \i j -> sin (fromIntegral i) + cos (fromIntegral j)
+
+main :: IO ()
+main = do
+    putStrLn "Two matrices 1000x1000 multiplying..."
+    (meas,_)  <- Meas.measure ( nfIO $ (m1 * m2) `deepseq` putStrLn "End!" ) 1
+    putStrLn $ "Measured time: " ++ show (measCpuTime meas) ++ " s."
+    return ()
+
multilinear.cabal view
@@ -1,11 +1,13 @@--- This file has been generated from package.yaml by hpack version 0.28.2.
+cabal-version: 1.12
++-- This file has been generated from package.yaml by hpack version 0.31.0. -- -- see: https://github.com/sol/hpack ----- hash: 303f9bcc9eca604310b89a96ec09fc72e7e996959cc498ef5d730cb3051669c3+-- hash: 8c8b8435434271d1b1843d492d988ebe7197f269825a8f98478d0b939b63b23f  name:           multilinear-version:        0.2.1+version:        0.2.2 synopsis:       Comprehensive and efficient (multi)linear algebra implementation. description:    Comprehensive and efficient (multi)linear algebra implementation, based on generic tensor formalism and concise Ricci-Curbastro index syntax. More information available on GitHub: <https://github.com/ArturB/multilinear#readme> category:       Machine learning@@ -17,9 +19,9 @@ license:        BSD3 license-file:   LICENSE build-type:     Simple-cabal-version:  >= 1.10 extra-source-files:     README.md+    ChangeLog.md  source-repository head   type: git@@ -44,15 +46,15 @@   hs-source-dirs:       src   default-extensions: DeriveGeneric FlexibleContexts FlexibleInstances MultiParamTypeClasses-  ghc-options: -O2 -Wall+  ghc-options: -O2 -Wall -fllvm -optlo-O3   build-depends:       base >=4.7 && <5-    , containers-    , deepseq-    , mwc-random-    , primitive-    , statistics-    , vector+    , containers >=0.5+    , deepseq >=1.4+    , mwc-random >=0.13+    , primitive >=0.6+    , statistics >=0.14+    , vector >=0.12   default-language: Haskell2010  test-suite multilinear-test@@ -63,11 +65,11 @@   hs-source-dirs:       test   default-extensions: DeriveGeneric FlexibleContexts FlexibleInstances MultiParamTypeClasses-  ghc-options: -O2 -Wall -threaded -rtsopts -with-rtsopts=-N+  ghc-options: -O2 -Wall -fllvm -optlo-O3 -threaded -rtsopts -with-rtsopts=-N   build-depends:       base >=4.7 && <5-    , criterion-    , deepseq+    , criterion >=1.2+    , deepseq >=1.4     , multilinear   default-language: Haskell2010 @@ -79,10 +81,10 @@   hs-source-dirs:       benchmark   default-extensions: DeriveGeneric FlexibleContexts FlexibleInstances MultiParamTypeClasses-  ghc-options: -O2 -Wall -threaded -rtsopts -with-rtsopts=-N+  ghc-options: -O2 -Wall -fllvm -optlo-O3 -threaded -rtsopts -with-rtsopts=-N   build-depends:       base >=4.7 && <5-    , criterion-    , deepseq+    , criterion >=1.2+    , deepseq >=1.4     , multilinear   default-language: Haskell2010
src/Multilinear.hs view
@@ -1,189 +1,189 @@-{-|-Module      : Multilinear-Description : A (multi)linear algbra library.-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--Multilinear library provides efficient and terse way to deal with linear algebra in Haskell. It is based on concept of tensor - a multidimensional indexed array of numbers. Vectors, matrices and linear functionals are examples of low-order tensors.--= Quick tutorial--Tensors are indexed, each having one or several indices numbering its components. A scalar has no indices, as being simply a value. A vector has one index, because it is a one-dimensional list of numbers. A matrix has two indices, being a bidimensional table of numbers. Tensors are arbitrarily - dimensional, so you can have a vector of matrices (third-order tensor) and so on. Such tensors are especially useful when dealing with more complex task, such as programming neural networks e.g. for deep learning.--Index may be either __lower (contravariant)__ or __upper (covariant)__, depending on its function.--A vector has one __upper__ or __contravariant__ index, because it represents a value, point in a space. A linear functional (called in this library as a __form__) is represented as a list of numbers, similar to vector, but it does not indicate a value, but rather a coefficients of __linear map__  or __transformation__ that takes a vector and returns a number, simply by calculating a linear combination of vector components with weights being a linear functional coefficients. So elements of linear functional are indexed by __lower__ or __covariant__ index.--A matrix also represents a linear transformation, similar to linear functional, but it take a vector and return a vector, not a scalar. So matrix is simply a bunch of linear functionals - each one is a matrix row and returns a one element of resulting vector. These linear functionals are also indexed - of course by an contravariant index, as vector, which is returned by a matrix. So matrix is a tensor with two indices - one uppper (contravariant) and one lower (covariant).--A dot product is - what a surprise! - a linear transformation. But it is different from matrix - it takes two vectors to multiplicate and returns one number. So it needs two lower (covariant) indices. In fact, a dot product is represented as a bidimensional table of numbers - as matrix - but with two lower indices, instead of one upper and one lower. Tensors with several lower indices are called n-forms. Actually, many linear maps that takes two vectors and returns a number are represented in such notation. A dot product is a table filled with zeros but having a 1-s in diagonal of the table - it look visually identical like unit matrix, but it isn't a matrix - it's actually a 2-form. In this library dot product is called (as in abstract maths) a __Kronecker delta__ (in "Multilinear.NForm"").--A cross product takes two vectors and returns a vector of numbers. So, as you can guess, it has three indices - two covariant (lower) and one upper (contravariant). A tensor that corresponds to cross product is called Levi-Civita symbol and is implemented under "Multilinear.Tensor".--As you see, multidimensional indexed arrays - tensors - provide a unified way to deal with linear algebra - such with data (vectors) and functions operating on them (matrices, n-forms). Using tensors instead of limited number of pre-defined functions, you gain a power of universal formalism, where you can express any linear function you want to deal with.--When you apply a linear functional to a vector, you compute a linear combination - or a weighted sum - of its components. It is so common operation in linear algebra,-that it requires a convenient way to note. Einstein (1905) introduced a summation rule:--If you multiply a tensor with lower index __/i/__ by a tensor with upper index with same name __/i__ then the linear combination of its components is automatically computed. The only condition is that an index of vector and index of corresponding linear transformation must have the same name.--== Examples--@-->>> v = Vector.fromIndices "i" 5 $ \\i -> i + 2 (vector v has 5 elements and v[i] = i + 2, indexing from 0)->>> v-\<i:5\>-   | 2-   | 3-   | 4-   | 5-   | 6->>> f = Form.const "i" 5 1 (linear functional has 5 elements and f[i] = 1)->>> f-[i:5] [1,1,1,1,1]->>> f * v-20-@--If you want to apply a vector to matrix, you must simply multiply them. The only condition is - as you can guess - that lower (indicating that matrix is a linear transformation) index of matrix must have the same name as the upper index of vector (indicating that this vector is a argument of matrix linear transformation; an upper index of matrix here indicates that this linear transformation returns a vector)--@-->>> m = Matrix.fromIndices "ij" 5 5 $ \\i j -> i + j->>> m-\<i:5\>-   | [j:5] [0,1,2,3,4]-   | [j:5] [1,2,3,4,5]-   | [j:5] [2,3,4,5,6]-   | [j:5] [3,4,5,6,7]-   | [j:5] [4,5,6,7,8]->>> v = Vector.fromIndices "j" 5 $ \\j -> j (vector v has 5 elements and v[j] = j, indexing from 0)->>> v-\<j:5\>-   | 0-   | 1-   | 2-   | 3-   | 4->>> m * v-\<i:5\>-   | 30-   | 40-   | 50-   | 60-   | 70-@-Note, that result vector is indexed with "i" - the same index as uppper index of our matrix.--If you want to do a matrix multiplication, a lower index of first matrix must have the same name as upper index of second matrix.--@-->>> m1 = Matrix.fromIndices "ij" 3 5 $ \\i j -> i + j->>> m1-\<i:3\>-   | [j:5] [0,1,2,3,4]-   | [j:5] [1,2,3,4,5]-   | [j:5] [2,3,4,5,6]->>> m2 = Matrix.fromIndices "jk" 5 4 $ \\j -> i + j (vector v has 5 elements and v[j] = j, indexing from 0)->>> m2-\<j:5\>-   | [k:4] [0,1,2,3]-   | [k:4] [1,2,3,4]-   | [k:4] [2,3,4,5]-   | [k:4] [3,4,5,6]-   | [k:4] [4,5,6,7]->>> m1 * m2-\<i:3\>-   | [k:4] [30,40,50,60]-   | [k:4] [40,50,60,70]-   | [k:4] [50,60,70,80]-@--Note, that rule that first matrix lower index must be the same as the second matrix upper index corresponeds to the fact, that to multiply two matrices, the widht of first matrix must be the same as width of the second matrix. The rule of matrix multiplication guarantees, that this operation is equivalent to linear functions composition.--The dot product of vectors may be done by simply making one of vectors with lower index, or - more correctly - by applying two vectors to Kronecker delta:--@-->>> v1 = Vector.fromIndices "i" 5 $ \\i -> i + 2 (vector v has 5 elements and v[i] = i + 2, indexing from 0)->>> v1-\<i:5\>-   | 2-   | 3-   | 4-   | 5-   | 6->>> v2 = Vector.fromIndices "j" 5 $ \\j -> j (vector v has 5 elements and v[j] = j, indexing from 0)->>> v2-\<j:5\>-   | 0-   | 1-   | 2-   | 3-   | 4->>> v1 * (lower "j" v2)-50->>> NForm.dot 5 "ij" * v1 * v2 (A Kronecker delta - representing a dot product - of size 5 with indices \"i\" and \"j\" is multiplied by v1 and v2)-50--@--If you want to know more about linear algebra and Einstein convention, read Wikipedia:--- <https://en.wikipedia.org/wiki/Matrix_(mathematics)>-- <https://en.wikipedia.org/wiki/Covariance_and_contravariance_of_vectors>-- <https://en.wikipedia.org/wiki/Einstein_notation>---}--module Multilinear (-    {-module Form,-    module Generic,-    module Index,-    module Index.Finite,-    module Index.Infinite,-    module Matrix,-    module NForm,-    module Tensor,-    module Vector,-    module X-}-) where---- Re-export other library modules-{-import           Multilinear.Class                       as Multilinear-import qualified Multilinear.Form                        as Form-import           Multilinear.Generic                     as Generic-import qualified Multilinear.Index                       as Index-import qualified Multilinear.Index.Finite                as Index.Finite-import qualified Multilinear.Index.Infinite              as Index.Infinite-import qualified Multilinear.Matrix                      as Matrix-import qualified Multilinear.NForm                       as NForm-import qualified Multilinear.NVector                     as NVector-import qualified Multilinear.Tensor                      as Tensor-import qualified Multilinear.Vector                      as Vector--import           Statistics.Distribution                 as X-import           Statistics.Distribution.Beta            as X-import           Statistics.Distribution.Binomial        as X-import           Statistics.Distribution.CauchyLorentz   as X-import           Statistics.Distribution.ChiSquared      as X-import           Statistics.Distribution.Exponential     as X-import           Statistics.Distribution.FDistribution   as X-import           Statistics.Distribution.Gamma           as X-import           Statistics.Distribution.Geometric       as X-import           Statistics.Distribution.Hypergeometric  as X-import           Statistics.Distribution.Laplace         as X-import           Statistics.Distribution.Normal          as X-import           Statistics.Distribution.StudentT        as X-import           Statistics.Distribution.Uniform         as X--import           System.IO.Unsafe                        as X-import           Control.Monad.Trans.Class               as X-import           Control.Monad.Trans.Either              as X-import           Control.Exception.Base                  as X+{-|
+Module      : Multilinear
+Description : A (multi)linear algbra library.
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+Multilinear library provides efficient and terse way to deal with linear algebra in Haskell. It is based on concept of tensor - a multidimensional indexed array of numbers. Vectors, matrices and linear functionals are examples of low-order tensors.
+
+= Quick tutorial
+
+Tensors are indexed, each having one or several indices numbering its components. A scalar has no indices, as being simply a value. A vector has one index, because it is a one-dimensional list of numbers. A matrix has two indices, being a bidimensional table of numbers. Tensors are arbitrarily - dimensional, so you can have a vector of matrices (third-order tensor) and so on. Such tensors are especially useful when dealing with more complex task, such as programming neural networks e.g. for deep learning.
+
+Index may be either __lower (contravariant)__ or __upper (covariant)__, depending on its function.
+
+A vector has one __upper__ or __contravariant__ index, because it represents a value, point in a space. A linear functional (called in this library as a __form__) is represented as a list of numbers, similar to vector, but it does not indicate a value, but rather a coefficients of __linear map__  or __transformation__ that takes a vector and returns a number, simply by calculating a linear combination of vector components with weights being a linear functional coefficients. So elements of linear functional are indexed by __lower__ or __covariant__ index.
+
+A matrix also represents a linear transformation, similar to linear functional, but it take a vector and return a vector, not a scalar. So matrix is simply a bunch of linear functionals - each one is a matrix row and returns a one element of resulting vector. These linear functionals are also indexed - of course by an contravariant index, as vector, which is returned by a matrix. So matrix is a tensor with two indices - one uppper (contravariant) and one lower (covariant).
+
+A dot product is - what a surprise! - a linear transformation. But it is different from matrix - it takes two vectors to multiplicate and returns one number. So it needs two lower (covariant) indices. In fact, a dot product is represented as a bidimensional table of numbers - as matrix - but with two lower indices, instead of one upper and one lower. Tensors with several lower indices are called n-forms. Actually, many linear maps that takes two vectors and returns a number are represented in such notation. A dot product is a table filled with zeros but having a 1-s in diagonal of the table - it look visually identical like unit matrix, but it isn't a matrix - it's actually a 2-form. In this library dot product is called (as in abstract maths) a __Kronecker delta__ (in "Multilinear.NForm"").
+
+A cross product takes two vectors and returns a vector of numbers. So, as you can guess, it has three indices - two covariant (lower) and one upper (contravariant). A tensor that corresponds to cross product is called Levi-Civita symbol and is implemented under "Multilinear.Tensor".
+
+As you see, multidimensional indexed arrays - tensors - provide a unified way to deal with linear algebra - such with data (vectors) and functions operating on them (matrices, n-forms). Using tensors instead of limited number of pre-defined functions, you gain a power of universal formalism, where you can express any linear function you want to deal with.
+
+When you apply a linear functional to a vector, you compute a linear combination - or a weighted sum - of its components. It is so common operation in linear algebra,
+that it requires a convenient way to note. Einstein (1905) introduced a summation rule:
+
+If you multiply a tensor with lower index __/i/__ by a tensor with upper index with same name __/i__ then the linear combination of its components is automatically computed. The only condition is that an index of vector and index of corresponding linear transformation must have the same name.
+
+== Examples
+
+@
+
+>>> v = Vector.fromIndices "i" 5 $ \\i -> i + 2 (vector v has 5 elements and v[i] = i + 2, indexing from 0)
+>>> v
+\<i:5\>
+   | 2
+   | 3
+   | 4
+   | 5
+   | 6
+>>> f = Form.const "i" 5 1 (linear functional has 5 elements and f[i] = 1)
+>>> f
+[i:5] [1,1,1,1,1]
+>>> f * v
+20
+@
+
+If you want to apply a vector to matrix, you must simply multiply them. The only condition is - as you can guess - that lower (indicating that matrix is a linear transformation) index of matrix must have the same name as the upper index of vector (indicating that this vector is a argument of matrix linear transformation; an upper index of matrix here indicates that this linear transformation returns a vector)
+
+@
+
+>>> m = Matrix.fromIndices "ij" 5 5 $ \\i j -> i + j
+>>> m
+\<i:5\>
+   | [j:5] [0,1,2,3,4]
+   | [j:5] [1,2,3,4,5]
+   | [j:5] [2,3,4,5,6]
+   | [j:5] [3,4,5,6,7]
+   | [j:5] [4,5,6,7,8]
+>>> v = Vector.fromIndices "j" 5 $ \\j -> j (vector v has 5 elements and v[j] = j, indexing from 0)
+>>> v
+\<j:5\>
+   | 0
+   | 1
+   | 2
+   | 3
+   | 4
+>>> m * v
+\<i:5\>
+   | 30
+   | 40
+   | 50
+   | 60
+   | 70
+@
+Note, that result vector is indexed with "i" - the same index as uppper index of our matrix.
+
+If you want to do a matrix multiplication, a lower index of first matrix must have the same name as upper index of second matrix.
+
+@
+
+>>> m1 = Matrix.fromIndices "ij" 3 5 $ \\i j -> i + j
+>>> m1
+\<i:3\>
+   | [j:5] [0,1,2,3,4]
+   | [j:5] [1,2,3,4,5]
+   | [j:5] [2,3,4,5,6]
+>>> m2 = Matrix.fromIndices "jk" 5 4 $ \\j -> i + j (vector v has 5 elements and v[j] = j, indexing from 0)
+>>> m2
+\<j:5\>
+   | [k:4] [0,1,2,3]
+   | [k:4] [1,2,3,4]
+   | [k:4] [2,3,4,5]
+   | [k:4] [3,4,5,6]
+   | [k:4] [4,5,6,7]
+>>> m1 * m2
+\<i:3\>
+   | [k:4] [30,40,50,60]
+   | [k:4] [40,50,60,70]
+   | [k:4] [50,60,70,80]
+@
+
+Note, that rule that first matrix lower index must be the same as the second matrix upper index corresponeds to the fact, that to multiply two matrices, the widht of first matrix must be the same as width of the second matrix. The rule of matrix multiplication guarantees, that this operation is equivalent to linear functions composition.
+
+The dot product of vectors may be done by simply making one of vectors with lower index, or - more correctly - by applying two vectors to Kronecker delta:
+
+@
+
+>>> v1 = Vector.fromIndices "i" 5 $ \\i -> i + 2 (vector v has 5 elements and v[i] = i + 2, indexing from 0)
+>>> v1
+\<i:5\>
+   | 2
+   | 3
+   | 4
+   | 5
+   | 6
+>>> v2 = Vector.fromIndices "j" 5 $ \\j -> j (vector v has 5 elements and v[j] = j, indexing from 0)
+>>> v2
+\<j:5\>
+   | 0
+   | 1
+   | 2
+   | 3
+   | 4
+>>> v1 * (lower "j" v2)
+50
+>>> NForm.dot 5 "ij" * v1 * v2 (A Kronecker delta - representing a dot product - of size 5 with indices \"i\" and \"j\" is multiplied by v1 and v2)
+50
+
+@
+
+If you want to know more about linear algebra and Einstein convention, read Wikipedia:
+
+- <https://en.wikipedia.org/wiki/Matrix_(mathematics)>
+- <https://en.wikipedia.org/wiki/Covariance_and_contravariance_of_vectors>
+- <https://en.wikipedia.org/wiki/Einstein_notation>
+
+-}
+
+module Multilinear (
+    {-module Form,
+    module Generic,
+    module Index,
+    module Index.Finite,
+    module Index.Infinite,
+    module Matrix,
+    module NForm,
+    module Tensor,
+    module Vector,
+    module X-}
+) where
+
+-- Re-export other library modules
+{-import           Multilinear.Class                       as Multilinear
+import qualified Multilinear.Form                        as Form
+import           Multilinear.Generic                     as Generic
+import qualified Multilinear.Index                       as Index
+import qualified Multilinear.Index.Finite                as Index.Finite
+import qualified Multilinear.Index.Infinite              as Index.Infinite
+import qualified Multilinear.Matrix                      as Matrix
+import qualified Multilinear.NForm                       as NForm
+import qualified Multilinear.NVector                     as NVector
+import qualified Multilinear.Tensor                      as Tensor
+import qualified Multilinear.Vector                      as Vector
+
+import           Statistics.Distribution                 as X
+import           Statistics.Distribution.Beta            as X
+import           Statistics.Distribution.Binomial        as X
+import           Statistics.Distribution.CauchyLorentz   as X
+import           Statistics.Distribution.ChiSquared      as X
+import           Statistics.Distribution.Exponential     as X
+import           Statistics.Distribution.FDistribution   as X
+import           Statistics.Distribution.Gamma           as X
+import           Statistics.Distribution.Geometric       as X
+import           Statistics.Distribution.Hypergeometric  as X
+import           Statistics.Distribution.Laplace         as X
+import           Statistics.Distribution.Normal          as X
+import           Statistics.Distribution.StudentT        as X
+import           Statistics.Distribution.Uniform         as X
+
+import           System.IO.Unsafe                        as X
+import           Control.Monad.Trans.Class               as X
+import           Control.Monad.Trans.Either              as X
+import           Control.Exception.Base                  as X
 -}
src/Multilinear/Class.hs view
@@ -154,7 +154,6 @@ {-| Multidimensional array treated as multilinear map - tensor -}
 class (
   Num (t a),     -- Tensors may be added, subtracted and multiplicated
-  Monoid (t a),  -- Tensors are monoids with concatenation as monoid operation
   Functor t      -- Tensor should be a Functor for convenience
   ) => Multilinear t a where
 
@@ -301,10 +300,6 @@     infixl 9 <<<|
     (<<<|) :: t a -> String -> t a
     t <<<| n = shiftLeftmost t n
-
-    {-| Concatenation of two tensors by common index -}
-    {-| Tensors must be equivalent: 'equiv' t1 t2 == True -}
-    augment ::  t a -> t a -> String -> t a
 
     {-| Simple mapping -}
     {-| @map f t@ returns tensor @t2@ in which @t2[i1,i2,...] = f t[i1,i2,...]@ -}
src/Multilinear/Form.hs view
@@ -1,173 +1,173 @@-{-|-Module      : Multilinear.Form-Description : Linear functional constructors (finitely- or infinitely-dimensional)-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--- This module provides convenient constructors that generates a linear functionals-- Finitely-dimensional functionals provide much greater performance that infinitely-dimensional---}--module Multilinear.Form (-  -- * Generators-  -- ** Finite functionals-  Multilinear.Form.fromIndices, -  Multilinear.Form.const,-  Multilinear.Form.randomDouble,-   Multilinear.Form.randomDoubleSeed,-  Multilinear.Form.randomInt, -  Multilinear.Form.randomIntSeed,-  -- ** Infinite functionals-  Multilinear.Form.fromIndices', -  Multilinear.Form.const'-) where--import           Control.Monad.Primitive-import           Multilinear.Generic-import           Multilinear.Index.Infinite as Infinite-import           Multilinear.Tensor         as Tensor-import           Statistics.Distribution--invalidIndices :: String-invalidIndices = "Indices and its sizes not compatible with structure of linear functional!"---- * Finite functional generators--{-| Generate linear functional as function of indices -}-{-# INLINE fromIndices #-}-fromIndices :: (-    Num a-  ) => String        -- ^ Index name (one character)-    -> Int           -- ^ Number of elements-    -> (Int -> a)    -- ^ Generator function - returns a linear functional component at index @i@-    -> Tensor a      -- ^ Generated linear functional--fromIndices [i] s f = Tensor.fromIndices ([],[]) ([i],[s]) $ \[] [x] -> f x-fromIndices _ _ _ = Err invalidIndices--{-| Generate linear functional with all components equal to some @v@ -}-{-# INLINE Multilinear.Form.const #-}-const :: (-    Num a-  ) => String      -- ^ Index name (one character)-    -> Int         -- ^ Number of elements-    -> a           -- ^ Value of each element-    -> Tensor a    -- ^ Generated linear functional--const [i] s = Tensor.const ([],[]) ([i],[s])-const _ _ = \_ -> Err invalidIndices--{-| Generate linear functional with random real components with given probability distribution.-The functional is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDouble #-}-randomDouble :: (-    ContGen d-  ) => String              -- ^ Index name (one character)-    -> Int                 -- ^ Number of elements-    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Double)  -- ^ Generated linear functional--randomDouble [i] s = Tensor.randomDouble ([],[]) ([i],[s])-randomDouble _ _ = \_ -> return $ Err invalidIndices--{-| Generate linear functional with random integer components with given probability distribution.-The functional is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomInt #-}-randomInt :: (-    DiscreteGen d-  ) => String             -- ^ Index name (one character)-    -> Int                -- ^ Number of elements-    -> d                  -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Int)    -- ^ Generated linear functional--randomInt [i] s = Tensor.randomInt ([],[]) ([i],[s])-randomInt _ _ = \_ -> return $ Err invalidIndices--{-| Generate linear functional with random real components with given probability distribution and given seed.-The functional is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDoubleSeed #-}-randomDoubleSeed :: (-    ContGen d, PrimMonad m-  ) => String                 -- ^ Index name (one character)-    -> Int                    -- ^ Number of elements-    -> d                      -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> Int                    -- ^ Randomness seed-    -> m (Tensor Double)      -- ^ Generated linear functional--randomDoubleSeed [i] s = Tensor.randomDoubleSeed ([],[]) ([i],[s])-randomDoubleSeed _ _ = \_ _ -> return $ Err invalidIndices--{-| Generate linear functional with random integer components with given probability distribution and given seed.-The functional is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomIntSeed #-}-randomIntSeed :: (-    DiscreteGen d, PrimMonad m-  ) => String                -- ^ Index name (one character)-    -> Int                   -- ^ Number of elements-    -> d                     -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> Int                   -- ^ Randomness seed-    -> m (Tensor Int)        -- ^ Generated linear functional--randomIntSeed [i] s = Tensor.randomIntSeed ([],[]) ([i],[s])-randomIntSeed _ _ = \_ _ -> return $ Err invalidIndices--{-| Generate linear functional as function of indices -}-{-# INLINE fromIndices' #-}-fromIndices' :: (-    Num a-  ) => String        -- ^ Index name (one character)-    -> (Int -> a)    -- ^ Generator function - returns a linear functional component at index @i@-    -> Tensor a      -- ^ Generated linear functional--fromIndices' i = case i of-    [d] -> \f -> InfiniteTensor (Infinite.Covariant [d]) $ (Scalar . f) <$> [0..]-    _   -> \_ -> Err invalidIndices--{-| Generate linear functional with all components equal to some @v@ -}-{-# INLINE Multilinear.Form.const' #-}-const' :: (-    Num a-  ) => String      -- ^ Index name (one character)-    -> a           -- ^ Value of each element-    -> Tensor a    -- ^ Generated linear functional--const' i = case i of-    [d] -> \v -> InfiniteTensor (Infinite.Covariant [d]) $ (\_ -> Scalar v) <$> ([0..] :: [Int])-    _   -> \_ -> Err invalidIndices-+{-|
+Module      : Multilinear.Form
+Description : Linear functional constructors (finitely- or infinitely-dimensional)
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+- This module provides convenient constructors that generates a linear functionals
+- Finitely-dimensional functionals provide much greater performance that infinitely-dimensional
+
+-}
+
+module Multilinear.Form (
+  -- * Generators
+  -- ** Finite functionals
+  Multilinear.Form.fromIndices, 
+  Multilinear.Form.const,
+  Multilinear.Form.randomDouble,
+   Multilinear.Form.randomDoubleSeed,
+  Multilinear.Form.randomInt, 
+  Multilinear.Form.randomIntSeed,
+  -- ** Infinite functionals
+  Multilinear.Form.fromIndices', 
+  Multilinear.Form.const'
+) where
+
+import           Control.Monad.Primitive
+import           Multilinear.Generic
+import           Multilinear.Index.Infinite as Infinite
+import           Multilinear.Tensor         as Tensor
+import           Statistics.Distribution
+
+invalidIndices :: String
+invalidIndices = "Indices and its sizes not compatible with structure of linear functional!"
+
+-- * Finite functional generators
+
+{-| Generate linear functional as function of indices -}
+{-# INLINE fromIndices #-}
+fromIndices :: (
+    Num a
+  ) => String        -- ^ Index name (one character)
+    -> Int           -- ^ Number of elements
+    -> (Int -> a)    -- ^ Generator function - returns a linear functional component at index @i@
+    -> Tensor a      -- ^ Generated linear functional
+
+fromIndices [i] s f = Tensor.fromIndices ([],[]) ([i],[s]) $ \[] [x] -> f x
+fromIndices _ _ _ = Err invalidIndices
+
+{-| Generate linear functional with all components equal to some @v@ -}
+{-# INLINE Multilinear.Form.const #-}
+const :: (
+    Num a
+  ) => String      -- ^ Index name (one character)
+    -> Int         -- ^ Number of elements
+    -> a           -- ^ Value of each element
+    -> Tensor a    -- ^ Generated linear functional
+
+const [i] s = Tensor.const ([],[]) ([i],[s])
+const _ _ = \_ -> Err invalidIndices
+
+{-| Generate linear functional with random real components with given probability distribution.
+The functional is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDouble #-}
+randomDouble :: (
+    ContGen d
+  ) => String              -- ^ Index name (one character)
+    -> Int                 -- ^ Number of elements
+    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Double)  -- ^ Generated linear functional
+
+randomDouble [i] s = Tensor.randomDouble ([],[]) ([i],[s])
+randomDouble _ _ = \_ -> return $ Err invalidIndices
+
+{-| Generate linear functional with random integer components with given probability distribution.
+The functional is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomInt #-}
+randomInt :: (
+    DiscreteGen d
+  ) => String             -- ^ Index name (one character)
+    -> Int                -- ^ Number of elements
+    -> d                  -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Int)    -- ^ Generated linear functional
+
+randomInt [i] s = Tensor.randomInt ([],[]) ([i],[s])
+randomInt _ _ = \_ -> return $ Err invalidIndices
+
+{-| Generate linear functional with random real components with given probability distribution and given seed.
+The functional is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDoubleSeed #-}
+randomDoubleSeed :: (
+    ContGen d, PrimMonad m
+  ) => String                 -- ^ Index name (one character)
+    -> Int                    -- ^ Number of elements
+    -> d                      -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> Int                    -- ^ Randomness seed
+    -> m (Tensor Double)      -- ^ Generated linear functional
+
+randomDoubleSeed [i] s = Tensor.randomDoubleSeed ([],[]) ([i],[s])
+randomDoubleSeed _ _ = \_ _ -> return $ Err invalidIndices
+
+{-| Generate linear functional with random integer components with given probability distribution and given seed.
+The functional is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomIntSeed #-}
+randomIntSeed :: (
+    DiscreteGen d, PrimMonad m
+  ) => String                -- ^ Index name (one character)
+    -> Int                   -- ^ Number of elements
+    -> d                     -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> Int                   -- ^ Randomness seed
+    -> m (Tensor Int)        -- ^ Generated linear functional
+
+randomIntSeed [i] s = Tensor.randomIntSeed ([],[]) ([i],[s])
+randomIntSeed _ _ = \_ _ -> return $ Err invalidIndices
+
+{-| Generate linear functional as function of indices -}
+{-# INLINE fromIndices' #-}
+fromIndices' :: (
+    Num a
+  ) => String        -- ^ Index name (one character)
+    -> (Int -> a)    -- ^ Generator function - returns a linear functional component at index @i@
+    -> Tensor a      -- ^ Generated linear functional
+
+fromIndices' i = case i of
+    [d] -> \f -> InfiniteTensor (Infinite.Covariant [d]) $ (Scalar . f) <$> [0..]
+    _   -> \_ -> Err invalidIndices
+
+{-| Generate linear functional with all components equal to some @v@ -}
+{-# INLINE Multilinear.Form.const' #-}
+const' :: (
+    Num a
+  ) => String      -- ^ Index name (one character)
+    -> a           -- ^ Value of each element
+    -> Tensor a    -- ^ Generated linear functional
+
+const' i = case i of
+    [d] -> \v -> InfiniteTensor (Infinite.Covariant [d]) $ (\_ -> Scalar v) <$> ([0..] :: [Int])
+    _   -> \_ -> Err invalidIndices
+
src/Multilinear/Generic.hs view
@@ -1,1070 +1,1030 @@-{-|-Module      : Multilinear.Generic.AsArray-Description : Generic array tensor-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--- This module contains generic implementation of tensor defined as nested arrays---}--module Multilinear.Generic (-    Tensor(..), (!), mergeScalars,-    isScalar, isSimple, isFiniteTensor, isInfiniteTensor,-    dot, _elemByElem, contractionErr, tensorIndex, _standardize-) where--import           Control.DeepSeq-import           Data.Bits-import           Data.Foldable-import           Data.List-import           Data.Maybe-import           Data.Monoid-import qualified Data.Vector                as Boxed-import           GHC.Generics-import           Multilinear.Class          as Multilinear-import qualified Multilinear.Index          as Index-import qualified Multilinear.Index.Finite   as Finite-import qualified Multilinear.Index.Infinite as Infinite--{-| ERROR MESSAGES -}-incompatibleTypes :: String-incompatibleTypes = "Incompatible tensor types!"--scalarIndices :: String-scalarIndices = "Scalar has no indices!"--differentIndices :: String-differentIndices = "Tensors have different indices!"--infiniteIndex :: String-infiniteIndex = "Index is infinitely-dimensional!"--infiniteTensor :: String-infiniteTensor = "This tensor is infinitely-dimensional and cannot be printed!"--indexNotFound :: String-indexNotFound = "This tensor has not such index!"--{-| Tensor defined recursively as scalar or list of other tensors -}-{-| @c@ is type of a container, @i@ is type of index size and @a@ is type of tensor elements -}-data Tensor a =-    {-| Scalar -}-    Scalar {-        {-| value of scalar -}-        scalarVal :: a-    } |-    {-| Simple, one-dimensional finite tensor -}-    SimpleFinite {-        tensorFiniteIndex :: Finite.Index,-        tensorScalars     :: Boxed.Vector a-    } |-    {-| Finite array of other tensors -}-    FiniteTensor {-        {-| Finite index "Mutltilinear.Index.Finite" of tensor -}-        tensorFiniteIndex :: Finite.Index,-        {-| Array of tensors on deeper recursion level -}-        tensorsFinite     :: Boxed.Vector (Tensor a)-    } |-    {-| Infinite list of other tensors -}-    InfiniteTensor {-        {-| Infinite index "Mutltilinear.Index.Infinite" of tensor -}-        tensorInfiniteIndex :: Infinite.Index,-        {-| Infinite list of tensors on deeper recursion level -}-        tensorsInfinite     :: [Tensor a]-    } |-    {-| Operations on tensors may throw an error -}-    Err {-        {-| Error message -}-        errMessage :: String-    } deriving (Eq, Generic)--{-| Return true if tensor is a scalar -}-{-# INLINE isScalar #-}-isScalar :: Tensor a -> Bool-isScalar x = case x of-    Scalar _ -> True-    _        -> False--{-| Return true if tensor is a simple tensor -}-{-# INLINE isSimple #-}-isSimple :: Tensor a -> Bool-isSimple x = case x of-    SimpleFinite _ _ -> True-    _                -> False--{-| Return True if tensor is a complex tensor -}-{-# INLINE isFiniteTensor #-}-isFiniteTensor :: Tensor a -> Bool-isFiniteTensor x = case x of-    FiniteTensor _ _ -> True-    _                -> False--{-| Return True if tensor is a infinite tensor -}-{-# INLINE isInfiniteTensor #-}-isInfiniteTensor :: Tensor a -> Bool-isInfiniteTensor x = case x of-    InfiniteTensor _ _ -> True-    _                  -> False--{- Return True if tensor is a error tensor -}-{-# INLINE isErrTensor #-}-isErrTensor :: Tensor a -> Bool-isErrTensor x = case x of-    Err _ -> True-    _     -> False--{-| Return generic tensor index -}-{-# INLINE tensorIndex #-}-tensorIndex :: Tensor a -> Index.TIndex-tensorIndex x = case x of-    Scalar _           -> error scalarIndices-    SimpleFinite i _   -> Index.toTIndex i-    FiniteTensor i _   -> Index.toTIndex i-    InfiniteTensor i _ -> Index.toTIndex i-    Err msg            -> error msg--{-| Return True if tensor has no elements -}-{-# INLINE isEmptyTensor #-}-isEmptyTensor :: Tensor a -> Bool-isEmptyTensor x = case x of-    Scalar _            -> False-    SimpleFinite _ ts   -> Boxed.null ts-    FiniteTensor _ ts   -> Boxed.null ts-    InfiniteTensor _ ts -> null ts-    Err _               -> False--{-| Returns sample element of the tensor. Used to determine some features common for all elements, like bit-qualities. -}-{-# INLINE firstElem #-}-firstElem :: Tensor a -> a-firstElem x = case x of-    Scalar val          -> val-    SimpleFinite _ ts   -> Boxed.head ts-    FiniteTensor _ ts   -> firstElem $ Boxed.head ts-    InfiniteTensor _ ts -> firstElem $ head ts-    Err msg             -> error msg--{-| Returns sample tensor on deeper recursion level.Used to determine some features common for all tensors -}-{-# INLINE firstTensor #-}-firstTensor :: Tensor a -> Tensor a-firstTensor x = case x of-    FiniteTensor _ ts   -> Boxed.head ts-    InfiniteTensor _ ts -> Data.List.head ts-    _                   -> x--{-| Recursive indexing on list tensor-    @t ! i = t[i]@ -}-{-# INLINE (!) #-}-(!) :: Tensor a      -- ^ tensor @t@-    -> Int           -- ^ index @i@-    -> Tensor a      -- ^ tensor @t[i]@-t ! i = case t of-    Scalar _            -> Err scalarIndices-    Err msg             -> Err msg-    SimpleFinite ind ts -> if i >= Finite.indexSize ind then error ("Index + " ++ show ind ++ " out of bonds!") else Scalar $ ts Boxed.! i-    FiniteTensor ind ts -> if i >= Finite.indexSize ind then error ("Index + " ++ show ind ++ " out of bonds!") else ts Boxed.! i-    InfiniteTensor _ ts -> ts !! i---- NFData instance-instance NFData a => NFData (Tensor a)---- move contravariant indices to lower recursion level-_standardize :: Num a => Tensor a -> Tensor a-_standardize tens = foldr' (\i t -> if Index.isContravariant i then t <<<| Index.indexName i else t) tens $ indices tens---- Print tensor-instance (-    Show a, Num a-    ) => Show (Tensor a) where--    -- merge errors first and then print whole tensor-    show = show' . _standardize . _mergeErr-        where-        show' x = case x of-            -- Scalar is showed simply as its value-            Scalar v -> show v-            -- SimpleFinite is shown dependent on its index...-            SimpleFinite index ts -> show index ++ "S: " ++ case index of-                -- If index is contravariant, show tensor components vertically-                Finite.Contravariant _ _ -> _showVertical ts-                -- If index is covariant or indifferent, show tensor compoments horizontally-                _                        -> _showHorizontal ts-            -- FiniteTensor is shown dependent on its index...-            FiniteTensor index ts -> show index ++ "T: " ++ case index of-                -- If index is contravariant, show tensor components vertically-                Finite.Contravariant _ _ -> _showVertical ts-                -- If index is covariant or indifferent, show tensor compoments horizontally-                _                        -> _showHorizontal ts-            -- Infinite tensor print erorr message as it cannot be fully shown-            InfiniteTensor _ _ -> show infiniteTensor-            -- Error prints its error message-            Err msg -> show msg-            -        -- Merge many errors in tensor to the first one-        _mergeErr x = case x of-            -- Error tensor is passed further-            Err msg -> Err msg-            -- FiniteTensor is merged to first error on deeper recursion level-            FiniteTensor _ ts ->-                -- find first error if present-                let err = Data.List.find isErrTensor (_mergeErr <$> ts)-                -- and return this error if found, whole tensor otherwise-                in fromMaybe x err-            -- in other types of tensor cannot be any error-            _ -> x--        -- print container elements vertically-        -- used to show contravariant components of tensor, which by convention are written vertically-        _showVertical :: (Show a, Foldable c) => c a -> String-        _showVertical container =-            "\n" ++ tail (foldl' (\string e -> string ++ "\n  |" ++ show e) "" container)--        -- print container elements horizontally-        -- used to show covariant (or indifferent) components of tensor, which by convention are written horizontally-        _showHorizontal :: (Show a, Foldable c) => c a -> String-        _showHorizontal container =-            "[" ++ tail (foldl' (\string e -> string ++ "," ++ show e) "" container) ++ "]"---- Tensor is a functor-instance Functor Tensor where--    {-# INLINE fmap #-}-    fmap f x = case x of-        -- Mapping scalar simply maps its value-        Scalar v                -> Scalar $ f v-        -- Mapping complex tensor does mapping element by element-        SimpleFinite index ts   -> SimpleFinite index (f <$> ts)-        FiniteTensor index ts   -> FiniteTensor index $ fmap (fmap f) ts-        InfiniteTensor index ts -> InfiniteTensor index $ fmap (fmap f) ts-        -- Mapping errors changes nothing-        Err msg                 -> Err msg---- Tensors can be compared lexigographically--- Allowes to put tensors in typical ordered containers-instance (-    Ord a-    ) => Ord (Tensor a) where--    {-# INLINE (<=) #-}-    -- Error is smaller by other tensors, so when printing ordered containers, all erorrs will be printed first-    -- Two errors are compared by they messages lexigographically-    Err msg1 <= Err msg2 = msg1 <= msg2-    Err _ <= _ = True-    _ <= Err _ = False-    -- Scalar is smaller than any complex tensor-    -- Two scalars are compared by they values-    Scalar x1 <= Scalar x2 = x1 <= x2-    Scalar _ <= _ = True-    _ <= Scalar _ = False-    -- Complex tensors are compared lexigographically-    SimpleFinite _ ts1 <= SimpleFinite _ ts2     = ts1 <= ts2-    FiniteTensor _ ts1 <= FiniteTensor _ ts2     = ts1 <= ts2-    InfiniteTensor _ ts1 <= InfiniteTensor _ ts2 = ts1 <= ts2-    FiniteTensor _ _ <= SimpleFinite _ _         = False-    SimpleFinite _ _ <= FiniteTensor _ _         = True-    InfiniteTensor _ _ <= FiniteTensor _ _       = False-    FiniteTensor _ _ <= InfiniteTensor _ _       = True-    InfiniteTensor _ _ <= SimpleFinite _ _       = False-    SimpleFinite _ _ <= InfiniteTensor _ _       = True---- Tensors concatenation makes them a monoid-instance (-    Num a-    ) => Monoid (Tensor a) where--    {-| Neutral element is a scalar as it has no indices and concatenation is by common inidces -}-    {-# INLINE mempty #-}-    mempty = Scalar 0--    {-| Tensor concatenation -}-    {-# INLINE mappend #-}-    mappend t1 t2 = -        -- To preserve tensor structure, indices must be the same-        if indices t1 == indices t2 -        then case (t1,t2) of-            -- Concatenation with scalar does nothing - Scalar is a neutral element-            (Scalar _, _) -> t2-            (_, Scalar _) -> t1-            -- Concatenation of two SimpleFiniteTensors-            (SimpleFinite i1 ts1, SimpleFinite _ ts2) -> -                SimpleFinite i1 $ ts1 <> ts2-            -- Concatenation of two FiniteTensors-            (FiniteTensor i1 ts1, FiniteTensor _ ts2) ->-                FiniteTensor i1 $ ts1 <> ts2-            -- Concatenation of other tensors (especially infinite ones) is impossible-            _ -> Err differentIndices-        -- If tensor indices are different, concatenation is impossible-        else Err differentIndices--{-| Merge FiniteTensor of Scalars to SimpleFinite tensor for performance improvement -}-{-# INLINE mergeScalars #-}-mergeScalars :: Tensor a -> Tensor a-mergeScalars x = case x of-    (FiniteTensor index1 ts1) -> case ts1 Boxed.! 0 of-        Scalar _ -> SimpleFinite index1 (scalarVal <$> ts1)-        _        -> FiniteTensor index1 $ mergeScalars <$> ts1-    _ -> x--{-| Apply a tensor operator (here denoted by (+) ) elem by elem, trying to connect as many common indices as possible -}-{-# INLINE _elemByElem' #-}-_elemByElem' :: Num a -             => Tensor a                            -- ^ First argument of operator-             -> Tensor a                            -- ^ Second argument of operator-             -> (a -> a -> a)                       -- ^ Operator on tensor elements if indices are different-             -> (Tensor a -> Tensor a -> Tensor a)  -- ^ Tensor operator called if indices are the same-             -> Tensor a                            -- ^ Result tensor---- @Scalar x + Scalar y = Scalar x + y@-_elemByElem' (Scalar x1) (Scalar x2) f _ = Scalar $ f x1 x2--- @Scalar x + Tensor t[i] = Tensor r[i] | r[i] = x + t[i]@-_elemByElem' (Scalar x) t f _ = (x `f`) <$> t--- @Tensor t[i] + Scalar x = Tensor r[i] | r[i] = t[i] + x@-_elemByElem' t (Scalar x) f _ = (`f` x) <$> t---- Two finite tensors case-_elemByElem' t1@(FiniteTensor index1 v1) t2@(FiniteTensor index2 v2) f op-    | Index.indexName index1 == Index.indexName index2 = op t1 t2-    | Index.indexName index1 `Data.List.elem` indicesNames t2 =-        FiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2-    | otherwise = FiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1---- Two infinite tensors case-_elemByElem' t1@(InfiniteTensor index1 v1) t2@(InfiniteTensor index2 v2) f op-    | Index.indexName index1 == Index.indexName index2 = op t1 t2-    | Index.indexName index1 `Data.List.elem` indicesNames t2 =-        InfiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2-    | otherwise = InfiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1---- Two simple tensors case-_elemByElem' t1@(SimpleFinite index1 v1) t2@(SimpleFinite index2 _) f op-    | Index.indexName index1 == Index.indexName index2 = op t1 t2-    | otherwise = FiniteTensor index1 $ (\x -> f x <$> t2) <$> v1---- Finite and infinite tensor case-_elemByElem' t1@(FiniteTensor index1 v1) t2@(InfiniteTensor index2 v2) f op-    | Index.indexName index1 == Index.indexName index2 = op t1 t2-    | Index.indexName index1 `Data.List.elem` indicesNames t2 =-        InfiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2-    | otherwise = FiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1---- Infinite and finite tensor case-_elemByElem' t1@(InfiniteTensor index1 v1) t2@(FiniteTensor index2 v2) f op-    | Index.indexName index1 == Index.indexName index2 = op t1 t2-    | Index.indexName index1 `Data.List.elem` indicesNames t2 =-        FiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2-    | otherwise = InfiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1---- Simple and finite tensor case-_elemByElem' t1@(SimpleFinite index1 _) t2@(FiniteTensor index2 v2) f op-    | Index.indexName index1 == Index.indexName index2 = op t1 t2-    | otherwise = FiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2---- Finite and simple tensor case-_elemByElem' t1@(FiniteTensor index1 v1) t2@(SimpleFinite index2 _) f op-    | Index.indexName index1 == Index.indexName index2 = op t1 t2-    | otherwise = FiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1---- Simple and infinite tensor case-_elemByElem' t1@(SimpleFinite index1 _) t2@(InfiniteTensor index2 v2) f op-    | Index.indexName index1 == Index.indexName index2 = op t1 t2-    | otherwise = InfiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2---- Infinite and simple tensor case-_elemByElem' t1@(InfiniteTensor index1 v1) t2@(SimpleFinite index2 _) f op-    | Index.indexName index1 == Index.indexName index2 = op t1 t2-    | otherwise = InfiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1---- Appying operator to error tensor simply pushes this error further-_elemByElem' (Err msg) _ _ _ = Err msg-_elemByElem' _ (Err msg) _ _ = Err msg--{-| Apply a tensor operator elem by elem and merge scalars to simple tensor at the and -}-{-# INLINE _elemByElem #-}-_elemByElem :: Num a -            => Tensor a                             -- ^ First argument of operator-            -> Tensor a                             -- ^ Second argument of operator-            -> (a -> a -> a)                        -- ^ Operator on tensor elements if indices are different-            -> (Tensor a -> Tensor a -> Tensor a)   -- ^ Tensor operator called if indices are the same-            -> Tensor a                             -- ^ Result tensor-_elemByElem t1 t2 f op = -    let commonIndices = filter (`Data.List.elem` indicesNames t2) $ indicesNames t1-        t1' = foldl' (|>>>) t1 commonIndices-        t2' = foldl' (|>>>) t2 commonIndices-    in mergeScalars $ _elemByElem' t1' t2' f op---- Zipping two tensors with a combinator, assuming they have the same indices-{-# INLINE zipT #-}-zipT :: Num a-      => (Tensor a -> Tensor a -> Tensor a)   -- ^ Two tensors combinator-      -> (Tensor a -> a -> Tensor a)          -- ^ Tensor and scalar combinator-      -> (a -> Tensor a -> Tensor a)          -- ^ Scalar and tensor combinator-      -> (a -> a -> a)                        -- ^ Two scalars combinator-      -> Tensor a                             -- ^ First tensor to zip-      -> Tensor a                             -- ^ Second tensor to zip-      -> Tensor a                             -- ^ Result tensor---- Two simple tensors case-zipT _ _ _ f (SimpleFinite index1 v1) (SimpleFinite index2 v2) = -    if index1 == index2 then SimpleFinite index1 $ Boxed.zipWith f v1 v2 else Err incompatibleTypes----Two finite tensors case-zipT f _ _ _ (FiniteTensor index1 v1) (FiniteTensor index2 v2)     = -    if index1 == index2 then FiniteTensor index1 $ Boxed.zipWith f v1 v2 else Err incompatibleTypes---- Two infinte tensors case-zipT f _ _ _ (InfiniteTensor index1 v1) (InfiniteTensor index2 v2) = -    if index1 == index2 then InfiniteTensor index1 $ Data.List.zipWith f v1 v2 else Err incompatibleTypes---- Infinite and finite tensor case-zipT f _ _ _ (InfiniteTensor _ v1) (FiniteTensor index2 v2)   = -    FiniteTensor index2 $ Boxed.zipWith f (Boxed.fromList $ take (Boxed.length v2) v1) v2---- Finite and infinite tensor case-zipT f _ _ _ (FiniteTensor index1 v1) (InfiniteTensor _ v2)   = -    FiniteTensor index1 $ Boxed.zipWith f v1 (Boxed.fromList $ take (Boxed.length v1) v2)---- Finite and simple tensor case-zipT _ f _ _ (FiniteTensor index1 v1) (SimpleFinite index2 v2)     = -    if index1 == index2 then FiniteTensor index1 $ Boxed.zipWith f v1 v2 else Err incompatibleTypes---- Simple and finite tensor case-zipT _ _ f _ (SimpleFinite index1 v1) (FiniteTensor index2 v2)     = -    if index1 == index2 then FiniteTensor index1 $ Boxed.zipWith f v1 v2 else Err incompatibleTypes---- Infinite and simple tensor case-zipT _ f _ _ (InfiniteTensor _ v1) (SimpleFinite index2 v2)     = -    FiniteTensor index2 $ Boxed.zipWith f (Boxed.fromList $ take (Boxed.length v2) v1) v2---- Simple and infinite tensor case-zipT _ _ f _ (SimpleFinite index1 v1) (InfiniteTensor _ v2)     = -    FiniteTensor index1 $ Boxed.zipWith f v1 (Boxed.fromList $ take (Boxed.length v1) v2)---- Zipping error tensor simply pushes this erorr further-zipT _ _ _ _ (Err msg) _ = Err msg-zipT _ _ _ _ _ (Err msg) = Err msg---- Zipping something with scalar is impossible-zipT _ _ _ _ _ _ = Err scalarIndices---- dot product of two tensors-{-# INLINE dot #-}-dot :: Num a-      => Tensor a  -- ^ First dot product argument-      -> Tensor a  -- ^ Second dot product argument-      -> Tensor a  -- ^ Resulting dot product---- Two simple tensors product-dot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = -        Scalar $ Boxed.sum $ Boxed.zipWith (*) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)-dot (SimpleFinite i1@(Finite.Contravariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = -        SimpleFinite i1 $ Boxed.zipWith (*) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)-dot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Covariant count2 _) ts2')-    | count1 == count2 = -        SimpleFinite i1 $ Boxed.zipWith (*) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)---- Two finite tensors product-dot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = Boxed.sum $ Boxed.zipWith (*) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)-dot (FiniteTensor i1@(Finite.Contravariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (*) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)-dot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Covariant count2 _) ts2')-    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (*) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)----- Simple tensor and finite tensor product-dot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = Boxed.sum $ Boxed.zipWith (*.) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)-dot (SimpleFinite i1@(Finite.Contravariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (*.) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)-dot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Covariant count2 _) ts2')-    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (*.) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)---- Finite tensor and simple tensor product-dot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = Boxed.sum $ Boxed.zipWith (.*) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)-dot (FiniteTensor i1@(Finite.Contravariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (.*) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)-dot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Covariant count2 _) ts2')-    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (.*) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)---- Simple tensor and infinite tensor product-dot (SimpleFinite (Finite.Covariant count1 _) ts1') (InfiniteTensor (Infinite.Contravariant _) ts2') = -    Boxed.sum $ Boxed.zipWith (*.) ts1' (Boxed.fromList $ take count1 ts2')-dot (SimpleFinite (Finite.Contravariant count1 _) ts1') (InfiniteTensor i2@(Infinite.Contravariant _) ts2') = -    InfiniteTensor i2 $ Boxed.toList $ Boxed.zipWith (*.) ts1' (Boxed.fromList $ take count1 ts2')-dot (SimpleFinite (Finite.Covariant count1 _) ts1') (InfiniteTensor i2@(Infinite.Covariant _) ts2') = -    InfiniteTensor i2 $ Boxed.toList $ Boxed.zipWith (*.) ts1' (Boxed.fromList $ take count1 ts2')---- Infinite tensor and simple tensor product-dot (InfiniteTensor (Infinite.Covariant _) ts1') (SimpleFinite (Finite.Contravariant count2 _) ts2') = -    Boxed.sum $ Boxed.zipWith (.*) (Boxed.fromList $ take count2 ts1') ts2'-dot (InfiniteTensor i1@(Infinite.Contravariant _) ts1') (SimpleFinite (Finite.Contravariant count2 _) ts2') = -    InfiniteTensor i1 $ Boxed.toList $ Boxed.zipWith (.*) (Boxed.fromList $ take count2 ts1') ts2'-dot (InfiniteTensor i1@(Infinite.Covariant _) ts1') (SimpleFinite (Finite.Covariant count2 _) ts2') = -    InfiniteTensor i1 $ Boxed.toList $ Boxed.zipWith (.*) (Boxed.fromList $ take count2 ts1') ts2'---- Finite tensor and infinite tensor product-dot (FiniteTensor (Finite.Covariant count1 _) ts1') (InfiniteTensor (Infinite.Contravariant _) ts2') = -    Boxed.sum $ Boxed.zipWith (*) ts1' (Boxed.fromList $ take count1 ts2')-dot (FiniteTensor (Finite.Contravariant count1 _) ts1') (InfiniteTensor i2@(Infinite.Contravariant _) ts2') = -    InfiniteTensor i2 $ Boxed.toList $ Boxed.zipWith (*) ts1' (Boxed.fromList $ take count1 ts2')-dot (FiniteTensor (Finite.Covariant count1 _) ts1') (InfiniteTensor i2@(Infinite.Covariant _) ts2') = -    InfiniteTensor i2 $ Boxed.toList $ Boxed.zipWith (*) ts1' (Boxed.fromList $ take count1 ts2')---- Infinite tensor and finite tensor product-dot (InfiniteTensor (Infinite.Covariant _) ts1') (FiniteTensor (Finite.Contravariant count2 _) ts2') = -    Boxed.sum $ Boxed.zipWith (*) (Boxed.fromList $ take count2 ts1') ts2'-dot (InfiniteTensor i1@(Infinite.Contravariant _) ts1') (FiniteTensor (Finite.Contravariant count2 _) ts2') = -    InfiniteTensor i1 $ Boxed.toList $ Boxed.zipWith (*) (Boxed.fromList $ take count2 ts1') ts2'-dot (InfiniteTensor i1@(Infinite.Covariant _) ts1') (FiniteTensor (Finite.Covariant count2 _) ts2') = -    InfiniteTensor i1 $ Boxed.toList $ Boxed.zipWith (*) (Boxed.fromList $ take count2 ts1') ts2'---- In other cases cannot happen!-dot t1' t2' = contractionErr (tensorIndex t1') (tensorIndex t2')---- bit dot product of two tensors-{-# INLINE bitDot #-}-bitDot :: (-    Num a, Bits a-    ) => Tensor a                             -- ^ First dot product argument-      -> Tensor a                             -- ^ Second dot product argument-      -> Tensor a                             -- ^ Resulting dot product---- Two finite tensors product-bitDot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (.&.) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)---- Two simple tensors product-bitDot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = -        let dotProduct v1 v2 =  Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (.&.) v1 v2-        in  Scalar $ dotProduct ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)---- Simple tensor and finite tensor product-bitDot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 =  Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (\e t -> (e .&.) <$> t) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)---- Finite tensor and simple tensor product-bitDot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')-    | count1 == count2 = Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (\t e -> (.&. e) <$> t) ts1' ts2'-    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)---- Simple tensor and infinite tensor product-bitDot (SimpleFinite (Finite.Covariant count1 _) ts1') (InfiniteTensor (Infinite.Contravariant _) ts2') = -    Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (\e t -> (e .&.) <$> t) ts1' (Boxed.fromList $ take count1 ts2')---- Infinite tensor and simple tensor product-bitDot (InfiniteTensor (Infinite.Covariant _) ts1') (SimpleFinite (Finite.Contravariant count2 _) ts2') = -    Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (\t e -> (.&. e) <$> t) (Boxed.fromList $ take count2 ts1') ts2'---- Finite tensor and infinite tensor product-bitDot (FiniteTensor (Finite.Covariant count1 _) ts1') (InfiniteTensor (Infinite.Contravariant _) ts2') = -    Boxed.sum $ Boxed.zipWith (*) ts1' (Boxed.fromList $ take count1 ts2')---- Infinite tensor and finite tensor product-bitDot (InfiniteTensor (Infinite.Covariant _) ts1') (FiniteTensor (Finite.Contravariant count2 _) ts2') = -    Boxed.sum $ Boxed.zipWith (*) (Boxed.fromList $ take count2 ts1') ts2'---- In other cases cannot happen!-bitDot t1' t2' = contractionErr (tensorIndex t1') (tensorIndex t2')---- contraction error-{-# INLINE contractionErr #-}-contractionErr :: Index.TIndex   -- ^ Index of first dot product parameter-               -> Index.TIndex   -- ^ Index of second dot product parameter-               -> Tensor a       -- ^ Erorr message--contractionErr i1' i2' = Err $-    "Tensor product: " ++ incompatibleTypes ++-    " - index1 is " ++ show i1' ++-    " and index2 is " ++ show i2'---- Tensors can be added, subtracted and multiplicated-instance Num a => Num (Tensor a) where--    -- Adding - element by element-    {-# INLINE (+) #-}-    t1 + t2 = _elemByElem t1 t2 (+) $ zipT (+) (.+) (+.) (+)--    -- Subtracting - element by element-    {-# INLINE (-) #-}-    t1 - t2 = _elemByElem t1 t2 (-) $ zipT (-) (.-) (-.) (-)--    -- Multiplicating is treated as tensor product-    -- Tensor product applies Einstein summation convention-    {-# INLINE (*) #-}-    t1 * t2 = _elemByElem t1 t2 (*) dot--    -- Absolute value - element by element-    {-# INLINE abs #-}-    abs t = abs <$> t--    -- Signum operation - element by element-    {-# INLINE signum #-}-    signum t = signum <$> t--    -- Simple integer can be conveted to Scalar-    {-# INLINE fromInteger #-}-    fromInteger x = Scalar $ fromInteger x---- Bit operations on tensors-instance (-    Num a, Bits a-    ) => Bits (Tensor a) where--    -- Bit sum - elem by elem-    {-# INLINE (.|.) #-}-    t1 .|. t2 = _elemByElem t1 t2 (.|.) $ zipT (.|.) (\t e -> (.|. e) <$> t) (\e t -> (e .|.) <$> t) (.|.)--    -- Bit tensor product-    -- Summation and multiplication are replaced by its bit equivalents-    -- Two scalars are multiplicated by their values-    {-# INLINE (.&.) #-}-    t1 .&. t2 = _elemByElem t1 t2 (.&.) bitDot--    -- Bit exclusive sum (XOR) - elem by elem-    {-# INLINE xor #-}-    t1 `xor` t2 = _elemByElem t1 t2 xor $ zipT xor (\t e -> (`xor` e) <$> t) (\e t -> (e `xor`) <$> t) xor--    -- Bit complement-    {-# INLINE complement #-}-    complement = Multilinear.map complement--    -- Bit shift of all elements-    {-# INLINE shift #-}-    shift t n = Multilinear.map (`shift` n) t--    -- Bit rotating of all elements-    {-# INLINE rotate #-}-    rotate t n = Multilinear.map (`rotate` n) t--    -- Returns number of bits of elements of tensor, -1 for elements of undefined size-    {-# INLINE bitSize #-}-    bitSize (Scalar x)          = fromMaybe (-1) $ bitSizeMaybe x-    bitSize (Err _)             = -1-    bitSize t =-        if isEmptyTensor t-        then (-1)-        else fromMaybe (-1) $ bitSizeMaybe $ firstElem t--    -- Returns number of bits of elements of tensor-    {-# INLINE bitSizeMaybe #-}-    bitSizeMaybe (Scalar x)          = bitSizeMaybe x-    bitSizeMaybe (Err _)             = Nothing-    bitSizeMaybe t =-        if isEmptyTensor t-        then Nothing-        else bitSizeMaybe $ firstElem t--    -- Returns true if tensors element are signed-    {-# INLINE isSigned #-}-    isSigned (Scalar x)          = isSigned x-    isSigned (Err _)             = False-    isSigned t =-        not (isEmptyTensor t) &&-        isSigned (firstElem t)--    -- bit i is a scalar value with the ith bit set and all other bits clear.-    {-# INLINE bit #-}-    bit i = Scalar (bit i)--    -- Test bit - shoud retur True, if bit n if equal to 1.-    -- Tensors are entities with many elements, so this function always returns False.-    -- Do not use it, it is implemented only for legacy purposes.-    {-# INLINE testBit #-}-    testBit _ _ = False--    -- Return the number of set bits in the argument. This number is known as the population count or the Hamming weight.-    {-# INLINE popCount #-}-    popCount = popCountDefault---- Tensors can be divided by each other-instance Fractional a => Fractional (Tensor a) where--    {-# INLINE (/) #-}-    -- Scalar division return result of division of its values-    Scalar x1 / Scalar x2 = Scalar $ x1 / x2-    -- Tensor and scalar are divided value by value-    Scalar x1 / t2 = (x1 /) <$> t2-    t1 / Scalar x2 = (/ x2) <$> t1-    Err msg / _ = Err msg-    _ / Err msg = Err msg-    -- Two complex tensors cannot be (for now) simply divided-    -- // TODO - tensor division and inversion-    _ / _ = Err "TODO"--    -- A scalar can be generated from rational number-    {-# INLINE fromRational #-}-    fromRational x = Scalar $ fromRational x---- Real-number functions on tensors.--- Function of tensor is tensor of function of its elements--- E.g. exp [1,2,3,4] = [exp 1, exp2, exp3, exp4]-instance Floating a => Floating (Tensor a) where--    {-| PI number -}-    {-# INLINE pi #-}-    pi = Scalar pi--    {-| Exponential function. (exp t)[i] = exp( t[i] ) -}-    {-# INLINE exp #-}-    exp t = exp <$> t--    {-| Natural logarithm. (log t)[i] = log( t[i] ) -}-    {-# INLINE log #-}-    log t = log <$> t--    {-| Sinus. (sin t)[i] = sin( t[i] ) -}-    {-# INLINE sin #-}-    sin t = sin <$> t--    {-| Cosinus. (cos t)[i] = cos( t[i] ) -}-    {-# INLINE cos #-}-    cos t = cos <$> t--    {-| Inverse sinus. (asin t)[i] = asin( t[i] ) -}-    {-# INLINE asin #-}-    asin t = asin <$> t--    {-| Inverse cosinus. (acos t)[i] = acos( t[i] ) -}-    {-# INLINE acos #-}-    acos t = acos <$> t--    {-| Inverse tangent. (atan t)[i] = atan( t[i] ) -}-    {-# INLINE atan #-}-    atan t = atan <$> t--    {-| Hyperbolic sinus. (sinh t)[i] = sinh( t[i] ) -}-    {-# INLINE sinh #-}-    sinh t = sinh <$> t--    {-| Hyperbolic cosinus. (cosh t)[i] = cosh( t[i] ) -}-    {-# INLINE cosh #-}-    cosh t = cosh <$> t--    {-| Inverse hyperbolic sinus. (asinh t)[i] = asinh( t[i] ) -}-    {-# INLINE asinh #-}-    asinh t = acosh <$> t--    {-| Inverse hyperbolic cosinus. (acosh t)[i] = acosh (t[i] ) -}-    {-# INLINE acosh #-}-    acosh t = acosh <$> t--    {-| Inverse hyperbolic tangent. (atanh t)[i] = atanh( t[i] ) -}-    {-# INLINE atanh #-}-    atanh t = atanh <$> t---- Multilinear operations-instance Num a => Multilinear Tensor a where--    -- Add scalar right-    {-# INLINE (.+) #-}-    t .+ x = (+x) <$> t--    -- Subtract scalar right-    {-# INLINE (.-) #-}-    t .- x = (\p -> p - x) <$> t--    -- Multiplicate by scalar right-    {-# INLINE (.*) #-}-    t .* x = (*x) <$> t--    -- Add scalar left-    {-# INLINE (+.) #-}-    x +. t = (x+) <$> t--    -- Subtract scalar left-    {-# INLINE (-.) #-}-    x -. t = (x-) <$> t--    -- Multiplicate by scalar left-    {-# INLINE (*.) #-}-    x *. t = (x*) <$> t--    -- Two tensors sum-    {-# INLINE (.+.) #-}-    t1 .+. t2 = _elemByElem t1 t2 (+) $ zipT (+) (.+) (+.) (+)--    -- Two tensors difference-    {-# INLINE (.-.) #-}-    t1 .-. t2 = _elemByElem t1 t2 (-) $ zipT (+) (.+) (+.) (+)--    -- Tensor product-    {-# INLINE (.*.) #-}-    t1 .*. t2 = _elemByElem t1 t2 (+) dot--    -- List of all tensor indices-    {-# INLINE indices #-}-    indices x = case x of-        Scalar _            -> []-        FiniteTensor i ts   -> Index.toTIndex i : indices (head $ toList ts)-        InfiniteTensor i ts -> Index.toTIndex i : indices (head ts)-        SimpleFinite i _    -> [Index.toTIndex i]-        Err _               -> []--    -- Get tensor order [ (contravariant,covariant)-type ]-    {-# INLINE order #-}-    order x = case x of-        Scalar _ -> (0,0)-        SimpleFinite index _ -> case index of-            Finite.Contravariant _ _ -> (1,0)-            Finite.Covariant _ _     -> (0,1)-            Finite.Indifferent _ _   -> (0,0)-        Err _ -> (-1,-1)-        _ -> let (cnvr, covr) = order $ firstTensor x-             in case tensorIndex x of-                Index.Contravariant _ _ -> (cnvr+1,covr)-                Index.Covariant _ _     -> (cnvr,covr+1)-                Index.Indifferent _ _   -> (cnvr,covr)--    -- Get size of tensor index or Left if index is infinite or tensor has no such index-    {-# INLINE size #-}-    size t iname = case t of-        Scalar _             -> error scalarIndices-        SimpleFinite index _ -> -            if Index.indexName index == iname -            then Finite.indexSize index -            else error indexNotFound-        FiniteTensor index _ -> -            if Index.indexName index == iname-            then Finite.indexSize index-            else size (firstTensor t) iname-        InfiniteTensor _ _   -> error infiniteIndex-        Err msg              -> error msg--    -- Rename tensor indices-    {-# INLINE ($|) #-}-    -    Scalar x $| _ = Scalar x-    SimpleFinite (Finite.Contravariant isize _) ts $| (u:_, _) = SimpleFinite (Finite.Contravariant isize [u]) ts-    SimpleFinite (Finite.Covariant isize _) ts $| (_, d:_) = SimpleFinite (Finite.Covariant isize [d]) ts-    FiniteTensor (Finite.Contravariant isize _) ts $| (u:us, ds) = FiniteTensor (Finite.Contravariant isize [u]) $ ($| (us,ds)) <$> ts-    FiniteTensor (Finite.Covariant isize _) ts $| (us, d:ds) = FiniteTensor (Finite.Covariant isize [d]) $ ($| (us,ds)) <$> ts-    InfiniteTensor (Infinite.Contravariant _) ts $| (u:us, ds) = InfiniteTensor (Infinite.Contravariant [u]) $ ($| (us,ds)) <$> ts-    InfiniteTensor (Infinite.Covariant _) ts $| (us, d:ds) = InfiniteTensor (Infinite.Covariant [d]) $ ($| (us,ds)) <$> ts-    Err msg $| _ = Err msg-    t $| _ = t--    -- Raise an index-    {-# INLINE (/\) #-}-    Scalar x /\ _ = Scalar x-    FiniteTensor index ts /\ n-        | Index.indexName index == n =-            FiniteTensor (Finite.Contravariant (Finite.indexSize index) n) $ (/\ n) <$> ts-        | otherwise =-            FiniteTensor index $ (/\ n) <$> ts-    InfiniteTensor index ts /\ n-        | Index.indexName index == n =-            InfiniteTensor (Infinite.Contravariant n) $ (/\ n) <$> ts-        | otherwise =-            InfiniteTensor index $ (/\ n) <$> ts-    t1@(SimpleFinite index ts) /\ n-        | Index.indexName index == n =-            SimpleFinite (Finite.Contravariant (Finite.indexSize index) n) ts-        | otherwise = t1-    Err msg /\ _ = Err msg--    -- Lower an index-    {-# INLINE (\/) #-}-    Scalar x \/ _ = Scalar x-    FiniteTensor index ts \/ n-        | Index.indexName index == n =-            FiniteTensor (Finite.Covariant (Finite.indexSize index) n) $ (\/ n) <$> ts-        | otherwise =-            FiniteTensor index $ (\/ n) <$> ts-    InfiniteTensor index ts \/ n-        | Index.indexName index == n =-            InfiniteTensor (Infinite.Covariant n) $ (\/ n) <$> ts-        | otherwise =-            InfiniteTensor index $ (\/ n) <$> ts-    t1@(SimpleFinite index ts) \/ n-        | Index.indexName index == n =-            SimpleFinite (Finite.Covariant (Finite.indexSize index) n) ts-        | otherwise = t1-    Err msg \/ _ = Err msg--    {-| Transpose a tensor (switch all indices types) -}-    {-# INLINE transpose #-}-    transpose (Scalar x) = Scalar x--    transpose (FiniteTensor (Finite.Covariant count name) ts) =-        FiniteTensor (Finite.Contravariant count name) (Multilinear.transpose <$> ts)-    transpose (FiniteTensor (Finite.Contravariant count name) ts) =-        FiniteTensor (Finite.Covariant count name) (Multilinear.transpose <$> ts)-    transpose (FiniteTensor (Finite.Indifferent count name) ts) =-        FiniteTensor (Finite.Indifferent count name) (Multilinear.transpose <$> ts)--    transpose (InfiniteTensor (Infinite.Covariant name) ts) =-        InfiniteTensor (Infinite.Contravariant name) (Multilinear.transpose <$> ts)-    transpose (InfiniteTensor (Infinite.Contravariant name) ts) =-        InfiniteTensor (Infinite.Covariant name) (Multilinear.transpose <$> ts)-    transpose (InfiniteTensor (Infinite.Indifferent name) ts) =-        InfiniteTensor (Infinite.Indifferent name) (Multilinear.transpose <$> ts)--    transpose (SimpleFinite (Finite.Covariant count name) ts) =-        SimpleFinite (Finite.Contravariant count name) ts-    transpose (SimpleFinite (Finite.Contravariant count name) ts) =-        SimpleFinite (Finite.Covariant count name) ts-    transpose (SimpleFinite (Finite.Indifferent count name) ts) =-        SimpleFinite (Finite.Indifferent count name) ts--    transpose (Err msg) = Err msg--    {-| Concatenation of two tensor with given index or by creating a new one -}-    {-# INLINE augment #-}-    augment t1 t2 ind =-        let t1' = t1 <<<| ind-            t2' = t2 <<<| ind-        in  t1' <> t2'--    {-| Shift tensor index right -}-    {-| Moves given index one level deeper in recursion -}-    {-# INLINE shiftRight #-}-    -- Error tensor has no indices to shift-    Err msg `shiftRight` _  = Err msg-    -- Scalar has no indices to shift-    Scalar x `shiftRight` _ = Scalar x-    -- Simple tensor has only one index which cannot be shifted-    t1@(SimpleFinite _ _) `shiftRight` _ = t1-    -- Finite tensor is shifted by converting to list and transposing it-    t1@(FiniteTensor index1 ts1) `shiftRight` ind-        -- We don't shift this index-        | Data.List.length (indicesNames t1) > 1 && Index.indexName index1 /= ind =-            FiniteTensor index1 $ (|>> ind) <$> ts1-        -- We found index to shift-        | Data.List.length (indicesNames t1) > 1 && Index.indexName index1 == ind =-                -- Next index-            let index2 = tensorFiniteIndex (ts1 Boxed.! 0)-                -- Elements to transpose-                dane = if isSimple (ts1 Boxed.! 0)-                       then (Scalar <$>) <$> (tensorScalars <$> ts1)-                       else tensorsFinite <$> ts1-                -- Convert to list-                daneList = Boxed.toList <$> Boxed.toList dane-                -- and transpose tensor data (standard function available only for list)-                transposedList = Data.List.transpose daneList-                -- then reconvert to vector again-                transposed = Boxed.fromList <$> Boxed.fromList transposedList-            -- and reconstruct tensor with transposed elements-            in  mergeScalars $ FiniteTensor index2 $ FiniteTensor index1 <$> transposed-        | otherwise = t1--    -- Infinite tensor is shifted by transposing nested lists-    t1@(InfiniteTensor index1 ts1) `shiftRight` ind-        -- We don't shift this index-        | Data.List.length (indicesNames t1) > 1 && Index.indexName index1 /= ind =-            InfiniteTensor index1 $ (|>> ind) <$> ts1-        -- We found index to shift-        | Data.List.length (indicesNames t1) > 1 && Index.indexName index1 == ind =-                -- Next index-            let index2 = tensorInfiniteIndex (head ts1)-                -- Elements to transpose-                dane = if isSimple (head ts1)-                       then (Scalar <$>) <$> (Boxed.toList . tensorScalars <$> ts1)-                       else tensorsInfinite <$> ts1-                -- transpose tensor data (standard function available only for list)-                transposed = Data.List.transpose dane-            -- and reconstruct tensor with transposed elements-            in  mergeScalars $ InfiniteTensor index2 $ InfiniteTensor index1 <$> transposed-        | otherwise = t1---{-| List allows for random access to tensor elements -}-instance Num a => Accessible Tensor a where--    {-| Accessing tensor elements -}-    {-# INLINE el #-}--    -- Scalar has only one element-    el (Scalar x) _ = Scalar x--    -- simple tensor case-    el t1@(SimpleFinite index1 _) (inds,vals) =-            -- zip indices with their given values-        let indvals = zip inds vals-            -- find value for simple tensor index if given-            val = Data.List.find (\(n,_) -> [n] == Index.indexName index1) indvals-            -- if value for current index is given-        in  if isJust val-            -- then get it from current tensor-            then t1 ! snd (fromJust val)-            -- otherwise return whole tensor - no filtering defined-            else t1--    -- finite tensor case-    el t1@(FiniteTensor index1 v1) (inds,vals) =-            -- zip indices with their given values-        let indvals = zip inds vals-            -- find value for current index if given-            val = Data.List.find (\(n,_) -> [n] == Index.indexName index1) indvals-            -- and remove used index from indices list-            indvals1 = Data.List.filter (\(n,_) -> [n] /= Index.indexName index1) indvals-            -- indices unused so far-            inds1 = Data.List.map fst indvals1-            -- and its corresponding values-            vals1 = Data.List.map snd indvals1-            -- if value for current index was given-        in  if isJust val-            -- then get it from current tensor and recursively process other indices-            then el (t1 ! snd (fromJust val)) (inds1,vals1)-            -- otherwise recursively access elements of all child tensors-            else FiniteTensor index1 $ (\t -> el t (inds,vals)) <$> v1--    -- infinite tensor case-    el t1@(InfiniteTensor index1 v1) (inds,vals) =-            -- zip indices with their given values-        let indvals = zip inds vals-            -- find value for current index if given-            val = Data.List.find (\(n,_) -> [n] == Index.indexName index1) indvals-            -- and remove used index from indices list-            indvals1 = Data.List.filter (\(n,_) -> [n] /= Index.indexName index1) indvals-            -- indices unused so far-            inds1 = Data.List.map fst indvals1-            -- and its corresponding values-            vals1 = Data.List.map snd indvals1-            -- if value for current index was given-        in  if isJust val-            -- then get it from current tensor and recursively process other indices-            then el (t1 ! snd (fromJust val)) (inds1,vals1)-            -- otherwise recursively access elements of all child tensors-            else InfiniteTensor index1 $ (\t -> el  t (inds,vals)) <$> v1--    -- accessing elements of erorr tensor simply pushes this error further-    el (Err msg) _ = Err msg--    {-| Mapping with indices. -}-    {-# INLINE iMap #-}-    iMap f t = iMap' t zeroList-        where-        zeroList = 0:zeroList--        iMap' (Scalar x) inds =-            Scalar $ f inds x-        iMap' (SimpleFinite index ts) inds =-            SimpleFinite index $ Boxed.imap (\i e -> f (inds ++ [i]) e) ts-        iMap' (FiniteTensor index ts) inds =-            FiniteTensor index $ Boxed.imap (\i e -> iMap' e (inds ++ [i])) ts-        iMap' (InfiniteTensor index  ts) inds =-            InfiniteTensor index $ (\tind -> iMap' (fst tind) $ inds ++ [snd tind]) <$> zip ts [0..]-        iMap' (Err msg) _  =-            Err msg+{-|
+Module      : Multilinear.Generic.AsArray
+Description : Generic array tensor
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+- This module contains generic implementation of tensor defined as nested arrays
+
+-}
+
+module Multilinear.Generic (
+    Tensor(..), (!), mergeScalars,
+    isScalar, isSimple, isFiniteTensor, isInfiniteTensor,
+    dot, _elemByElem, contractionErr, tensorIndex, _standardize
+) where
+
+import           Control.DeepSeq
+import           Data.Bits
+import           Data.Foldable
+import           Data.List
+import           Data.Maybe
+import qualified Data.Vector                as Boxed
+import           GHC.Generics
+import           Multilinear.Class          as Multilinear
+import qualified Multilinear.Index          as Index
+import qualified Multilinear.Index.Finite   as Finite
+import qualified Multilinear.Index.Infinite as Infinite
+
+{-| ERROR MESSAGES -}
+incompatibleTypes :: String
+incompatibleTypes = "Incompatible tensor types!"
+
+scalarIndices :: String
+scalarIndices = "Scalar has no indices!"
+
+infiniteIndex :: String
+infiniteIndex = "Index is infinitely-dimensional!"
+
+infiniteTensor :: String
+infiniteTensor = "This tensor is infinitely-dimensional and cannot be printed!"
+
+indexNotFound :: String
+indexNotFound = "This tensor has not such index!"
+
+{-| Tensor defined recursively as scalar or list of other tensors -}
+{-| @c@ is type of a container, @i@ is type of index size and @a@ is type of tensor elements -}
+data Tensor a =
+    {-| Scalar -}
+    Scalar {
+        {-| value of scalar -}
+        scalarVal :: a
+    } |
+    {-| Simple, one-dimensional finite tensor -}
+    SimpleFinite {
+        tensorFiniteIndex :: Finite.Index,
+        tensorScalars     :: Boxed.Vector a
+    } |
+    {-| Finite array of other tensors -}
+    FiniteTensor {
+        {-| Finite index "Mutltilinear.Index.Finite" of tensor -}
+        tensorFiniteIndex :: Finite.Index,
+        {-| Array of tensors on deeper recursion level -}
+        tensorsFinite     :: Boxed.Vector (Tensor a)
+    } |
+    {-| Infinite list of other tensors -}
+    InfiniteTensor {
+        {-| Infinite index "Mutltilinear.Index.Infinite" of tensor -}
+        tensorInfiniteIndex :: Infinite.Index,
+        {-| Infinite list of tensors on deeper recursion level -}
+        tensorsInfinite     :: [Tensor a]
+    } |
+    {-| Operations on tensors may throw an error -}
+    Err {
+        {-| Error message -}
+        errMessage :: String
+    } deriving (Eq, Generic)
+
+{-| Return true if tensor is a scalar -}
+{-# INLINE isScalar #-}
+isScalar :: Tensor a -> Bool
+isScalar x = case x of
+    Scalar _ -> True
+    _        -> False
+
+{-| Return true if tensor is a simple tensor -}
+{-# INLINE isSimple #-}
+isSimple :: Tensor a -> Bool
+isSimple x = case x of
+    SimpleFinite _ _ -> True
+    _                -> False
+
+{-| Return True if tensor is a complex tensor -}
+{-# INLINE isFiniteTensor #-}
+isFiniteTensor :: Tensor a -> Bool
+isFiniteTensor x = case x of
+    FiniteTensor _ _ -> True
+    _                -> False
+
+{-| Return True if tensor is a infinite tensor -}
+{-# INLINE isInfiniteTensor #-}
+isInfiniteTensor :: Tensor a -> Bool
+isInfiniteTensor x = case x of
+    InfiniteTensor _ _ -> True
+    _                  -> False
+
+{- Return True if tensor is a error tensor -}
+{-# INLINE isErrTensor #-}
+isErrTensor :: Tensor a -> Bool
+isErrTensor x = case x of
+    Err _ -> True
+    _     -> False
+
+{-| Return generic tensor index -}
+{-# INLINE tensorIndex #-}
+tensorIndex :: Tensor a -> Index.TIndex
+tensorIndex x = case x of
+    Scalar _           -> error scalarIndices
+    SimpleFinite i _   -> Index.toTIndex i
+    FiniteTensor i _   -> Index.toTIndex i
+    InfiniteTensor i _ -> Index.toTIndex i
+    Err msg            -> error msg
+
+{-| Return True if tensor has no elements -}
+{-# INLINE isEmptyTensor #-}
+isEmptyTensor :: Tensor a -> Bool
+isEmptyTensor x = case x of
+    Scalar _            -> False
+    SimpleFinite _ ts   -> Boxed.null ts
+    FiniteTensor _ ts   -> Boxed.null ts
+    InfiniteTensor _ ts -> null ts
+    Err _               -> False
+
+{-| Returns sample element of the tensor. Used to determine some features common for all elements, like bit-qualities. -}
+{-# INLINE firstElem #-}
+firstElem :: Tensor a -> a
+firstElem x = case x of
+    Scalar val          -> val
+    SimpleFinite _ ts   -> Boxed.head ts
+    FiniteTensor _ ts   -> firstElem $ Boxed.head ts
+    InfiniteTensor _ ts -> firstElem $ head ts
+    Err msg             -> error msg
+
+{-| Returns sample tensor on deeper recursion level.Used to determine some features common for all tensors -}
+{-# INLINE firstTensor #-}
+firstTensor :: Tensor a -> Tensor a
+firstTensor x = case x of
+    FiniteTensor _ ts   -> Boxed.head ts
+    InfiniteTensor _ ts -> Data.List.head ts
+    _                   -> x
+
+{-| Recursive indexing on list tensor
+    @t ! i = t[i]@ -}
+{-# INLINE (!) #-}
+(!) :: Tensor a      -- ^ tensor @t@
+    -> Int           -- ^ index @i@
+    -> Tensor a      -- ^ tensor @t[i]@
+t ! i = case t of
+    Scalar _            -> Err scalarIndices
+    Err msg             -> Err msg
+    SimpleFinite ind ts -> if i >= Finite.indexSize ind then error ("Index + " ++ show ind ++ " out of bonds!") else Scalar $ ts Boxed.! i
+    FiniteTensor ind ts -> if i >= Finite.indexSize ind then error ("Index + " ++ show ind ++ " out of bonds!") else ts Boxed.! i
+    InfiniteTensor _ ts -> ts !! i
+
+-- NFData instance
+instance NFData a => NFData (Tensor a)
+
+-- move contravariant indices to lower recursion level
+_standardize :: Num a => Tensor a -> Tensor a
+_standardize tens = foldr' (\i t -> if Index.isContravariant i then t <<<| Index.indexName i else t) tens $ indices tens
+
+-- Print tensor
+instance (
+    Show a, Num a
+    ) => Show (Tensor a) where
+
+    -- merge errors first and then print whole tensor
+    show = show' . _standardize . _mergeErr
+        where
+        show' x = case x of
+            -- Scalar is showed simply as its value
+            Scalar v -> show v
+            -- SimpleFinite is shown dependent on its index...
+            SimpleFinite index ts -> show index ++ "S: " ++ case index of
+                -- If index is contravariant, show tensor components vertically
+                Finite.Contravariant _ _ -> _showVertical ts
+                -- If index is covariant or indifferent, show tensor compoments horizontally
+                _                        -> _showHorizontal ts
+            -- FiniteTensor is shown dependent on its index...
+            FiniteTensor index ts -> show index ++ "T: " ++ case index of
+                -- If index is contravariant, show tensor components vertically
+                Finite.Contravariant _ _ -> _showVertical ts
+                -- If index is covariant or indifferent, show tensor compoments horizontally
+                _                        -> _showHorizontal ts
+            -- Infinite tensor print erorr message as it cannot be fully shown
+            InfiniteTensor _ _ -> show infiniteTensor
+            -- Error prints its error message
+            Err msg -> show msg
+            
+        -- Merge many errors in tensor to the first one
+        _mergeErr x = case x of
+            -- Error tensor is passed further
+            Err msg -> Err msg
+            -- FiniteTensor is merged to first error on deeper recursion level
+            FiniteTensor _ ts ->
+                -- find first error if present
+                let err = Data.List.find isErrTensor (_mergeErr <$> ts)
+                -- and return this error if found, whole tensor otherwise
+                in fromMaybe x err
+            -- in other types of tensor cannot be any error
+            _ -> x
+
+        -- print container elements vertically
+        -- used to show contravariant components of tensor, which by convention are written vertically
+        _showVertical :: (Show a, Foldable c) => c a -> String
+        _showVertical container =
+            "\n" ++ tail (foldl' (\string e -> string ++ "\n  |" ++ show e) "" container)
+
+        -- print container elements horizontally
+        -- used to show covariant (or indifferent) components of tensor, which by convention are written horizontally
+        _showHorizontal :: (Show a, Foldable c) => c a -> String
+        _showHorizontal container =
+            "[" ++ tail (foldl' (\string e -> string ++ "," ++ show e) "" container) ++ "]"
+
+-- Tensor is a functor
+instance Functor Tensor where
+
+    {-# INLINE fmap #-}
+    fmap f x = case x of
+        -- Mapping scalar simply maps its value
+        Scalar v                -> Scalar $ f v
+        -- Mapping complex tensor does mapping element by element
+        SimpleFinite index ts   -> SimpleFinite index (f <$> ts)
+        FiniteTensor index ts   -> FiniteTensor index $ fmap (fmap f) ts
+        InfiniteTensor index ts -> InfiniteTensor index $ fmap (fmap f) ts
+        -- Mapping errors changes nothing
+        Err msg                 -> Err msg
+
+-- Tensors can be compared lexigographically
+-- Allowes to put tensors in typical ordered containers
+instance (
+    Ord a
+    ) => Ord (Tensor a) where
+
+    {-# INLINE (<=) #-}
+    -- Error is smaller by other tensors, so when printing ordered containers, all erorrs will be printed first
+    -- Two errors are compared by they messages lexigographically
+    Err msg1 <= Err msg2 = msg1 <= msg2
+    Err _ <= _ = True
+    _ <= Err _ = False
+    -- Scalar is smaller than any complex tensor
+    -- Two scalars are compared by they values
+    Scalar x1 <= Scalar x2 = x1 <= x2
+    Scalar _ <= _ = True
+    _ <= Scalar _ = False
+    -- Complex tensors are compared lexigographically
+    SimpleFinite _ ts1 <= SimpleFinite _ ts2     = ts1 <= ts2
+    FiniteTensor _ ts1 <= FiniteTensor _ ts2     = ts1 <= ts2
+    InfiniteTensor _ ts1 <= InfiniteTensor _ ts2 = ts1 <= ts2
+    FiniteTensor _ _ <= SimpleFinite _ _         = False
+    SimpleFinite _ _ <= FiniteTensor _ _         = True
+    InfiniteTensor _ _ <= FiniteTensor _ _       = False
+    FiniteTensor _ _ <= InfiniteTensor _ _       = True
+    InfiniteTensor _ _ <= SimpleFinite _ _       = False
+    SimpleFinite _ _ <= InfiniteTensor _ _       = True
+
+{-| Merge FiniteTensor of Scalars to SimpleFinite tensor for performance improvement -}
+{-# INLINE mergeScalars #-}
+mergeScalars :: Tensor a -> Tensor a
+mergeScalars x = case x of
+    (FiniteTensor index1 ts1) -> case ts1 Boxed.! 0 of
+        Scalar _ -> SimpleFinite index1 (scalarVal <$> ts1)
+        _        -> FiniteTensor index1 $ mergeScalars <$> ts1
+    _ -> x
+
+{-| Apply a tensor operator (here denoted by (+) ) elem by elem, trying to connect as many common indices as possible -}
+{-# INLINE _elemByElem' #-}
+_elemByElem' :: Num a 
+             => Tensor a                            -- ^ First argument of operator
+             -> Tensor a                            -- ^ Second argument of operator
+             -> (a -> a -> a)                       -- ^ Operator on tensor elements if indices are different
+             -> (Tensor a -> Tensor a -> Tensor a)  -- ^ Tensor operator called if indices are the same
+             -> Tensor a                            -- ^ Result tensor
+
+-- @Scalar x + Scalar y = Scalar x + y@
+_elemByElem' (Scalar x1) (Scalar x2) f _ = Scalar $ f x1 x2
+-- @Scalar x + Tensor t[i] = Tensor r[i] | r[i] = x + t[i]@
+_elemByElem' (Scalar x) t f _ = (x `f`) <$> t
+-- @Tensor t[i] + Scalar x = Tensor r[i] | r[i] = t[i] + x@
+_elemByElem' t (Scalar x) f _ = (`f` x) <$> t
+
+-- Two finite tensors case
+_elemByElem' t1@(FiniteTensor index1 v1) t2@(FiniteTensor index2 v2) f op
+    | Index.indexName index1 == Index.indexName index2 = op t1 t2
+    | Index.indexName index1 `Data.List.elem` indicesNames t2 =
+        FiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2
+    | otherwise = FiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1
+
+-- Two infinite tensors case
+_elemByElem' t1@(InfiniteTensor index1 v1) t2@(InfiniteTensor index2 v2) f op
+    | Index.indexName index1 == Index.indexName index2 = op t1 t2
+    | Index.indexName index1 `Data.List.elem` indicesNames t2 =
+        InfiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2
+    | otherwise = InfiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1
+
+-- Two simple tensors case
+_elemByElem' t1@(SimpleFinite index1 v1) t2@(SimpleFinite index2 _) f op
+    | Index.indexName index1 == Index.indexName index2 = op t1 t2
+    | otherwise = FiniteTensor index1 $ (\x -> f x <$> t2) <$> v1
+
+-- Finite and infinite tensor case
+_elemByElem' t1@(FiniteTensor index1 v1) t2@(InfiniteTensor index2 v2) f op
+    | Index.indexName index1 == Index.indexName index2 = op t1 t2
+    | Index.indexName index1 `Data.List.elem` indicesNames t2 =
+        InfiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2
+    | otherwise = FiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1
+
+-- Infinite and finite tensor case
+_elemByElem' t1@(InfiniteTensor index1 v1) t2@(FiniteTensor index2 v2) f op
+    | Index.indexName index1 == Index.indexName index2 = op t1 t2
+    | Index.indexName index1 `Data.List.elem` indicesNames t2 =
+        FiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2
+    | otherwise = InfiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1
+
+-- Simple and finite tensor case
+_elemByElem' t1@(SimpleFinite index1 _) t2@(FiniteTensor index2 v2) f op
+    | Index.indexName index1 == Index.indexName index2 = op t1 t2
+    | otherwise = FiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2
+
+-- Finite and simple tensor case
+_elemByElem' t1@(FiniteTensor index1 v1) t2@(SimpleFinite index2 _) f op
+    | Index.indexName index1 == Index.indexName index2 = op t1 t2
+    | otherwise = FiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1
+
+-- Simple and infinite tensor case
+_elemByElem' t1@(SimpleFinite index1 _) t2@(InfiniteTensor index2 v2) f op
+    | Index.indexName index1 == Index.indexName index2 = op t1 t2
+    | otherwise = InfiniteTensor index2 $ (\x -> _elemByElem' t1 x f op) <$> v2
+
+-- Infinite and simple tensor case
+_elemByElem' t1@(InfiniteTensor index1 v1) t2@(SimpleFinite index2 _) f op
+    | Index.indexName index1 == Index.indexName index2 = op t1 t2
+    | otherwise = InfiniteTensor index1 $ (\x -> _elemByElem' x t2 f op) <$> v1
+
+-- Appying operator to error tensor simply pushes this error further
+_elemByElem' (Err msg) _ _ _ = Err msg
+_elemByElem' _ (Err msg) _ _ = Err msg
+
+{-| Apply a tensor operator elem by elem and merge scalars to simple tensor at the and -}
+{-# INLINE _elemByElem #-}
+_elemByElem :: Num a 
+            => Tensor a                             -- ^ First argument of operator
+            -> Tensor a                             -- ^ Second argument of operator
+            -> (a -> a -> a)                        -- ^ Operator on tensor elements if indices are different
+            -> (Tensor a -> Tensor a -> Tensor a)   -- ^ Tensor operator called if indices are the same
+            -> Tensor a                             -- ^ Result tensor
+_elemByElem t1 t2 f op = 
+    let commonIndices = filter (`Data.List.elem` indicesNames t2) $ indicesNames t1
+        t1' = foldl' (|>>>) t1 commonIndices
+        t2' = foldl' (|>>>) t2 commonIndices
+    in mergeScalars $ _elemByElem' t1' t2' f op
+
+-- Zipping two tensors with a combinator, assuming they have the same indices
+{-# INLINE zipT #-}
+zipT :: Num a
+      => (Tensor a -> Tensor a -> Tensor a)   -- ^ Two tensors combinator
+      -> (Tensor a -> a -> Tensor a)          -- ^ Tensor and scalar combinator
+      -> (a -> Tensor a -> Tensor a)          -- ^ Scalar and tensor combinator
+      -> (a -> a -> a)                        -- ^ Two scalars combinator
+      -> Tensor a                             -- ^ First tensor to zip
+      -> Tensor a                             -- ^ Second tensor to zip
+      -> Tensor a                             -- ^ Result tensor
+
+-- Two simple tensors case
+zipT _ _ _ f (SimpleFinite index1 v1) (SimpleFinite index2 v2) = 
+    if index1 == index2 then SimpleFinite index1 $ Boxed.zipWith f v1 v2 else Err incompatibleTypes
+
+--Two finite tensors case
+zipT f _ _ _ (FiniteTensor index1 v1) (FiniteTensor index2 v2)     = 
+    if index1 == index2 then FiniteTensor index1 $ Boxed.zipWith f v1 v2 else Err incompatibleTypes
+
+-- Two infinte tensors case
+zipT f _ _ _ (InfiniteTensor index1 v1) (InfiniteTensor index2 v2) = 
+    if index1 == index2 then InfiniteTensor index1 $ Data.List.zipWith f v1 v2 else Err incompatibleTypes
+
+-- Infinite and finite tensor case
+zipT f _ _ _ (InfiniteTensor _ v1) (FiniteTensor index2 v2)   = 
+    FiniteTensor index2 $ Boxed.zipWith f (Boxed.fromList $ take (Boxed.length v2) v1) v2
+
+-- Finite and infinite tensor case
+zipT f _ _ _ (FiniteTensor index1 v1) (InfiniteTensor _ v2)   = 
+    FiniteTensor index1 $ Boxed.zipWith f v1 (Boxed.fromList $ take (Boxed.length v1) v2)
+
+-- Finite and simple tensor case
+zipT _ f _ _ (FiniteTensor index1 v1) (SimpleFinite index2 v2)     = 
+    if index1 == index2 then FiniteTensor index1 $ Boxed.zipWith f v1 v2 else Err incompatibleTypes
+
+-- Simple and finite tensor case
+zipT _ _ f _ (SimpleFinite index1 v1) (FiniteTensor index2 v2)     = 
+    if index1 == index2 then FiniteTensor index1 $ Boxed.zipWith f v1 v2 else Err incompatibleTypes
+
+-- Infinite and simple tensor case
+zipT _ f _ _ (InfiniteTensor _ v1) (SimpleFinite index2 v2)     = 
+    FiniteTensor index2 $ Boxed.zipWith f (Boxed.fromList $ take (Boxed.length v2) v1) v2
+
+-- Simple and infinite tensor case
+zipT _ _ f _ (SimpleFinite index1 v1) (InfiniteTensor _ v2)     = 
+    FiniteTensor index1 $ Boxed.zipWith f v1 (Boxed.fromList $ take (Boxed.length v1) v2)
+
+-- Zipping error tensor simply pushes this erorr further
+zipT _ _ _ _ (Err msg) _ = Err msg
+zipT _ _ _ _ _ (Err msg) = Err msg
+
+-- Zipping something with scalar is impossible
+zipT _ _ _ _ _ _ = Err scalarIndices
+
+-- dot product of two tensors
+{-# INLINE dot #-}
+dot :: Num a
+      => Tensor a  -- ^ First dot product argument
+      -> Tensor a  -- ^ Second dot product argument
+      -> Tensor a  -- ^ Resulting dot product
+
+-- Two simple tensors product
+dot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = 
+        Scalar $ Boxed.sum $ Boxed.zipWith (*) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+dot (SimpleFinite i1@(Finite.Contravariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = 
+        SimpleFinite i1 $ Boxed.zipWith (*) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+dot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Covariant count2 _) ts2')
+    | count1 == count2 = 
+        SimpleFinite i1 $ Boxed.zipWith (*) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+
+-- Two finite tensors product
+dot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = Boxed.sum $ Boxed.zipWith (*) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+dot (FiniteTensor i1@(Finite.Contravariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (*) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+dot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Covariant count2 _) ts2')
+    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (*) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+
+
+-- Simple tensor and finite tensor product
+dot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = Boxed.sum $ Boxed.zipWith (*.) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+dot (SimpleFinite i1@(Finite.Contravariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (*.) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+dot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Covariant count2 _) ts2')
+    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (*.) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+
+-- Finite tensor and simple tensor product
+dot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = Boxed.sum $ Boxed.zipWith (.*) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+dot (FiniteTensor i1@(Finite.Contravariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (.*) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+dot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Covariant count2 _) ts2')
+    | count1 == count2 = FiniteTensor i1 $ Boxed.zipWith (.*) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+
+-- Simple tensor and infinite tensor product
+dot (SimpleFinite (Finite.Covariant count1 _) ts1') (InfiniteTensor (Infinite.Contravariant _) ts2') = 
+    Boxed.sum $ Boxed.zipWith (*.) ts1' (Boxed.fromList $ take count1 ts2')
+dot (SimpleFinite (Finite.Contravariant count1 _) ts1') (InfiniteTensor i2@(Infinite.Contravariant _) ts2') = 
+    InfiniteTensor i2 $ Boxed.toList $ Boxed.zipWith (*.) ts1' (Boxed.fromList $ take count1 ts2')
+dot (SimpleFinite (Finite.Covariant count1 _) ts1') (InfiniteTensor i2@(Infinite.Covariant _) ts2') = 
+    InfiniteTensor i2 $ Boxed.toList $ Boxed.zipWith (*.) ts1' (Boxed.fromList $ take count1 ts2')
+
+-- Infinite tensor and simple tensor product
+dot (InfiniteTensor (Infinite.Covariant _) ts1') (SimpleFinite (Finite.Contravariant count2 _) ts2') = 
+    Boxed.sum $ Boxed.zipWith (.*) (Boxed.fromList $ take count2 ts1') ts2'
+dot (InfiniteTensor i1@(Infinite.Contravariant _) ts1') (SimpleFinite (Finite.Contravariant count2 _) ts2') = 
+    InfiniteTensor i1 $ Boxed.toList $ Boxed.zipWith (.*) (Boxed.fromList $ take count2 ts1') ts2'
+dot (InfiniteTensor i1@(Infinite.Covariant _) ts1') (SimpleFinite (Finite.Covariant count2 _) ts2') = 
+    InfiniteTensor i1 $ Boxed.toList $ Boxed.zipWith (.*) (Boxed.fromList $ take count2 ts1') ts2'
+
+-- Finite tensor and infinite tensor product
+dot (FiniteTensor (Finite.Covariant count1 _) ts1') (InfiniteTensor (Infinite.Contravariant _) ts2') = 
+    Boxed.sum $ Boxed.zipWith (*) ts1' (Boxed.fromList $ take count1 ts2')
+dot (FiniteTensor (Finite.Contravariant count1 _) ts1') (InfiniteTensor i2@(Infinite.Contravariant _) ts2') = 
+    InfiniteTensor i2 $ Boxed.toList $ Boxed.zipWith (*) ts1' (Boxed.fromList $ take count1 ts2')
+dot (FiniteTensor (Finite.Covariant count1 _) ts1') (InfiniteTensor i2@(Infinite.Covariant _) ts2') = 
+    InfiniteTensor i2 $ Boxed.toList $ Boxed.zipWith (*) ts1' (Boxed.fromList $ take count1 ts2')
+
+-- Infinite tensor and finite tensor product
+dot (InfiniteTensor (Infinite.Covariant _) ts1') (FiniteTensor (Finite.Contravariant count2 _) ts2') = 
+    Boxed.sum $ Boxed.zipWith (*) (Boxed.fromList $ take count2 ts1') ts2'
+dot (InfiniteTensor i1@(Infinite.Contravariant _) ts1') (FiniteTensor (Finite.Contravariant count2 _) ts2') = 
+    InfiniteTensor i1 $ Boxed.toList $ Boxed.zipWith (*) (Boxed.fromList $ take count2 ts1') ts2'
+dot (InfiniteTensor i1@(Infinite.Covariant _) ts1') (FiniteTensor (Finite.Covariant count2 _) ts2') = 
+    InfiniteTensor i1 $ Boxed.toList $ Boxed.zipWith (*) (Boxed.fromList $ take count2 ts1') ts2'
+
+-- In other cases cannot happen!
+dot t1' t2' = contractionErr (tensorIndex t1') (tensorIndex t2')
+
+-- bit dot product of two tensors
+{-# INLINE bitDot #-}
+bitDot :: (
+    Num a, Bits a
+    ) => Tensor a                             -- ^ First dot product argument
+      -> Tensor a                             -- ^ Second dot product argument
+      -> Tensor a                             -- ^ Resulting dot product
+
+-- Two finite tensors product
+bitDot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (.&.) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+
+-- Two simple tensors product
+bitDot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = 
+        let dotProduct v1 v2 =  Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (.&.) v1 v2
+        in  Scalar $ dotProduct ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+
+-- Simple tensor and finite tensor product
+bitDot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 =  Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (\e t -> (e .&.) <$> t) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+
+-- Finite tensor and simple tensor product
+bitDot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')
+    | count1 == count2 = Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (\t e -> (.&. e) <$> t) ts1' ts2'
+    | otherwise = contractionErr (Index.toTIndex i1) (Index.toTIndex i2)
+
+-- Simple tensor and infinite tensor product
+bitDot (SimpleFinite (Finite.Covariant count1 _) ts1') (InfiniteTensor (Infinite.Contravariant _) ts2') = 
+    Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (\e t -> (e .&.) <$> t) ts1' (Boxed.fromList $ take count1 ts2')
+
+-- Infinite tensor and simple tensor product
+bitDot (InfiniteTensor (Infinite.Covariant _) ts1') (SimpleFinite (Finite.Contravariant count2 _) ts2') = 
+    Data.Foldable.foldl' (.|.) 0 $ Boxed.zipWith (\t e -> (.&. e) <$> t) (Boxed.fromList $ take count2 ts1') ts2'
+
+-- Finite tensor and infinite tensor product
+bitDot (FiniteTensor (Finite.Covariant count1 _) ts1') (InfiniteTensor (Infinite.Contravariant _) ts2') = 
+    Boxed.sum $ Boxed.zipWith (*) ts1' (Boxed.fromList $ take count1 ts2')
+
+-- Infinite tensor and finite tensor product
+bitDot (InfiniteTensor (Infinite.Covariant _) ts1') (FiniteTensor (Finite.Contravariant count2 _) ts2') = 
+    Boxed.sum $ Boxed.zipWith (*) (Boxed.fromList $ take count2 ts1') ts2'
+
+-- In other cases cannot happen!
+bitDot t1' t2' = contractionErr (tensorIndex t1') (tensorIndex t2')
+
+-- contraction error
+{-# INLINE contractionErr #-}
+contractionErr :: Index.TIndex   -- ^ Index of first dot product parameter
+               -> Index.TIndex   -- ^ Index of second dot product parameter
+               -> Tensor a       -- ^ Erorr message
+
+contractionErr i1' i2' = Err $
+    "Tensor product: " ++ incompatibleTypes ++
+    " - index1 is " ++ show i1' ++
+    " and index2 is " ++ show i2'
+
+-- Tensors can be added, subtracted and multiplicated
+instance Num a => Num (Tensor a) where
+
+    -- Adding - element by element
+    {-# INLINE (+) #-}
+    t1 + t2 = _elemByElem t1 t2 (+) $ zipT (+) (.+) (+.) (+)
+
+    -- Subtracting - element by element
+    {-# INLINE (-) #-}
+    t1 - t2 = _elemByElem t1 t2 (-) $ zipT (-) (.-) (-.) (-)
+
+    -- Multiplicating is treated as tensor product
+    -- Tensor product applies Einstein summation convention
+    {-# INLINE (*) #-}
+    t1 * t2 = _elemByElem t1 t2 (*) dot
+
+    -- Absolute value - element by element
+    {-# INLINE abs #-}
+    abs t = abs <$> t
+
+    -- Signum operation - element by element
+    {-# INLINE signum #-}
+    signum t = signum <$> t
+
+    -- Simple integer can be conveted to Scalar
+    {-# INLINE fromInteger #-}
+    fromInteger x = Scalar $ fromInteger x
+
+-- Bit operations on tensors
+instance (
+    Num a, Bits a
+    ) => Bits (Tensor a) where
+
+    -- Bit sum - elem by elem
+    {-# INLINE (.|.) #-}
+    t1 .|. t2 = _elemByElem t1 t2 (.|.) $ zipT (.|.) (\t e -> (.|. e) <$> t) (\e t -> (e .|.) <$> t) (.|.)
+
+    -- Bit tensor product
+    -- Summation and multiplication are replaced by its bit equivalents
+    -- Two scalars are multiplicated by their values
+    {-# INLINE (.&.) #-}
+    t1 .&. t2 = _elemByElem t1 t2 (.&.) bitDot
+
+    -- Bit exclusive sum (XOR) - elem by elem
+    {-# INLINE xor #-}
+    t1 `xor` t2 = _elemByElem t1 t2 xor $ zipT xor (\t e -> (`xor` e) <$> t) (\e t -> (e `xor`) <$> t) xor
+
+    -- Bit complement
+    {-# INLINE complement #-}
+    complement = Multilinear.map complement
+
+    -- Bit shift of all elements
+    {-# INLINE shift #-}
+    shift t n = Multilinear.map (`shift` n) t
+
+    -- Bit rotating of all elements
+    {-# INLINE rotate #-}
+    rotate t n = Multilinear.map (`rotate` n) t
+
+    -- Returns number of bits of elements of tensor, -1 for elements of undefined size
+    {-# INLINE bitSize #-}
+    bitSize (Scalar x)          = fromMaybe (-1) $ bitSizeMaybe x
+    bitSize (Err _)             = -1
+    bitSize t =
+        if isEmptyTensor t
+        then (-1)
+        else fromMaybe (-1) $ bitSizeMaybe $ firstElem t
+
+    -- Returns number of bits of elements of tensor
+    {-# INLINE bitSizeMaybe #-}
+    bitSizeMaybe (Scalar x)          = bitSizeMaybe x
+    bitSizeMaybe (Err _)             = Nothing
+    bitSizeMaybe t =
+        if isEmptyTensor t
+        then Nothing
+        else bitSizeMaybe $ firstElem t
+
+    -- Returns true if tensors element are signed
+    {-# INLINE isSigned #-}
+    isSigned (Scalar x)          = isSigned x
+    isSigned (Err _)             = False
+    isSigned t =
+        not (isEmptyTensor t) &&
+        isSigned (firstElem t)
+
+    -- bit i is a scalar value with the ith bit set and all other bits clear.
+    {-# INLINE bit #-}
+    bit i = Scalar (bit i)
+
+    -- Test bit - shoud retur True, if bit n if equal to 1.
+    -- Tensors are entities with many elements, so this function always returns False.
+    -- Do not use it, it is implemented only for legacy purposes.
+    {-# INLINE testBit #-}
+    testBit _ _ = False
+
+    -- Return the number of set bits in the argument. This number is known as the population count or the Hamming weight.
+    {-# INLINE popCount #-}
+    popCount = popCountDefault
+
+-- Tensors can be divided by each other
+instance Fractional a => Fractional (Tensor a) where
+
+    {-# INLINE (/) #-}
+    -- Scalar division return result of division of its values
+    Scalar x1 / Scalar x2 = Scalar $ x1 / x2
+    -- Tensor and scalar are divided value by value
+    Scalar x1 / t2 = (x1 /) <$> t2
+    t1 / Scalar x2 = (/ x2) <$> t1
+    Err msg / _ = Err msg
+    _ / Err msg = Err msg
+    -- Two complex tensors cannot be (for now) simply divided
+    -- // TODO - tensor division and inversion
+    _ / _ = Err "TODO"
+
+    -- A scalar can be generated from rational number
+    {-# INLINE fromRational #-}
+    fromRational x = Scalar $ fromRational x
+
+-- Real-number functions on tensors.
+-- Function of tensor is tensor of function of its elements
+-- E.g. exp [1,2,3,4] = [exp 1, exp2, exp3, exp4]
+instance Floating a => Floating (Tensor a) where
+
+    {-| PI number -}
+    {-# INLINE pi #-}
+    pi = Scalar pi
+
+    {-| Exponential function. (exp t)[i] = exp( t[i] ) -}
+    {-# INLINE exp #-}
+    exp t = exp <$> t
+
+    {-| Natural logarithm. (log t)[i] = log( t[i] ) -}
+    {-# INLINE log #-}
+    log t = log <$> t
+
+    {-| Sinus. (sin t)[i] = sin( t[i] ) -}
+    {-# INLINE sin #-}
+    sin t = sin <$> t
+
+    {-| Cosinus. (cos t)[i] = cos( t[i] ) -}
+    {-# INLINE cos #-}
+    cos t = cos <$> t
+
+    {-| Inverse sinus. (asin t)[i] = asin( t[i] ) -}
+    {-# INLINE asin #-}
+    asin t = asin <$> t
+
+    {-| Inverse cosinus. (acos t)[i] = acos( t[i] ) -}
+    {-# INLINE acos #-}
+    acos t = acos <$> t
+
+    {-| Inverse tangent. (atan t)[i] = atan( t[i] ) -}
+    {-# INLINE atan #-}
+    atan t = atan <$> t
+
+    {-| Hyperbolic sinus. (sinh t)[i] = sinh( t[i] ) -}
+    {-# INLINE sinh #-}
+    sinh t = sinh <$> t
+
+    {-| Hyperbolic cosinus. (cosh t)[i] = cosh( t[i] ) -}
+    {-# INLINE cosh #-}
+    cosh t = cosh <$> t
+
+    {-| Inverse hyperbolic sinus. (asinh t)[i] = asinh( t[i] ) -}
+    {-# INLINE asinh #-}
+    asinh t = acosh <$> t
+
+    {-| Inverse hyperbolic cosinus. (acosh t)[i] = acosh (t[i] ) -}
+    {-# INLINE acosh #-}
+    acosh t = acosh <$> t
+
+    {-| Inverse hyperbolic tangent. (atanh t)[i] = atanh( t[i] ) -}
+    {-# INLINE atanh #-}
+    atanh t = atanh <$> t
+
+-- Multilinear operations
+instance Num a => Multilinear Tensor a where
+
+    -- Add scalar right
+    {-# INLINE (.+) #-}
+    t .+ x = (+x) <$> t
+
+    -- Subtract scalar right
+    {-# INLINE (.-) #-}
+    t .- x = (\p -> p - x) <$> t
+
+    -- Multiplicate by scalar right
+    {-# INLINE (.*) #-}
+    t .* x = (*x) <$> t
+
+    -- Add scalar left
+    {-# INLINE (+.) #-}
+    x +. t = (x+) <$> t
+
+    -- Subtract scalar left
+    {-# INLINE (-.) #-}
+    x -. t = (x-) <$> t
+
+    -- Multiplicate by scalar left
+    {-# INLINE (*.) #-}
+    x *. t = (x*) <$> t
+
+    -- Two tensors sum
+    {-# INLINE (.+.) #-}
+    t1 .+. t2 = _elemByElem t1 t2 (+) $ zipT (+) (.+) (+.) (+)
+
+    -- Two tensors difference
+    {-# INLINE (.-.) #-}
+    t1 .-. t2 = _elemByElem t1 t2 (-) $ zipT (+) (.+) (+.) (+)
+
+    -- Tensor product
+    {-# INLINE (.*.) #-}
+    t1 .*. t2 = _elemByElem t1 t2 (+) dot
+
+    -- List of all tensor indices
+    {-# INLINE indices #-}
+    indices x = case x of
+        Scalar _            -> []
+        FiniteTensor i ts   -> Index.toTIndex i : indices (head $ toList ts)
+        InfiniteTensor i ts -> Index.toTIndex i : indices (head ts)
+        SimpleFinite i _    -> [Index.toTIndex i]
+        Err _               -> []
+
+    -- Get tensor order [ (contravariant,covariant)-type ]
+    {-# INLINE order #-}
+    order x = case x of
+        Scalar _ -> (0,0)
+        SimpleFinite index _ -> case index of
+            Finite.Contravariant _ _ -> (1,0)
+            Finite.Covariant _ _     -> (0,1)
+            Finite.Indifferent _ _   -> (0,0)
+        Err _ -> (-1,-1)
+        _ -> let (cnvr, covr) = order $ firstTensor x
+             in case tensorIndex x of
+                Index.Contravariant _ _ -> (cnvr+1,covr)
+                Index.Covariant _ _     -> (cnvr,covr+1)
+                Index.Indifferent _ _   -> (cnvr,covr)
+
+    -- Get size of tensor index or Left if index is infinite or tensor has no such index
+    {-# INLINE size #-}
+    size t iname = case t of
+        Scalar _             -> error scalarIndices
+        SimpleFinite index _ -> 
+            if Index.indexName index == iname 
+            then Finite.indexSize index 
+            else error indexNotFound
+        FiniteTensor index _ -> 
+            if Index.indexName index == iname
+            then Finite.indexSize index
+            else size (firstTensor t) iname
+        InfiniteTensor _ _   -> error infiniteIndex
+        Err msg              -> error msg
+
+    -- Rename tensor indices
+    {-# INLINE ($|) #-}
+    
+    Scalar x $| _ = Scalar x
+    SimpleFinite (Finite.Contravariant isize _) ts $| (u:_, _) = SimpleFinite (Finite.Contravariant isize [u]) ts
+    SimpleFinite (Finite.Covariant isize _) ts $| (_, d:_) = SimpleFinite (Finite.Covariant isize [d]) ts
+    FiniteTensor (Finite.Contravariant isize _) ts $| (u:us, ds) = FiniteTensor (Finite.Contravariant isize [u]) $ ($| (us,ds)) <$> ts
+    FiniteTensor (Finite.Covariant isize _) ts $| (us, d:ds) = FiniteTensor (Finite.Covariant isize [d]) $ ($| (us,ds)) <$> ts
+    InfiniteTensor (Infinite.Contravariant _) ts $| (u:us, ds) = InfiniteTensor (Infinite.Contravariant [u]) $ ($| (us,ds)) <$> ts
+    InfiniteTensor (Infinite.Covariant _) ts $| (us, d:ds) = InfiniteTensor (Infinite.Covariant [d]) $ ($| (us,ds)) <$> ts
+    Err msg $| _ = Err msg
+    t $| _ = t
+
+    -- Raise an index
+    {-# INLINE (/\) #-}
+    Scalar x /\ _ = Scalar x
+    FiniteTensor index ts /\ n
+        | Index.indexName index == n =
+            FiniteTensor (Finite.Contravariant (Finite.indexSize index) n) $ (/\ n) <$> ts
+        | otherwise =
+            FiniteTensor index $ (/\ n) <$> ts
+    InfiniteTensor index ts /\ n
+        | Index.indexName index == n =
+            InfiniteTensor (Infinite.Contravariant n) $ (/\ n) <$> ts
+        | otherwise =
+            InfiniteTensor index $ (/\ n) <$> ts
+    t1@(SimpleFinite index ts) /\ n
+        | Index.indexName index == n =
+            SimpleFinite (Finite.Contravariant (Finite.indexSize index) n) ts
+        | otherwise = t1
+    Err msg /\ _ = Err msg
+
+    -- Lower an index
+    {-# INLINE (\/) #-}
+    Scalar x \/ _ = Scalar x
+    FiniteTensor index ts \/ n
+        | Index.indexName index == n =
+            FiniteTensor (Finite.Covariant (Finite.indexSize index) n) $ (\/ n) <$> ts
+        | otherwise =
+            FiniteTensor index $ (\/ n) <$> ts
+    InfiniteTensor index ts \/ n
+        | Index.indexName index == n =
+            InfiniteTensor (Infinite.Covariant n) $ (\/ n) <$> ts
+        | otherwise =
+            InfiniteTensor index $ (\/ n) <$> ts
+    t1@(SimpleFinite index ts) \/ n
+        | Index.indexName index == n =
+            SimpleFinite (Finite.Covariant (Finite.indexSize index) n) ts
+        | otherwise = t1
+    Err msg \/ _ = Err msg
+
+    {-| Transpose a tensor (switch all indices types) -}
+    {-# INLINE transpose #-}
+    transpose (Scalar x) = Scalar x
+
+    transpose (FiniteTensor (Finite.Covariant count name) ts) =
+        FiniteTensor (Finite.Contravariant count name) (Multilinear.transpose <$> ts)
+    transpose (FiniteTensor (Finite.Contravariant count name) ts) =
+        FiniteTensor (Finite.Covariant count name) (Multilinear.transpose <$> ts)
+    transpose (FiniteTensor (Finite.Indifferent count name) ts) =
+        FiniteTensor (Finite.Indifferent count name) (Multilinear.transpose <$> ts)
+
+    transpose (InfiniteTensor (Infinite.Covariant name) ts) =
+        InfiniteTensor (Infinite.Contravariant name) (Multilinear.transpose <$> ts)
+    transpose (InfiniteTensor (Infinite.Contravariant name) ts) =
+        InfiniteTensor (Infinite.Covariant name) (Multilinear.transpose <$> ts)
+    transpose (InfiniteTensor (Infinite.Indifferent name) ts) =
+        InfiniteTensor (Infinite.Indifferent name) (Multilinear.transpose <$> ts)
+
+    transpose (SimpleFinite (Finite.Covariant count name) ts) =
+        SimpleFinite (Finite.Contravariant count name) ts
+    transpose (SimpleFinite (Finite.Contravariant count name) ts) =
+        SimpleFinite (Finite.Covariant count name) ts
+    transpose (SimpleFinite (Finite.Indifferent count name) ts) =
+        SimpleFinite (Finite.Indifferent count name) ts
+
+    transpose (Err msg) = Err msg
+
+    {-| Shift tensor index right -}
+    {-| Moves given index one level deeper in recursion -}
+    {-# INLINE shiftRight #-}
+    -- Error tensor has no indices to shift
+    Err msg `shiftRight` _  = Err msg
+    -- Scalar has no indices to shift
+    Scalar x `shiftRight` _ = Scalar x
+    -- Simple tensor has only one index which cannot be shifted
+    t1@(SimpleFinite _ _) `shiftRight` _ = t1
+    -- Finite tensor is shifted by converting to list and transposing it
+    t1@(FiniteTensor index1 ts1) `shiftRight` ind
+        -- We don't shift this index
+        | Data.List.length (indicesNames t1) > 1 && Index.indexName index1 /= ind =
+            FiniteTensor index1 $ (|>> ind) <$> ts1
+        -- We found index to shift
+        | Data.List.length (indicesNames t1) > 1 && Index.indexName index1 == ind =
+                -- Next index
+            let index2 = tensorFiniteIndex (ts1 Boxed.! 0)
+                -- Elements to transpose
+                dane = if isSimple (ts1 Boxed.! 0)
+                       then (Scalar <$>) <$> (tensorScalars <$> ts1)
+                       else tensorsFinite <$> ts1
+                -- Convert to list
+                daneList = Boxed.toList <$> Boxed.toList dane
+                -- and transpose tensor data (standard function available only for list)
+                transposedList = Data.List.transpose daneList
+                -- then reconvert to vector again
+                transposed = Boxed.fromList <$> Boxed.fromList transposedList
+            -- and reconstruct tensor with transposed elements
+            in  mergeScalars $ FiniteTensor index2 $ FiniteTensor index1 <$> transposed
+        | otherwise = t1
+
+    -- Infinite tensor is shifted by transposing nested lists
+    t1@(InfiniteTensor index1 ts1) `shiftRight` ind
+        -- We don't shift this index
+        | Data.List.length (indicesNames t1) > 1 && Index.indexName index1 /= ind =
+            InfiniteTensor index1 $ (|>> ind) <$> ts1
+        -- We found index to shift
+        | Data.List.length (indicesNames t1) > 1 && Index.indexName index1 == ind =
+                -- Next index
+            let index2 = tensorInfiniteIndex (head ts1)
+                -- Elements to transpose
+                dane = if isSimple (head ts1)
+                       then (Scalar <$>) <$> (Boxed.toList . tensorScalars <$> ts1)
+                       else tensorsInfinite <$> ts1
+                -- transpose tensor data (standard function available only for list)
+                transposed = Data.List.transpose dane
+            -- and reconstruct tensor with transposed elements
+            in  mergeScalars $ InfiniteTensor index2 $ InfiniteTensor index1 <$> transposed
+        | otherwise = t1
+
+
+{-| List allows for random access to tensor elements -}
+instance Num a => Accessible Tensor a where
+
+    {-| Accessing tensor elements -}
+    {-# INLINE el #-}
+
+    -- Scalar has only one element
+    el (Scalar x) _ = Scalar x
+
+    -- simple tensor case
+    el t1@(SimpleFinite index1 _) (inds,vals) =
+            -- zip indices with their given values
+        let indvals = zip inds vals
+            -- find value for simple tensor index if given
+            val = Data.List.find (\(n,_) -> [n] == Index.indexName index1) indvals
+            -- if value for current index is given
+        in  if isJust val
+            -- then get it from current tensor
+            then t1 ! snd (fromJust val)
+            -- otherwise return whole tensor - no filtering defined
+            else t1
+
+    -- finite tensor case
+    el t1@(FiniteTensor index1 v1) (inds,vals) =
+            -- zip indices with their given values
+        let indvals = zip inds vals
+            -- find value for current index if given
+            val = Data.List.find (\(n,_) -> [n] == Index.indexName index1) indvals
+            -- and remove used index from indices list
+            indvals1 = Data.List.filter (\(n,_) -> [n] /= Index.indexName index1) indvals
+            -- indices unused so far
+            inds1 = Data.List.map fst indvals1
+            -- and its corresponding values
+            vals1 = Data.List.map snd indvals1
+            -- if value for current index was given
+        in  if isJust val
+            -- then get it from current tensor and recursively process other indices
+            then el (t1 ! snd (fromJust val)) (inds1,vals1)
+            -- otherwise recursively access elements of all child tensors
+            else FiniteTensor index1 $ (\t -> el t (inds,vals)) <$> v1
+
+    -- infinite tensor case
+    el t1@(InfiniteTensor index1 v1) (inds,vals) =
+            -- zip indices with their given values
+        let indvals = zip inds vals
+            -- find value for current index if given
+            val = Data.List.find (\(n,_) -> [n] == Index.indexName index1) indvals
+            -- and remove used index from indices list
+            indvals1 = Data.List.filter (\(n,_) -> [n] /= Index.indexName index1) indvals
+            -- indices unused so far
+            inds1 = Data.List.map fst indvals1
+            -- and its corresponding values
+            vals1 = Data.List.map snd indvals1
+            -- if value for current index was given
+        in  if isJust val
+            -- then get it from current tensor and recursively process other indices
+            then el (t1 ! snd (fromJust val)) (inds1,vals1)
+            -- otherwise recursively access elements of all child tensors
+            else InfiniteTensor index1 $ (\t -> el  t (inds,vals)) <$> v1
+
+    -- accessing elements of erorr tensor simply pushes this error further
+    el (Err msg) _ = Err msg
+
+    {-| Mapping with indices. -}
+    {-# INLINE iMap #-}
+    iMap f t = iMap' t zeroList
+        where
+        zeroList = 0:zeroList
+
+        iMap' (Scalar x) inds =
+            Scalar $ f inds x
+        iMap' (SimpleFinite index ts) inds =
+            SimpleFinite index $ Boxed.imap (\i e -> f (inds ++ [i]) e) ts
+        iMap' (FiniteTensor index ts) inds =
+            FiniteTensor index $ Boxed.imap (\i e -> iMap' e (inds ++ [i])) ts
+        iMap' (InfiniteTensor index  ts) inds =
+            InfiniteTensor index $ (\tind -> iMap' (fst tind) $ inds ++ [snd tind]) <$> zip ts [0..]
+        iMap' (Err msg) _  =
+            Err msg
src/Multilinear/Index.hs view
@@ -1,105 +1,105 @@-{-|-Module      : Index-Description : Implements tensor index.-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--Generic tensor index which may be finitely- or infinitely-dimensional. ---}--module Multilinear.Index (-    Index(..),-    TIndex(..)-) where--{-| Tensor index class which may be lower (covariant), upper (contravariant) or indifferent. -}-class Index i where--    {-| Index name -}-    indexName :: i -> String--    {-| Returns True if index is lower (covariant), False otherwise. -}-    isCovariant :: i -> Bool--    {-| Returns True if index is upper (contravariant), False otherwise. -}-    isContravariant :: i -> Bool--    {-| Returns True if index if indifferent, False otherwise. -}-    isIndifferent :: i -> Bool--    {-| Returns True if two indices are equivalent, thus differs only by name, but share same size and type. -}-    equivI :: i -> i -> Bool--    {-| Infix equivalent for 'equiv'. Has low priority equal to 2. -}-    infixl 2 !=!-    (!=!) :: i -> i -> Bool-    i1 !=! i2 = equivI i1 i2--    {-| Convert to generic index type -}-    toTIndex :: i -> TIndex--{-| Generic index type finitely- or infinitely-dimensional -}-data TIndex =-    Covariant {-        indexSize  :: Maybe Int,-        tIndexName :: String-    } |-    Contravariant {-        indexSize  :: Maybe Int,-        tIndexName :: String-    } |-    Indifferent {-        indexSize  :: Maybe Int,-        tIndexName :: String-    }-    deriving Eq--{-| Show tensor index -}-instance Show TIndex where-    show (Covariant c n)     = "[" ++ n ++ ":" ++ show c ++ "]"-    show (Contravariant c n) = "<" ++ n ++ ":" ++ show c ++ ">"-    show (Indifferent c n)   = "(" ++ n ++ ":" ++ show c ++ ")"--{-| Finite index is a Multilinear.Index instance -}-instance Index TIndex where--    {-| Index name -}-    indexName = tIndexName--    {-| Return true if index is covariant |-}-    isCovariant (Covariant _ _) = True-    isCovariant _               = False--    {-| Return true if index is contravariant |-}-    isContravariant (Contravariant _ _) = True-    isContravariant _                   = False--    {-| Return true if index is indifferent |-}-    isIndifferent (Indifferent _ _) = True-    isIndifferent _                 = False--    {-| Returns true if two indices are quivalent, i.e. differs only by name, but share same type and size. -}-    equivI (Covariant count1 _) (Covariant count2 _)-        | count1 == count2 = True-        | otherwise = False-    equivI (Contravariant count1 _) (Contravariant count2 _)-        | count1 == count2 = True-        | otherwise = False-    equivI (Indifferent count1 _) (Indifferent count2 _)-        | count1 == count2 = True-        | otherwise = False-    equivI _ _ = False--    {-| TIndex must not be converted to TIndex -}-    toTIndex = id--{-| Indices can be compared by its size |-}-{-| Used to allow to put tensors to typical ordered containers |-}-instance Ord TIndex where-    ind1 <= ind2 = indexSize ind1 <= indexSize ind2--+{-|
+Module      : Index
+Description : Implements tensor index.
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+Generic tensor index which may be finitely- or infinitely-dimensional. 
+
+-}
+
+module Multilinear.Index (
+    Index(..),
+    TIndex(..)
+) where
+
+{-| Tensor index class which may be lower (covariant), upper (contravariant) or indifferent. -}
+class Index i where
+
+    {-| Index name -}
+    indexName :: i -> String
+
+    {-| Returns True if index is lower (covariant), False otherwise. -}
+    isCovariant :: i -> Bool
+
+    {-| Returns True if index is upper (contravariant), False otherwise. -}
+    isContravariant :: i -> Bool
+
+    {-| Returns True if index if indifferent, False otherwise. -}
+    isIndifferent :: i -> Bool
+
+    {-| Returns True if two indices are equivalent, thus differs only by name, but share same size and type. -}
+    equivI :: i -> i -> Bool
+
+    {-| Infix equivalent for 'equiv'. Has low priority equal to 2. -}
+    infixl 2 !=!
+    (!=!) :: i -> i -> Bool
+    i1 !=! i2 = equivI i1 i2
+
+    {-| Convert to generic index type -}
+    toTIndex :: i -> TIndex
+
+{-| Generic index type finitely- or infinitely-dimensional -}
+data TIndex =
+    Covariant {
+        indexSize  :: Maybe Int,
+        tIndexName :: String
+    } |
+    Contravariant {
+        indexSize  :: Maybe Int,
+        tIndexName :: String
+    } |
+    Indifferent {
+        indexSize  :: Maybe Int,
+        tIndexName :: String
+    }
+    deriving Eq
+
+{-| Show tensor index -}
+instance Show TIndex where
+    show (Covariant c n)     = "[" ++ n ++ ":" ++ show c ++ "]"
+    show (Contravariant c n) = "<" ++ n ++ ":" ++ show c ++ ">"
+    show (Indifferent c n)   = "(" ++ n ++ ":" ++ show c ++ ")"
+
+{-| Finite index is a Multilinear.Index instance -}
+instance Index TIndex where
+
+    {-| Index name -}
+    indexName = tIndexName
+
+    {-| Return true if index is covariant |-}
+    isCovariant (Covariant _ _) = True
+    isCovariant _               = False
+
+    {-| Return true if index is contravariant |-}
+    isContravariant (Contravariant _ _) = True
+    isContravariant _                   = False
+
+    {-| Return true if index is indifferent |-}
+    isIndifferent (Indifferent _ _) = True
+    isIndifferent _                 = False
+
+    {-| Returns true if two indices are quivalent, i.e. differs only by name, but share same type and size. -}
+    equivI (Covariant count1 _) (Covariant count2 _)
+        | count1 == count2 = True
+        | otherwise = False
+    equivI (Contravariant count1 _) (Contravariant count2 _)
+        | count1 == count2 = True
+        | otherwise = False
+    equivI (Indifferent count1 _) (Indifferent count2 _)
+        | count1 == count2 = True
+        | otherwise = False
+    equivI _ _ = False
+
+    {-| TIndex must not be converted to TIndex -}
+    toTIndex = id
+
+{-| Indices can be compared by its size |-}
+{-| Used to allow to put tensors to typical ordered containers |-}
+instance Ord TIndex where
+    ind1 <= ind2 = indexSize ind1 <= indexSize ind2
+
+
src/Multilinear/Index/Finite.hs view
@@ -1,85 +1,85 @@-{-|-Module      : Multilinear.Index.Finite-Description : Finite-dimensional tensor index.-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--Finite-dimensional tensor index.---}--module Multilinear.Index.Finite (-    Index(..),-) where--import           Control.DeepSeq-import           GHC.Generics-import qualified Multilinear.Index as TIndex--{-| Index of finite-dimensional tensor with specified size -}-data Index =-    Covariant {-        indexSize  :: Int,-        indexName' :: String-    } |-    Contravariant {-        indexSize  :: Int,-        indexName' :: String-    } |-    Indifferent {-        indexSize  :: Int,-        indexName' :: String-    }-    deriving (Eq, Generic)--{-| Show instance of Finite index -}-instance Show Index where-    show (Covariant c n)     = "[" ++ n ++ ":" ++ show c ++ "]"-    show (Contravariant c n) = "<" ++ n ++ ":" ++ show c ++ ">"-    show (Indifferent c n)   = "(" ++ n ++ ":" ++ show c ++ ")"--{-| Finite index is a Multilinear.Index instance -}-instance TIndex.Index Index where--    {-| Index name -}-    indexName = indexName'--    {-| Return true if index is covariant |-}-    isCovariant (Covariant _ _) = True-    isCovariant _               = False--    {-| Return true if index is contravariant |-}-    isContravariant (Contravariant _ _) = True-    isContravariant _                   = False--    {-| Return true if index is indifferent |-}-    isIndifferent (Indifferent _ _) = True-    isIndifferent _                 = False--    {-| Returns true if two indices are quivalent, i.e. differs only by name, but share same type and size. -}-    equivI (Covariant count1 _) (Covariant count2 _)-        | count1 == count2 = True-        | otherwise = False-    equivI (Contravariant count1 _) (Contravariant count2 _)-        | count1 == count2 = True-        | otherwise = False-    equivI (Indifferent count1 _) (Indifferent count2 _)-        | count1 == count2 = True-        | otherwise = False-    equivI _ _ = False--    {-| Convert to TIndex type -}-    toTIndex (Covariant size name)     = TIndex.Covariant (Just size) name-    toTIndex (Contravariant size name) = TIndex.Contravariant (Just size) name-    toTIndex (Indifferent size name)   = TIndex.Indifferent (Just size) name--{-| Indices can be compared by its size |-}-{-| Used to allow to put tensors to typical ordered containers |-}-instance Ord Index where-    ind1 <= ind2 = indexSize ind1 <= indexSize ind2---- NFData instance-instance NFData Index+{-|
+Module      : Multilinear.Index.Finite
+Description : Finite-dimensional tensor index.
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+Finite-dimensional tensor index.
+
+-}
+
+module Multilinear.Index.Finite (
+    Index(..),
+) where
+
+import           Control.DeepSeq
+import           GHC.Generics
+import qualified Multilinear.Index as TIndex
+
+{-| Index of finite-dimensional tensor with specified size -}
+data Index =
+    Covariant {
+        indexSize  :: Int,
+        indexName' :: String
+    } |
+    Contravariant {
+        indexSize  :: Int,
+        indexName' :: String
+    } |
+    Indifferent {
+        indexSize  :: Int,
+        indexName' :: String
+    }
+    deriving (Eq, Generic)
+
+{-| Show instance of Finite index -}
+instance Show Index where
+    show (Covariant c n)     = "[" ++ n ++ ":" ++ show c ++ "]"
+    show (Contravariant c n) = "<" ++ n ++ ":" ++ show c ++ ">"
+    show (Indifferent c n)   = "(" ++ n ++ ":" ++ show c ++ ")"
+
+{-| Finite index is a Multilinear.Index instance -}
+instance TIndex.Index Index where
+
+    {-| Index name -}
+    indexName = indexName'
+
+    {-| Return true if index is covariant |-}
+    isCovariant (Covariant _ _) = True
+    isCovariant _               = False
+
+    {-| Return true if index is contravariant |-}
+    isContravariant (Contravariant _ _) = True
+    isContravariant _                   = False
+
+    {-| Return true if index is indifferent |-}
+    isIndifferent (Indifferent _ _) = True
+    isIndifferent _                 = False
+
+    {-| Returns true if two indices are quivalent, i.e. differs only by name, but share same type and size. -}
+    equivI (Covariant count1 _) (Covariant count2 _)
+        | count1 == count2 = True
+        | otherwise = False
+    equivI (Contravariant count1 _) (Contravariant count2 _)
+        | count1 == count2 = True
+        | otherwise = False
+    equivI (Indifferent count1 _) (Indifferent count2 _)
+        | count1 == count2 = True
+        | otherwise = False
+    equivI _ _ = False
+
+    {-| Convert to TIndex type -}
+    toTIndex (Covariant size name)     = TIndex.Covariant (Just size) name
+    toTIndex (Contravariant size name) = TIndex.Contravariant (Just size) name
+    toTIndex (Indifferent size name)   = TIndex.Indifferent (Just size) name
+
+{-| Indices can be compared by its size |-}
+{-| Used to allow to put tensors to typical ordered containers |-}
+instance Ord Index where
+    ind1 <= ind2 = indexSize ind1 <= indexSize ind2
+
+-- NFData instance
+instance NFData Index
src/Multilinear/Index/Infinite.hs view
@@ -1,71 +1,71 @@-{-|-Module      : Multilinear.Index.Infinite-Description : Infinite-dimensional tensor index.-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--Infinite-dimensional tensor index.---}--module Multilinear.Index.Infinite (-    Index(..)-) where--import           Control.DeepSeq-import           GHC.Generics-import qualified Multilinear.Index as TIndex--{-| Index of infinite-dimensional tensor -}-data Index =-    Covariant {-        indexName' :: String-    } |-    Contravariant {-        indexName' :: String-    } |-    Indifferent {-        indexName' :: String-    }-    deriving (Eq, Generic)--{-| Show instance of Infinite index -}-instance Show Index where-    show (Covariant n)     = "[" ++ n ++ "]"-    show (Contravariant n) = "<" ++ n ++ ">"-    show (Indifferent n)   = "(" ++ n ++ ")"--{-| Infinite index is a Multilinear.Index instance -}-instance TIndex.Index Index where--    {-| Index name -}-    indexName = indexName'--    {-| Return true if index is covariant |-}-    isCovariant (Covariant _) = True-    isCovariant _             = False--    {-| Return true if index is contravariant |-}-    isContravariant (Contravariant _) = True-    isContravariant _                 = False--    {-| Return true if index is indifferent |-}-    isIndifferent (Indifferent _) = True-    isIndifferent _               = False--    {-| Returns true if two indices are quivalent, i.e. differs only by name, but share same type. -}-    equivI (Covariant _) (Covariant _)         = True-    equivI (Contravariant _) (Contravariant _) = True-    equivI (Indifferent _) (Indifferent _)     = True-    equivI _ _                                 = False--    {-| Convert to TIndex -}-    toTIndex (Covariant name)     = TIndex.Covariant Nothing name-    toTIndex (Contravariant name) = TIndex.Contravariant Nothing name-    toTIndex (Indifferent name)   = TIndex.Indifferent Nothing name---- NFData instance-instance NFData Index+{-|
+Module      : Multilinear.Index.Infinite
+Description : Infinite-dimensional tensor index.
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+Infinite-dimensional tensor index.
+
+-}
+
+module Multilinear.Index.Infinite (
+    Index(..)
+) where
+
+import           Control.DeepSeq
+import           GHC.Generics
+import qualified Multilinear.Index as TIndex
+
+{-| Index of infinite-dimensional tensor -}
+data Index =
+    Covariant {
+        indexName' :: String
+    } |
+    Contravariant {
+        indexName' :: String
+    } |
+    Indifferent {
+        indexName' :: String
+    }
+    deriving (Eq, Generic)
+
+{-| Show instance of Infinite index -}
+instance Show Index where
+    show (Covariant n)     = "[" ++ n ++ "]"
+    show (Contravariant n) = "<" ++ n ++ ">"
+    show (Indifferent n)   = "(" ++ n ++ ")"
+
+{-| Infinite index is a Multilinear.Index instance -}
+instance TIndex.Index Index where
+
+    {-| Index name -}
+    indexName = indexName'
+
+    {-| Return true if index is covariant |-}
+    isCovariant (Covariant _) = True
+    isCovariant _             = False
+
+    {-| Return true if index is contravariant |-}
+    isContravariant (Contravariant _) = True
+    isContravariant _                 = False
+
+    {-| Return true if index is indifferent |-}
+    isIndifferent (Indifferent _) = True
+    isIndifferent _               = False
+
+    {-| Returns true if two indices are quivalent, i.e. differs only by name, but share same type. -}
+    equivI (Covariant _) (Covariant _)         = True
+    equivI (Contravariant _) (Contravariant _) = True
+    equivI (Indifferent _) (Indifferent _)     = True
+    equivI _ _                                 = False
+
+    {-| Convert to TIndex -}
+    toTIndex (Covariant name)     = TIndex.Covariant Nothing name
+    toTIndex (Contravariant name) = TIndex.Contravariant Nothing name
+    toTIndex (Indifferent name)   = TIndex.Indifferent Nothing name
+
+-- NFData instance
+instance NFData Index
src/Multilinear/Matrix.hs view
@@ -1,147 +1,147 @@-{-|-Module      : Multilinear.Matrix-Description : Matrix constructors (finitely- or infinitely dimensional)-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--- This module provides convenient constructors that generates a matrix (finitely- or infinite-dimensional)-- Finitely-dimensional matrices provide much greater performance than infinitely-dimensional---}--module Multilinear.Matrix (-  -- * Generators-  Multilinear.Matrix.fromIndices, -  Multilinear.Matrix.const,-  Multilinear.Matrix.randomDouble, -  Multilinear.Matrix.randomDoubleSeed,-  Multilinear.Matrix.randomInt, -  Multilinear.Matrix.randomIntSeed,-) where--import           Control.Monad.Primitive-import           Multilinear.Generic-import qualified Multilinear.Tensor         as Tensor-import           Statistics.Distribution--invalidIndices :: String-invalidIndices = "Indices and its sizes not compatible with structure of matrix!"--{-| Generate matrix as function of its indices -}-{-# INLINE fromIndices #-}-fromIndices :: (-    Num a-  ) => String               -- ^ Indices names (one character per index, first character: rows index, second character: columns index)-    -> Int                  -- ^ Number of matrix rows-    -> Int                  -- ^ Number of matrix columns-    -> (Int -> Int -> a)    -- ^ Generator function - returns a matrix component at @i,j@-    -> Tensor a             -- ^ Generated matrix--fromIndices [u,d] us ds f = Tensor.fromIndices ([u],[us]) ([d],[ds]) $ \[ui] [di] -> f ui di-fromIndices _ _ _ _ = Err invalidIndices--{-| Generate matrix with all components equal to @v@ -}-{-# INLINE Multilinear.Matrix.const #-}-const :: (-    Num a-  ) => String    -- ^ Indices names (one character per index, first character: rows index, second character: columns index)-    -> Int       -- ^ Number of matrix rows-    -> Int       -- ^ Number of matrix columns-    -> a         -- ^ Value of matrix components-    -> Tensor a  -- ^ Generated matrix--const [u,d] us ds = Tensor.const ([u],[us]) ([d],[ds])-const _ _ _ = \_ -> Err invalidIndices--{-| Generate matrix with random real components with given probability distribution.-The matrix is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDouble #-}-randomDouble :: (-    ContGen d-  ) => String              -- ^ Indices names (one character per index, first character: rows index, second character: columns index)-    -> Int                 -- ^ Number of matrix rows-    -> Int                 -- ^ Number of matrix columns-    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Double)  -- ^ Generated matrix--randomDouble [u,d] us ds = Tensor.randomDouble ([u],[us]) ([d],[ds])-randomDouble _ _ _ = \_ -> return $ Err invalidIndices--{-| Generate matrix with random integer components with given probability distribution.-The matrix is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomInt #-}-randomInt :: (-    DiscreteGen d-  ) => String           -- ^ Indices names (one character per index, first character: rows index, second character: columns index)-    -> Int              -- ^ Number of matrix rows-    -> Int              -- ^ Number of matrix columns-    -> d                -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Int)  -- ^ Generated matrix--randomInt [u,d] us ds = Tensor.randomInt ([u],[us]) ([d],[ds])-randomInt _ _ _ = \_ -> return $ Err invalidIndices--{-| Generate matrix with random real components with given probability distribution and given seed.-The matrix is wrapped in the a monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDoubleSeed #-}-randomDoubleSeed :: (-    ContGen d, PrimMonad m-  ) => String              -- ^ Indices names (one character per index, first character: rows index, second character: columns index)-    -> Int                 -- ^ Number of matrix rows-    -> Int                 -- ^ Number of matrix columns-    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> Int                 -- ^ Randomness seed-    -> m (Tensor Double)   -- ^ Generated matrix--randomDoubleSeed [u,d] us ds = Tensor.randomDoubleSeed ([u],[us]) ([d],[ds])-randomDoubleSeed _ _ _ = \_ _ -> return $ Err invalidIndices--{-| Generate matrix with random integer components with given probability distribution. and given seed.-The matrix is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomIntSeed #-}-randomIntSeed :: (-    DiscreteGen d, PrimMonad m-  ) => String              -- ^ Indices names (one character per index, first character: rows index, second character: columns index)-    -> Int                 -- ^ Number of matrix rows-    -> Int                 -- ^ Number of matrix columns-    -> d                   -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> Int                 -- ^ Randomness seed-    -> m (Tensor Int)      -- ^ Generated matrix--randomIntSeed [u,d] us ds = Tensor.randomIntSeed ([u],[us]) ([d],[ds])-randomIntSeed _ _ _ = \_ _ -> return $ Err invalidIndices+{-|
+Module      : Multilinear.Matrix
+Description : Matrix constructors (finitely- or infinitely dimensional)
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+- This module provides convenient constructors that generates a matrix (finitely- or infinite-dimensional)
+- Finitely-dimensional matrices provide much greater performance than infinitely-dimensional
+
+-}
+
+module Multilinear.Matrix (
+  -- * Generators
+  Multilinear.Matrix.fromIndices, 
+  Multilinear.Matrix.const,
+  Multilinear.Matrix.randomDouble, 
+  Multilinear.Matrix.randomDoubleSeed,
+  Multilinear.Matrix.randomInt, 
+  Multilinear.Matrix.randomIntSeed,
+) where
+
+import           Control.Monad.Primitive
+import           Multilinear.Generic
+import qualified Multilinear.Tensor         as Tensor
+import           Statistics.Distribution
+
+invalidIndices :: String
+invalidIndices = "Indices and its sizes not compatible with structure of matrix!"
+
+{-| Generate matrix as function of its indices -}
+{-# INLINE fromIndices #-}
+fromIndices :: (
+    Num a
+  ) => String               -- ^ Indices names (one character per index, first character: rows index, second character: columns index)
+    -> Int                  -- ^ Number of matrix rows
+    -> Int                  -- ^ Number of matrix columns
+    -> (Int -> Int -> a)    -- ^ Generator function - returns a matrix component at @i,j@
+    -> Tensor a             -- ^ Generated matrix
+
+fromIndices [u,d] us ds f = Tensor.fromIndices ([u],[us]) ([d],[ds]) $ \[ui] [di] -> f ui di
+fromIndices _ _ _ _ = Err invalidIndices
+
+{-| Generate matrix with all components equal to @v@ -}
+{-# INLINE Multilinear.Matrix.const #-}
+const :: (
+    Num a
+  ) => String    -- ^ Indices names (one character per index, first character: rows index, second character: columns index)
+    -> Int       -- ^ Number of matrix rows
+    -> Int       -- ^ Number of matrix columns
+    -> a         -- ^ Value of matrix components
+    -> Tensor a  -- ^ Generated matrix
+
+const [u,d] us ds = Tensor.const ([u],[us]) ([d],[ds])
+const _ _ _ = \_ -> Err invalidIndices
+
+{-| Generate matrix with random real components with given probability distribution.
+The matrix is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDouble #-}
+randomDouble :: (
+    ContGen d
+  ) => String              -- ^ Indices names (one character per index, first character: rows index, second character: columns index)
+    -> Int                 -- ^ Number of matrix rows
+    -> Int                 -- ^ Number of matrix columns
+    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Double)  -- ^ Generated matrix
+
+randomDouble [u,d] us ds = Tensor.randomDouble ([u],[us]) ([d],[ds])
+randomDouble _ _ _ = \_ -> return $ Err invalidIndices
+
+{-| Generate matrix with random integer components with given probability distribution.
+The matrix is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomInt #-}
+randomInt :: (
+    DiscreteGen d
+  ) => String           -- ^ Indices names (one character per index, first character: rows index, second character: columns index)
+    -> Int              -- ^ Number of matrix rows
+    -> Int              -- ^ Number of matrix columns
+    -> d                -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Int)  -- ^ Generated matrix
+
+randomInt [u,d] us ds = Tensor.randomInt ([u],[us]) ([d],[ds])
+randomInt _ _ _ = \_ -> return $ Err invalidIndices
+
+{-| Generate matrix with random real components with given probability distribution and given seed.
+The matrix is wrapped in the a monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDoubleSeed #-}
+randomDoubleSeed :: (
+    ContGen d, PrimMonad m
+  ) => String              -- ^ Indices names (one character per index, first character: rows index, second character: columns index)
+    -> Int                 -- ^ Number of matrix rows
+    -> Int                 -- ^ Number of matrix columns
+    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> Int                 -- ^ Randomness seed
+    -> m (Tensor Double)   -- ^ Generated matrix
+
+randomDoubleSeed [u,d] us ds = Tensor.randomDoubleSeed ([u],[us]) ([d],[ds])
+randomDoubleSeed _ _ _ = \_ _ -> return $ Err invalidIndices
+
+{-| Generate matrix with random integer components with given probability distribution. and given seed.
+The matrix is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomIntSeed #-}
+randomIntSeed :: (
+    DiscreteGen d, PrimMonad m
+  ) => String              -- ^ Indices names (one character per index, first character: rows index, second character: columns index)
+    -> Int                 -- ^ Number of matrix rows
+    -> Int                 -- ^ Number of matrix columns
+    -> d                   -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> Int                 -- ^ Randomness seed
+    -> m (Tensor Int)      -- ^ Generated matrix
+
+randomIntSeed [u,d] us ds = Tensor.randomIntSeed ([u],[us]) ([d],[ds])
+randomIntSeed _ _ _ = \_ _ -> return $ Err invalidIndices
src/Multilinear/NForm.hs view
@@ -1,168 +1,168 @@-{-|-Module      : Multilinear.NForm-Description : N-Forms, dot and cross product and determinant-Copyright   : (c) Artur M. Brodzki, 2018-License     : GLP-3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--- This module provides convenient constructors that generates n-forms (tensors with n lower indices with finite or infinite size). -- Finitely-dimensional n-forms provide much greater performance than infinitely-dimensional---}--module Multilinear.NForm (-    -- * Generators-  Multilinear.NForm.fromIndices, -  Multilinear.NForm.const,-  Multilinear.NForm.randomDouble, -  Multilinear.NForm.randomDoubleSeed,-  Multilinear.NForm.randomInt, -  Multilinear.NForm.randomIntSeed,-  -- * Common cases-  Multilinear.NForm.dot, -  Multilinear.NForm.cross-) where--import           Control.Monad.Primitive-import           Multilinear.Generic-import qualified Multilinear.Tensor       as Tensor-import           Statistics.Distribution--invalidIndices :: String-invalidIndices = "Indices and its sizes incompatible with n-form structure!"--invalidCrossProductIndices :: String-invalidCrossProductIndices = "Indices and its sizes incompatible with cross product structure!"--{-| Generate N-form as function of its indices -}-{-# INLINE fromIndices #-}-fromIndices :: (-    Num a-  ) => String        -- ^ Indices names (one characted per index)-    -> [Int]         -- ^ Indices sizes-    -> ([Int] -> a)  -- ^ Generator function-    -> Tensor a      -- ^ Generated N-form--fromIndices d ds f = Tensor.fromIndices ([],[]) (d,ds) $ \[] -> f--{-| Generate N-form with all components equal to @v@ -}-{-# INLINE Multilinear.NForm.const #-}-const :: (-    Num a-  ) => String    -- ^ Indices names (one characted per index)-    -> [Int]     -- ^ Indices sizes-    -> a         -- ^ N-form elements value-    -> Tensor a  -- ^ Generated N-form--const d ds = Tensor.const ([],[]) (d,ds)--{-| Generate n-vector with random real components with given probability distribution.-The n-vector is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDouble #-}-randomDouble :: (-    ContGen d-  ) => String              -- ^ Indices names (one character per index)-    -> [Int]               -- ^ Indices sizes-    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Double)  -- ^ Generated linear functional--randomDouble d ds = Tensor.randomDouble ([],[]) (d,ds)--{-| Generate n-vector with random integer components with given probability distribution.-The n-vector is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomInt #-}-randomInt :: (-    DiscreteGen d-  ) => String              -- ^ Indices names (one character per index)-    -> [Int]               -- ^ Indices sizes-    -> d                   -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Int)     -- ^ Generated n-vector--randomInt d ds = Tensor.randomInt ([],[]) (d,ds)--{-| Generate n-vector with random real components with given probability distribution and given seed.-The form is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDoubleSeed #-}-randomDoubleSeed :: (-    ContGen d, PrimMonad m-  ) => String            -- ^ Index name (one character)-    -> [Int]             -- ^ Number of elements-    -> d                 -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> Int               -- ^ Randomness seed-    -> m (Tensor Double) -- ^ Generated n-vector--randomDoubleSeed d ds = Tensor.randomDoubleSeed ([],[]) (d,ds)--{-| Generate n-vector with random integer components with given probability distribution and given seed.-The form is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomIntSeed #-}-randomIntSeed :: (-    DiscreteGen d, PrimMonad m-  ) => String            -- ^ Index name (one character)-    -> [Int]             -- ^ Number of elements-    -> d                 -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> Int               -- ^ Randomness seed-    -> m (Tensor Int)    -- ^ Generated n-vector--randomIntSeed d ds = Tensor.randomIntSeed ([],[]) (d,ds)--{-| 2-form representing a dot product -}-{-# INLINE dot #-}-dot :: (-    Num a-  ) => String    -- ^ Indices names (one characted per index)-    -> Int       -- ^ Size of tensor (dot product is a square tensor)-    -> Tensor a  -- ^ Generated dot product--dot [i1,i2] size = fromIndices [i1,i2] [size,size] (\[i,j] -> if i == j then 1 else 0)-dot _ _ = Err invalidIndices--{-| Tensor representing a cross product (Levi - Civita symbol). It also allows to compute a determinant of square matrix - determinant of matrix @M@ is a equal to length of cross product of all columns of @M@ -}--- // TODO-{-# INLINE cross #-}-cross :: (-    Num a-  ) => String    -- ^ Indices names (one characted per index)-    -> Int       -- ^ Size of tensor (dot product is a square tensor)-    -> Tensor a  -- ^ Generated dot product--cross [i,j,k] size =-  Tensor.fromIndices ([i],[size]) ([j,k],[size,size])-    (\[_] [_,_] -> 0)-cross _ _ = Err invalidCrossProductIndices+{-|
+Module      : Multilinear.NForm
+Description : N-Forms, dot and cross product and determinant
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : GLP-3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+- This module provides convenient constructors that generates n-forms (tensors with n lower indices with finite or infinite size). 
+- Finitely-dimensional n-forms provide much greater performance than infinitely-dimensional
+
+-}
+
+module Multilinear.NForm (
+    -- * Generators
+  Multilinear.NForm.fromIndices, 
+  Multilinear.NForm.const,
+  Multilinear.NForm.randomDouble, 
+  Multilinear.NForm.randomDoubleSeed,
+  Multilinear.NForm.randomInt, 
+  Multilinear.NForm.randomIntSeed,
+  -- * Common cases
+  Multilinear.NForm.dot, 
+  Multilinear.NForm.cross
+) where
+
+import           Control.Monad.Primitive
+import           Multilinear.Generic
+import qualified Multilinear.Tensor       as Tensor
+import           Statistics.Distribution
+
+invalidIndices :: String
+invalidIndices = "Indices and its sizes incompatible with n-form structure!"
+
+invalidCrossProductIndices :: String
+invalidCrossProductIndices = "Indices and its sizes incompatible with cross product structure!"
+
+{-| Generate N-form as function of its indices -}
+{-# INLINE fromIndices #-}
+fromIndices :: (
+    Num a
+  ) => String        -- ^ Indices names (one characted per index)
+    -> [Int]         -- ^ Indices sizes
+    -> ([Int] -> a)  -- ^ Generator function
+    -> Tensor a      -- ^ Generated N-form
+
+fromIndices d ds f = Tensor.fromIndices ([],[]) (d,ds) $ \[] -> f
+
+{-| Generate N-form with all components equal to @v@ -}
+{-# INLINE Multilinear.NForm.const #-}
+const :: (
+    Num a
+  ) => String    -- ^ Indices names (one characted per index)
+    -> [Int]     -- ^ Indices sizes
+    -> a         -- ^ N-form elements value
+    -> Tensor a  -- ^ Generated N-form
+
+const d ds = Tensor.const ([],[]) (d,ds)
+
+{-| Generate n-vector with random real components with given probability distribution.
+The n-vector is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDouble #-}
+randomDouble :: (
+    ContGen d
+  ) => String              -- ^ Indices names (one character per index)
+    -> [Int]               -- ^ Indices sizes
+    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Double)  -- ^ Generated linear functional
+
+randomDouble d ds = Tensor.randomDouble ([],[]) (d,ds)
+
+{-| Generate n-vector with random integer components with given probability distribution.
+The n-vector is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomInt #-}
+randomInt :: (
+    DiscreteGen d
+  ) => String              -- ^ Indices names (one character per index)
+    -> [Int]               -- ^ Indices sizes
+    -> d                   -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Int)     -- ^ Generated n-vector
+
+randomInt d ds = Tensor.randomInt ([],[]) (d,ds)
+
+{-| Generate n-vector with random real components with given probability distribution and given seed.
+The form is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDoubleSeed #-}
+randomDoubleSeed :: (
+    ContGen d, PrimMonad m
+  ) => String            -- ^ Index name (one character)
+    -> [Int]             -- ^ Number of elements
+    -> d                 -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> Int               -- ^ Randomness seed
+    -> m (Tensor Double) -- ^ Generated n-vector
+
+randomDoubleSeed d ds = Tensor.randomDoubleSeed ([],[]) (d,ds)
+
+{-| Generate n-vector with random integer components with given probability distribution and given seed.
+The form is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomIntSeed #-}
+randomIntSeed :: (
+    DiscreteGen d, PrimMonad m
+  ) => String            -- ^ Index name (one character)
+    -> [Int]             -- ^ Number of elements
+    -> d                 -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> Int               -- ^ Randomness seed
+    -> m (Tensor Int)    -- ^ Generated n-vector
+
+randomIntSeed d ds = Tensor.randomIntSeed ([],[]) (d,ds)
+
+{-| 2-form representing a dot product -}
+{-# INLINE dot #-}
+dot :: (
+    Num a
+  ) => String    -- ^ Indices names (one characted per index)
+    -> Int       -- ^ Size of tensor (dot product is a square tensor)
+    -> Tensor a  -- ^ Generated dot product
+
+dot [i1,i2] size = fromIndices [i1,i2] [size,size] (\[i,j] -> if i == j then 1 else 0)
+dot _ _ = Err invalidIndices
+
+{-| Tensor representing a cross product (Levi - Civita symbol). It also allows to compute a determinant of square matrix - determinant of matrix @M@ is a equal to length of cross product of all columns of @M@ -}
+-- // TODO
+{-# INLINE cross #-}
+cross :: (
+    Num a
+  ) => String    -- ^ Indices names (one characted per index)
+    -> Int       -- ^ Size of tensor (dot product is a square tensor)
+    -> Tensor a  -- ^ Generated dot product
+
+cross [i,j,k] size =
+  Tensor.fromIndices ([i],[size]) ([j,k],[size,size])
+    (\[_] [_,_] -> 0)
+cross _ _ = Err invalidCrossProductIndices
src/Multilinear/NVector.hs view
@@ -1,134 +1,134 @@-{-|-Module      : Multilinear.NVector-Description : N-Vectors constructors (finitely- or infinitely-dimensional)-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--- This module provides convenient constructors that generate a n-vector (tensor with n upper indices with finite or infinite size).  -- Finitely-dimensional n-vectors provide much greater performance than infinitely-dimensional---}--module Multilinear.NVector (-  -- * Generators-  Multilinear.NVector.fromIndices, -  Multilinear.NVector.const,-  Multilinear.NVector.randomDouble, -  Multilinear.NVector.randomDoubleSeed,-  Multilinear.NVector.randomInt, -  Multilinear.NVector.randomIntSeed,-) where--import           Control.Monad.Primitive-import           Multilinear.Generic-import           Multilinear.Tensor          as Tensor-import           Statistics.Distribution--{-| Generate n-vector as function of its indices -}-{-# INLINE fromIndices #-}-fromIndices :: (-    Num a-  ) => String        -- ^ Indices names (one characted per index)-    -> [Int]         -- ^ Indices sizes-    -> ([Int] -> a)  -- ^ Generator function-    -> Tensor a      -- ^ Generated n-vector--fromIndices u us f = Tensor.fromIndices (u,us) ([],[]) $ \uis [] -> f uis--{-| Generate n-vector with all components equal to @v@ -}-{-# INLINE Multilinear.NForm.const #-}-const :: (-    Num a-  ) => String    -- ^ Indices names (one characted per index)-    -> [Int]     -- ^ Indices sizes-    -> a         -- ^ n-vector elements value-    -> Tensor a  -- ^ Generated n-vector--const u us = Tensor.const (u,us) ([],[])--{-| Generate n-vector with random real components with given probability distribution.-The n-vector is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDouble #-}-randomDouble :: (-    ContGen d-  ) => String              -- ^ Indices names (one character per index)-    -> [Int]               -- ^ Indices sizes-    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Double)  -- ^ Generated linear functional--randomDouble u us = Tensor.randomDouble (u,us) ([],[])--{-| Generate n-vector with random integer components with given probability distribution.-The n-vector is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomInt #-}-randomInt :: (-    DiscreteGen d-  ) => String              -- ^ Indices names (one character per index)-    -> [Int]               -- ^ Indices sizes-    -> d                   -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Int)     -- ^ Generated n-vector--randomInt u us = Tensor.randomInt (u,us) ([],[])--{-| Generate n-vector with random real components with given probability distribution and given seed.-The form is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDoubleSeed #-}-randomDoubleSeed :: (-    ContGen d, PrimMonad m-  ) => String            -- ^ Index name (one character)-    -> [Int]             -- ^ Number of elements-    -> d                 -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> Int               -- ^ Randomness seed-    -> m (Tensor Double) -- ^ Generated n-vector--randomDoubleSeed u us = Tensor.randomDoubleSeed (u,us) ([],[])--{-| Generate n-vector with random integer components with given probability distribution and given seed.-The form is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomIntSeed #-}-randomIntSeed :: (-    DiscreteGen d, PrimMonad m-  ) => String            -- ^ Index name (one character)-    -> [Int]             -- ^ Number of elements-    -> d                 -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> Int               -- ^ Randomness seed-    -> m (Tensor Int)    -- ^ Generated n-vector--randomIntSeed u us = Tensor.randomIntSeed (u,us) ([],[])+{-|
+Module      : Multilinear.NVector
+Description : N-Vectors constructors (finitely- or infinitely-dimensional)
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+- This module provides convenient constructors that generate a n-vector (tensor with n upper indices with finite or infinite size).  
+- Finitely-dimensional n-vectors provide much greater performance than infinitely-dimensional
+
+-}
+
+module Multilinear.NVector (
+  -- * Generators
+  Multilinear.NVector.fromIndices, 
+  Multilinear.NVector.const,
+  Multilinear.NVector.randomDouble, 
+  Multilinear.NVector.randomDoubleSeed,
+  Multilinear.NVector.randomInt, 
+  Multilinear.NVector.randomIntSeed,
+) where
+
+import           Control.Monad.Primitive
+import           Multilinear.Generic
+import           Multilinear.Tensor          as Tensor
+import           Statistics.Distribution
+
+{-| Generate n-vector as function of its indices -}
+{-# INLINE fromIndices #-}
+fromIndices :: (
+    Num a
+  ) => String        -- ^ Indices names (one characted per index)
+    -> [Int]         -- ^ Indices sizes
+    -> ([Int] -> a)  -- ^ Generator function
+    -> Tensor a      -- ^ Generated n-vector
+
+fromIndices u us f = Tensor.fromIndices (u,us) ([],[]) $ \uis [] -> f uis
+
+{-| Generate n-vector with all components equal to @v@ -}
+{-# INLINE Multilinear.NForm.const #-}
+const :: (
+    Num a
+  ) => String    -- ^ Indices names (one characted per index)
+    -> [Int]     -- ^ Indices sizes
+    -> a         -- ^ n-vector elements value
+    -> Tensor a  -- ^ Generated n-vector
+
+const u us = Tensor.const (u,us) ([],[])
+
+{-| Generate n-vector with random real components with given probability distribution.
+The n-vector is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDouble #-}
+randomDouble :: (
+    ContGen d
+  ) => String              -- ^ Indices names (one character per index)
+    -> [Int]               -- ^ Indices sizes
+    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Double)  -- ^ Generated linear functional
+
+randomDouble u us = Tensor.randomDouble (u,us) ([],[])
+
+{-| Generate n-vector with random integer components with given probability distribution.
+The n-vector is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomInt #-}
+randomInt :: (
+    DiscreteGen d
+  ) => String              -- ^ Indices names (one character per index)
+    -> [Int]               -- ^ Indices sizes
+    -> d                   -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Int)     -- ^ Generated n-vector
+
+randomInt u us = Tensor.randomInt (u,us) ([],[])
+
+{-| Generate n-vector with random real components with given probability distribution and given seed.
+The form is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDoubleSeed #-}
+randomDoubleSeed :: (
+    ContGen d, PrimMonad m
+  ) => String            -- ^ Index name (one character)
+    -> [Int]             -- ^ Number of elements
+    -> d                 -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> Int               -- ^ Randomness seed
+    -> m (Tensor Double) -- ^ Generated n-vector
+
+randomDoubleSeed u us = Tensor.randomDoubleSeed (u,us) ([],[])
+
+{-| Generate n-vector with random integer components with given probability distribution and given seed.
+The form is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomIntSeed #-}
+randomIntSeed :: (
+    DiscreteGen d, PrimMonad m
+  ) => String            -- ^ Index name (one character)
+    -> [Int]             -- ^ Number of elements
+    -> d                 -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> Int               -- ^ Randomness seed
+    -> m (Tensor Int)    -- ^ Generated n-vector
+
+randomIntSeed u us = Tensor.randomIntSeed (u,us) ([],[])
src/Multilinear/Tensor.hs view
@@ -1,289 +1,289 @@-{-|-Module      : Multilinear.Tensor-Description : Tensors constructors (finitely- or infinitely-dimensional)-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--- This module provides convenient constructors that generate a arbitrary finitely- or infinitely-dimensional tensors. -- Finitely-dimensional tensors provide much greater performance than inifitely-dimensional---}--module Multilinear.Tensor (-  -- * Generators-  Multilinear.Tensor.fromIndices, -  Multilinear.Tensor.generate,-  Multilinear.Tensor.const,-  Multilinear.Tensor.randomDouble, -  Multilinear.Tensor.randomDoubleSeed,-  Multilinear.Tensor.randomInt, -  Multilinear.Tensor.randomIntSeed-) where--import           Control.Monad.Primitive-import qualified Data.Vector                as Boxed-import           Multilinear.Generic-import           Multilinear.Index.Finite   as Finite-import           Statistics.Distribution-import qualified System.Random.MWC          as MWC--invalidIndices :: (String, [Int]) -> (String, [Int]) -> String-invalidIndices us ds = "Indices and its sizes incompatible, upper indices: " ++ show us ++", lower indices: " ++ show ds--{-| Generate tensor as functions of its indices -}-{-# INLINE fromIndices #-}-fromIndices :: (-    Num a-    ) => (String,[Int])          -- ^ Upper indices names (one character per index) and its sizes-      -> (String,[Int])          -- ^ Lower indices names (one character per index) and its sizes-      -> ([Int] -> [Int] -> a)   -- ^ Generator function (f [u1,u2,...] [d1,d2,...] returns a tensor element at t [u1,u2,...] [d1,d2,...])-      -> Tensor a                -- ^ Generated tensor---- If only one upper index is given, generate a SimpleFinite tensor with upper index-fromIndices ([u],[s]) ([],[]) f = -  SimpleFinite (Contravariant s [u]) $ Boxed.generate s $ \x -> f [x] []---- If only one lower index is given, generate a SimpleFinite tensor with lower index-fromIndices ([],[]) ([d],[s]) f = -  SimpleFinite (Covariant s [d]) $ Boxed.generate s $ \x -> f [] [x]---- If many indices are given, first generate upper indices recursively from indices list-fromIndices (u:us,s:size) d f =-    FiniteTensor (Contravariant s [u]) $ Boxed.generate s (\x -> fromIndices (us,size) d (\uss dss -> f (x:uss) dss) )---- After upper indices, generate lower indices recursively from indices list-fromIndices u (d:ds,s:size) f =-    FiniteTensor (Covariant s [d]) $ Boxed.generate s (\x -> fromIndices u (ds,size) (\uss dss -> f uss (x:dss)) )---- If there are indices without size or sizes without names, throw an error-fromIndices us ds _ = Err $ invalidIndices us ds--{-| Generate tensor composed of other tensors -}-{-# INLINE generate #-}-generate :: (-    Num a-    ) => (String,[Int])                 -- ^ Upper indices names (one character per index) and its sizes-      -> (String,[Int])                 -- ^ Lower indices names (one character per index) and its sizes-      -> ([Int] -> [Int] -> Tensor a)   -- ^ Generator function (f [u1,u2,...] [d1,d2,...] returns a tensor element at t [u1,u2,...] [d1,d2,...])-      -> Tensor a                       -- ^ Generated tensor---- If no indices are given, generate a tensor by using generator function-generate ([],[]) ([],[]) f = f [] []---- If many indices are given, first generate upper indices recursively from indices list-generate (u:us,s:size) d f =-    FiniteTensor (Contravariant s [u]) $ Boxed.generate s (\x -> generate (us,size) d (\uss dss -> f (x:uss) dss) )---- After upper indices, generate lower indices recursively from indices list-generate u (d:ds,s:size) f =-    FiniteTensor (Covariant s [d]) $ Boxed.generate s (\x -> generate u (ds,size) (\uss dss -> f uss (x:dss)) )---- If there are indices without size or sizes without names, throw an error-generate us ds _ = Err $ invalidIndices us ds--{-| Generate tensor with all components equal to @v@ -}-{-# INLINE Multilinear.Tensor.const #-}-const :: (-    Num a-    ) => (String,[Int]) -- ^ Upper indices names (one character per index) and its sizes-      -> (String,[Int]) -- ^ Lower indices names (one character per index) and its sizes-      -> a              -- ^ Tensor elements value-      -> Tensor a       -- ^ Generated tensor---- If only one upper index is given, generate a SimpleFinite tensor with upper index-const ([u],[s]) ([],[]) v =-  SimpleFinite (Contravariant s [u]) $ Boxed.replicate s v---- If only ine lower index is given, generate a SimpleFinite tensor with lower index-const ([],[]) ([d],[s]) v =-  SimpleFinite (Covariant s [d]) $ Boxed.replicate s v---- If many indices are given, first generate upper indices recursively from indices list-const (u:us,s:size) d v =-    FiniteTensor (Contravariant s [u]) $ Boxed.replicate (fromIntegral s) $ Multilinear.Tensor.const (us,size) d v---- After upper indices, generate lower indices recursively from indices list-const u (d:ds,s:size) v =-    FiniteTensor (Covariant s [d]) $ Boxed.replicate (fromIntegral s) $ Multilinear.Tensor.const u (ds,size) v---- If there are indices without size or sizes without names, throw an error-const us ds _ = Err $ invalidIndices us ds--{-| Generate tensor with random real components with given probability distribution.-The tensor is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDouble #-}-randomDouble :: (-    ContGen d-  ) => (String,[Int])      -- ^ Upper indices names (one character per index) and its sizes-    -> (String,[Int])      -- ^ Lower indices names (one character per index) and its sizes-    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Double)  -- ^ Generated tensor---- If only one upper index is given, generate a SimpleFinite tensor with upper index-randomDouble ([u],[s]) ([],[]) distr = do-    gen <- MWC.createSystemRandom-    component <- sequence $ Boxed.generate s $ \_ -> genContVar distr gen-    return $ SimpleFinite (Contravariant s [u]) component---- If only one lower index is given, generate a SimpleFinite tensor with lower index-randomDouble ([],[]) ([d],[s]) distr = do-    gen <- MWC.createSystemRandom-    component <- sequence $ Boxed.generate s $ \_ -> genContVar distr gen-    return $ SimpleFinite (Covariant s [d]) component---- If many indices are given, first generate upper indices recursively from indices list-randomDouble (u:us,s:size) d distr = do-  tensors <- sequence $ Boxed.generate s $ \_ -> randomDouble (us,size) d distr-  return $ FiniteTensor (Contravariant s [u]) tensors---- After upper indices, generate lower indices recursively from indices list-randomDouble u (d:ds,s:size) distr = do-  tensors <- sequence $ Boxed.generate s $ \_ -> randomDouble u (ds,size) distr-  return $ FiniteTensor (Covariant s [d]) tensors---- If there are indices without size or sizes without names, throw an error-randomDouble us ds _ = return $ Err $ invalidIndices us ds--{-| Generate tensor with random integer components with given probability distribution.-The tensor is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomInt #-}-randomInt :: (-    DiscreteGen d-  ) => (String,[Int])    -- ^ Upper indices names (one character per index) and its sizes-    -> (String,[Int])    -- ^ Lower indices names (one character per index) and its sizes-    -> d                 -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Int)   -- ^ Generated tensor---- If only one upper index is given, generate a SimpleFinite tensor with upper index-randomInt ([u],[s]) ([],[]) distr = do-    gen <- MWC.createSystemRandom-    component <- sequence $ Boxed.generate s $ \_ -> genDiscreteVar distr gen-    return $ SimpleFinite (Contravariant s [u]) component---- If only one lower index is given, generate a SimpleFinite tensor with lower index-randomInt ([],[]) ([d],[s]) distr = do-    gen <- MWC.createSystemRandom-    component <- sequence $ Boxed.generate s $ \_ -> genDiscreteVar distr gen-    return $ SimpleFinite (Covariant s [d]) component---- If many indices are given, first generate upper indices recursively from indices list-randomInt (u:us,s:size) d distr = do-  tensors <- sequence $ Boxed.generate s $ \_ -> randomInt (us,size) d distr-  return $ FiniteTensor (Contravariant s [u]) tensors---- After upper indices, generate lower indices recursively from indices list-randomInt u (d:ds,s:size) distr = do-  tensors <- sequence $ Boxed.generate s $ \_ -> randomInt u (ds,size) distr-  return $ FiniteTensor (Covariant s [d]) tensors---- If there are indices without size or sizes without names, throw an error-randomInt us ds _ = return $ Err $ invalidIndices us ds--{-| Generate tensor with random real components with given probability distribution and given seed.-The tensor is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDoubleSeed #-}-randomDoubleSeed :: (-    ContGen d, PrimMonad m-  ) => (String,[Int])    -- ^ Upper indices names (one character per index) and its sizes-    -> (String,[Int])    -- ^ Lower indices names (one character per index) and its sizes-    -> d                 -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> Int               -- ^ Randomness seed-    -> m (Tensor Double) -- ^ Generated tensor---- If only one upper index is given, generate a SimpleFinite tensor with upper index-randomDoubleSeed ([u],[s]) ([],[]) distr seed = do-    gen <- MWC.initialize (Boxed.singleton $ fromIntegral seed)-    component <- sequence $ Boxed.generate s $ \_ -> genContVar distr gen-    return $ SimpleFinite (Contravariant s [u]) component---- If only one lower index is given, generate a SimpleFinite tensor with lower index-randomDoubleSeed ([],[]) ([d],[s]) distr seed = do-    gen <- MWC.initialize (Boxed.singleton $ fromIntegral seed)-    component <- sequence $ Boxed.generate s $ \_ -> genContVar distr gen-    return $ SimpleFinite (Covariant s [d]) component---- If many indices are given, first generate upper indices recursively from indices list-randomDoubleSeed (u:us,s:size) d distr seed = do-  tensors <- sequence $ Boxed.generate s $ \_ -> randomDoubleSeed (us,size) d distr seed-  return $ FiniteTensor (Contravariant s [u]) tensors---- After upper indices, generate lower indices recursively from indices list-randomDoubleSeed u (d:ds,s:size) distr seed = do-  tensors <- sequence $ Boxed.generate s $ \_ -> randomDoubleSeed u (ds,size) distr seed-  return $ FiniteTensor (Covariant s [d]) tensors---- If there are indices without size or sizes without names, throw an error-randomDoubleSeed us ds _ _ = return $ Err $ invalidIndices us ds--{-| Generate tensor with random integer components with given probability distribution and given seed.-The tensor is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomIntSeed #-}-randomIntSeed :: (-    DiscreteGen d, PrimMonad m-  ) => (String,[Int])    -- ^ Index name (one character)-    -> (String,[Int])    -- ^ Number of elements-    -> d                 -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> Int               -- ^ Randomness seed-    -> m (Tensor Int)    -- ^ Generated tensor---- If only one upper index is given, generate a SimpleFinite tensor with upper index-randomIntSeed ([u],[s]) ([],[]) distr seed = do-    gen <- MWC.initialize (Boxed.singleton $ fromIntegral seed)-    component <- sequence $ Boxed.generate s $ \_ -> genDiscreteVar distr gen-    return $ SimpleFinite (Contravariant s [u]) component---- If only one lower index is given, generate a SimpleFinite tensor with lower index-randomIntSeed ([],[]) ([d],[s]) distr seed = do-    gen <- MWC.initialize (Boxed.singleton $ fromIntegral seed)-    component <- sequence $ Boxed.generate s $ \_ -> genDiscreteVar distr gen-    return $ SimpleFinite (Covariant s [d]) component---- If many indices are given, first generate upper indices recursively from indices list-randomIntSeed (u:us,s:size) d distr seed = do-  tensors <- sequence $ Boxed.generate s $ \_ -> randomIntSeed (us,size) d distr seed-  return $ FiniteTensor (Contravariant s [u]) tensors---- After upper indices, generate lower indices recursively from indices list-randomIntSeed u (d:ds,s:size) distr seed = do-  tensors <- sequence $ Boxed.generate s $ \_ -> randomIntSeed u (ds,size) distr seed-  return $ FiniteTensor (Covariant s [d]) tensors---- If there are indices without size or sizes without names, throw an error-randomIntSeed us ds _ _ = return $ Err $ invalidIndices us ds+{-|
+Module      : Multilinear.Tensor
+Description : Tensors constructors (finitely- or infinitely-dimensional)
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+- This module provides convenient constructors that generate a arbitrary finitely- or infinitely-dimensional tensors. 
+- Finitely-dimensional tensors provide much greater performance than inifitely-dimensional
+
+-}
+
+module Multilinear.Tensor (
+  -- * Generators
+  Multilinear.Tensor.fromIndices, 
+  Multilinear.Tensor.generate,
+  Multilinear.Tensor.const,
+  Multilinear.Tensor.randomDouble, 
+  Multilinear.Tensor.randomDoubleSeed,
+  Multilinear.Tensor.randomInt, 
+  Multilinear.Tensor.randomIntSeed
+) where
+
+import           Control.Monad.Primitive
+import qualified Data.Vector                as Boxed
+import           Multilinear.Generic
+import           Multilinear.Index.Finite   as Finite
+import           Statistics.Distribution
+import qualified System.Random.MWC          as MWC
+
+invalidIndices :: (String, [Int]) -> (String, [Int]) -> String
+invalidIndices us ds = "Indices and its sizes incompatible, upper indices: " ++ show us ++", lower indices: " ++ show ds
+
+{-| Generate tensor as functions of its indices -}
+{-# INLINE fromIndices #-}
+fromIndices :: (
+    Num a
+    ) => (String,[Int])          -- ^ Upper indices names (one character per index) and its sizes
+      -> (String,[Int])          -- ^ Lower indices names (one character per index) and its sizes
+      -> ([Int] -> [Int] -> a)   -- ^ Generator function (f [u1,u2,...] [d1,d2,...] returns a tensor element at t [u1,u2,...] [d1,d2,...])
+      -> Tensor a                -- ^ Generated tensor
+
+-- If only one upper index is given, generate a SimpleFinite tensor with upper index
+fromIndices ([u],[s]) ([],[]) f = 
+  SimpleFinite (Contravariant s [u]) $ Boxed.generate s $ \x -> f [x] []
+
+-- If only one lower index is given, generate a SimpleFinite tensor with lower index
+fromIndices ([],[]) ([d],[s]) f = 
+  SimpleFinite (Covariant s [d]) $ Boxed.generate s $ \x -> f [] [x]
+
+-- If many indices are given, first generate upper indices recursively from indices list
+fromIndices (u:us,s:size) d f =
+    FiniteTensor (Contravariant s [u]) $ Boxed.generate s (\x -> fromIndices (us,size) d (\uss dss -> f (x:uss) dss) )
+
+-- After upper indices, generate lower indices recursively from indices list
+fromIndices u (d:ds,s:size) f =
+    FiniteTensor (Covariant s [d]) $ Boxed.generate s (\x -> fromIndices u (ds,size) (\uss dss -> f uss (x:dss)) )
+
+-- If there are indices without size or sizes without names, throw an error
+fromIndices us ds _ = Err $ invalidIndices us ds
+
+{-| Generate tensor composed of other tensors -}
+{-# INLINE generate #-}
+generate :: (
+    Num a
+    ) => (String,[Int])                 -- ^ Upper indices names (one character per index) and its sizes
+      -> (String,[Int])                 -- ^ Lower indices names (one character per index) and its sizes
+      -> ([Int] -> [Int] -> Tensor a)   -- ^ Generator function (f [u1,u2,...] [d1,d2,...] returns a tensor element at t [u1,u2,...] [d1,d2,...])
+      -> Tensor a                       -- ^ Generated tensor
+
+-- If no indices are given, generate a tensor by using generator function
+generate ([],[]) ([],[]) f = f [] []
+
+-- If many indices are given, first generate upper indices recursively from indices list
+generate (u:us,s:size) d f =
+    FiniteTensor (Contravariant s [u]) $ Boxed.generate s (\x -> generate (us,size) d (\uss dss -> f (x:uss) dss) )
+
+-- After upper indices, generate lower indices recursively from indices list
+generate u (d:ds,s:size) f =
+    FiniteTensor (Covariant s [d]) $ Boxed.generate s (\x -> generate u (ds,size) (\uss dss -> f uss (x:dss)) )
+
+-- If there are indices without size or sizes without names, throw an error
+generate us ds _ = Err $ invalidIndices us ds
+
+{-| Generate tensor with all components equal to @v@ -}
+{-# INLINE Multilinear.Tensor.const #-}
+const :: (
+    Num a
+    ) => (String,[Int]) -- ^ Upper indices names (one character per index) and its sizes
+      -> (String,[Int]) -- ^ Lower indices names (one character per index) and its sizes
+      -> a              -- ^ Tensor elements value
+      -> Tensor a       -- ^ Generated tensor
+
+-- If only one upper index is given, generate a SimpleFinite tensor with upper index
+const ([u],[s]) ([],[]) v =
+  SimpleFinite (Contravariant s [u]) $ Boxed.replicate s v
+
+-- If only ine lower index is given, generate a SimpleFinite tensor with lower index
+const ([],[]) ([d],[s]) v =
+  SimpleFinite (Covariant s [d]) $ Boxed.replicate s v
+
+-- If many indices are given, first generate upper indices recursively from indices list
+const (u:us,s:size) d v =
+    FiniteTensor (Contravariant s [u]) $ Boxed.replicate (fromIntegral s) $ Multilinear.Tensor.const (us,size) d v
+
+-- After upper indices, generate lower indices recursively from indices list
+const u (d:ds,s:size) v =
+    FiniteTensor (Covariant s [d]) $ Boxed.replicate (fromIntegral s) $ Multilinear.Tensor.const u (ds,size) v
+
+-- If there are indices without size or sizes without names, throw an error
+const us ds _ = Err $ invalidIndices us ds
+
+{-| Generate tensor with random real components with given probability distribution.
+The tensor is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDouble #-}
+randomDouble :: (
+    ContGen d
+  ) => (String,[Int])      -- ^ Upper indices names (one character per index) and its sizes
+    -> (String,[Int])      -- ^ Lower indices names (one character per index) and its sizes
+    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Double)  -- ^ Generated tensor
+
+-- If only one upper index is given, generate a SimpleFinite tensor with upper index
+randomDouble ([u],[s]) ([],[]) distr = do
+    gen <- MWC.createSystemRandom
+    component <- sequence $ Boxed.generate s $ \_ -> genContVar distr gen
+    return $ SimpleFinite (Contravariant s [u]) component
+
+-- If only one lower index is given, generate a SimpleFinite tensor with lower index
+randomDouble ([],[]) ([d],[s]) distr = do
+    gen <- MWC.createSystemRandom
+    component <- sequence $ Boxed.generate s $ \_ -> genContVar distr gen
+    return $ SimpleFinite (Covariant s [d]) component
+
+-- If many indices are given, first generate upper indices recursively from indices list
+randomDouble (u:us,s:size) d distr = do
+  tensors <- sequence $ Boxed.generate s $ \_ -> randomDouble (us,size) d distr
+  return $ FiniteTensor (Contravariant s [u]) tensors
+
+-- After upper indices, generate lower indices recursively from indices list
+randomDouble u (d:ds,s:size) distr = do
+  tensors <- sequence $ Boxed.generate s $ \_ -> randomDouble u (ds,size) distr
+  return $ FiniteTensor (Covariant s [d]) tensors
+
+-- If there are indices without size or sizes without names, throw an error
+randomDouble us ds _ = return $ Err $ invalidIndices us ds
+
+{-| Generate tensor with random integer components with given probability distribution.
+The tensor is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomInt #-}
+randomInt :: (
+    DiscreteGen d
+  ) => (String,[Int])    -- ^ Upper indices names (one character per index) and its sizes
+    -> (String,[Int])    -- ^ Lower indices names (one character per index) and its sizes
+    -> d                 -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Int)   -- ^ Generated tensor
+
+-- If only one upper index is given, generate a SimpleFinite tensor with upper index
+randomInt ([u],[s]) ([],[]) distr = do
+    gen <- MWC.createSystemRandom
+    component <- sequence $ Boxed.generate s $ \_ -> genDiscreteVar distr gen
+    return $ SimpleFinite (Contravariant s [u]) component
+
+-- If only one lower index is given, generate a SimpleFinite tensor with lower index
+randomInt ([],[]) ([d],[s]) distr = do
+    gen <- MWC.createSystemRandom
+    component <- sequence $ Boxed.generate s $ \_ -> genDiscreteVar distr gen
+    return $ SimpleFinite (Covariant s [d]) component
+
+-- If many indices are given, first generate upper indices recursively from indices list
+randomInt (u:us,s:size) d distr = do
+  tensors <- sequence $ Boxed.generate s $ \_ -> randomInt (us,size) d distr
+  return $ FiniteTensor (Contravariant s [u]) tensors
+
+-- After upper indices, generate lower indices recursively from indices list
+randomInt u (d:ds,s:size) distr = do
+  tensors <- sequence $ Boxed.generate s $ \_ -> randomInt u (ds,size) distr
+  return $ FiniteTensor (Covariant s [d]) tensors
+
+-- If there are indices without size or sizes without names, throw an error
+randomInt us ds _ = return $ Err $ invalidIndices us ds
+
+{-| Generate tensor with random real components with given probability distribution and given seed.
+The tensor is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDoubleSeed #-}
+randomDoubleSeed :: (
+    ContGen d, PrimMonad m
+  ) => (String,[Int])    -- ^ Upper indices names (one character per index) and its sizes
+    -> (String,[Int])    -- ^ Lower indices names (one character per index) and its sizes
+    -> d                 -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> Int               -- ^ Randomness seed
+    -> m (Tensor Double) -- ^ Generated tensor
+
+-- If only one upper index is given, generate a SimpleFinite tensor with upper index
+randomDoubleSeed ([u],[s]) ([],[]) distr seed = do
+    gen <- MWC.initialize (Boxed.singleton $ fromIntegral seed)
+    component <- sequence $ Boxed.generate s $ \_ -> genContVar distr gen
+    return $ SimpleFinite (Contravariant s [u]) component
+
+-- If only one lower index is given, generate a SimpleFinite tensor with lower index
+randomDoubleSeed ([],[]) ([d],[s]) distr seed = do
+    gen <- MWC.initialize (Boxed.singleton $ fromIntegral seed)
+    component <- sequence $ Boxed.generate s $ \_ -> genContVar distr gen
+    return $ SimpleFinite (Covariant s [d]) component
+
+-- If many indices are given, first generate upper indices recursively from indices list
+randomDoubleSeed (u:us,s:size) d distr seed = do
+  tensors <- sequence $ Boxed.generate s $ \_ -> randomDoubleSeed (us,size) d distr seed
+  return $ FiniteTensor (Contravariant s [u]) tensors
+
+-- After upper indices, generate lower indices recursively from indices list
+randomDoubleSeed u (d:ds,s:size) distr seed = do
+  tensors <- sequence $ Boxed.generate s $ \_ -> randomDoubleSeed u (ds,size) distr seed
+  return $ FiniteTensor (Covariant s [d]) tensors
+
+-- If there are indices without size or sizes without names, throw an error
+randomDoubleSeed us ds _ _ = return $ Err $ invalidIndices us ds
+
+{-| Generate tensor with random integer components with given probability distribution and given seed.
+The tensor is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomIntSeed #-}
+randomIntSeed :: (
+    DiscreteGen d, PrimMonad m
+  ) => (String,[Int])    -- ^ Index name (one character)
+    -> (String,[Int])    -- ^ Number of elements
+    -> d                 -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> Int               -- ^ Randomness seed
+    -> m (Tensor Int)    -- ^ Generated tensor
+
+-- If only one upper index is given, generate a SimpleFinite tensor with upper index
+randomIntSeed ([u],[s]) ([],[]) distr seed = do
+    gen <- MWC.initialize (Boxed.singleton $ fromIntegral seed)
+    component <- sequence $ Boxed.generate s $ \_ -> genDiscreteVar distr gen
+    return $ SimpleFinite (Contravariant s [u]) component
+
+-- If only one lower index is given, generate a SimpleFinite tensor with lower index
+randomIntSeed ([],[]) ([d],[s]) distr seed = do
+    gen <- MWC.initialize (Boxed.singleton $ fromIntegral seed)
+    component <- sequence $ Boxed.generate s $ \_ -> genDiscreteVar distr gen
+    return $ SimpleFinite (Covariant s [d]) component
+
+-- If many indices are given, first generate upper indices recursively from indices list
+randomIntSeed (u:us,s:size) d distr seed = do
+  tensors <- sequence $ Boxed.generate s $ \_ -> randomIntSeed (us,size) d distr seed
+  return $ FiniteTensor (Contravariant s [u]) tensors
+
+-- After upper indices, generate lower indices recursively from indices list
+randomIntSeed u (d:ds,s:size) distr seed = do
+  tensors <- sequence $ Boxed.generate s $ \_ -> randomIntSeed u (ds,size) distr seed
+  return $ FiniteTensor (Covariant s [d]) tensors
+
+-- If there are indices without size or sizes without names, throw an error
+randomIntSeed us ds _ _ = return $ Err $ invalidIndices us ds
src/Multilinear/Vector.hs view
@@ -1,142 +1,142 @@-{-|-Module      : Multilinear.Vector-Description : Vector constructors (finitely- or infinitely-dimensional)-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX--- This module provides convenient constructors that generates a vector (tensor with one upper index) of finite or infinite size. -- Finitely-dimensional vectors provide much greater performance than infinitely-dimensional ---}--module Multilinear.Vector (-  -- * Generators-  Multilinear.Vector.fromIndices, -  Multilinear.Vector.const,-  Multilinear.Vector.randomDouble, -  Multilinear.Vector.randomDoubleSeed,-  Multilinear.Vector.randomInt, -  Multilinear.Vector.randomIntSeed-) where--import           Control.Monad.Primitive-import           Multilinear.Generic-import           Multilinear.Tensor         as Tensor-import           Statistics.Distribution--invalidIndices :: String-invalidIndices = "Indices and its sizes not compatible with structure of vector!"--{-| Generate vector as function of indices -}-{-# INLINE fromIndices #-}-fromIndices :: (-    Num a-  ) => String        -- ^ Index name (one character)-    -> Int           -- ^ Number of elements-    -> (Int -> a)    -- ^ Generator function - returns a vector component at index @i@-    -> Tensor a      -- ^ Generated vector--fromIndices [i] s f = Tensor.fromIndices ([i],[s]) ([],[]) $ \[x] [] -> f x-fromIndices _ _ _ = Err invalidIndices--{-| Generate vector with all components equal to some @v@ -}-{-# INLINE Multilinear.Vector.const #-}-const :: (-    Num a-  ) => String      -- ^ Index name (one character)-    -> Int         -- ^ Number of elements-    -> a           -- ^ Value of each element-    -> Tensor a    -- ^ Generated vector--const [i] s = Tensor.const ([i],[s]) ([],[])-const _ _ = \_ -> Err invalidIndices--{-| Generate vector with random real components with given probability distribution.-The vector is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDouble #-}-randomDouble :: (-    ContGen d-  ) => String              -- ^ Index name (one character)-    -> Int                 -- ^ Number of elements-    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Double)  -- ^ Generated vector--randomDouble [i] s = Tensor.randomDouble ([i],[s]) ([],[])-randomDouble _ _ = \_ -> return $ Err invalidIndices--{-| Generate vector with random integer components with given probability distribution.-The vector is wrapped in the IO monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomInt #-}-randomInt :: (-    DiscreteGen d-  ) => String           -- ^ Index name (one character)-    -> Int              -- ^ Number of elements-    -> d                -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> IO (Tensor Int)  -- ^ Generated vector--randomInt [i] s = Tensor.randomInt ([i],[s]) ([],[])-randomInt _ _ = \_ -> return $ Err invalidIndices--{-| Generate vector with random real components with given probability distribution and given seed.-The vector is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Beta : "Statistics.Distribution.BetaDistribution" -}-{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}-{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}-{-| - Exponential : "Statistics.Distribution.Exponential" -}-{-| - Gamma : "Statistics.Distribution.Gamma" -}-{-| - Normal : "Statistics.Distribution.Normal" -}-{-| - StudentT : "Statistics.Distribution.StudentT" -}-{-| - Uniform : "Statistics.Distribution.Uniform" -}-{-| - F : "Statistics.Distribution.FDistribution" -}-{-| - Laplace : "Statistics.Distribution.Laplace" -}-{-# INLINE randomDoubleSeed #-}-randomDoubleSeed :: (-    ContGen d, PrimMonad m-  ) => String             -- ^ Index name (one character)-    -> Int                -- ^ Number of elements-    -> d                  -- ^ Continuous probability distribution (as from "Statistics.Distribution")-    -> Int                -- ^ Randomness seed-    -> m (Tensor Double)  -- ^ Generated vector--randomDoubleSeed [i] s = Tensor.randomDoubleSeed ([i],[s]) ([],[])-randomDoubleSeed _ _ = \_ _ -> return $ Err invalidIndices--{-| Generate vector with random integer components with given probability distribution and given seed.-The vector is wrapped in a monad. -}-{-| Available probability distributions: -}-{-| - Binomial : "Statistics.Distribution.Binomial" -}-{-| - Poisson : "Statistics.Distribution.Poisson" -}-{-| - Geometric : "Statistics.Distribution.Geometric" -}-{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}-{-# INLINE randomIntSeed #-}-randomIntSeed :: (-    DiscreteGen d, PrimMonad m-  ) => String          -- ^ Index name (one character)-    -> Int             -- ^ Number of elements-    -> d               -- ^ Discrete probability distribution (as from "Statistics.Distribution")-    -> Int             -- ^ Randomness seed-    -> m (Tensor Int)  -- ^ Generated vector--randomIntSeed [i] s = Tensor.randomIntSeed ([i],[s]) ([],[])-randomIntSeed _ _ = \_ _ -> return $ Err invalidIndices-+{-|
+Module      : Multilinear.Vector
+Description : Vector constructors (finitely- or infinitely-dimensional)
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+- This module provides convenient constructors that generates a vector (tensor with one upper index) of finite or infinite size. 
+- Finitely-dimensional vectors provide much greater performance than infinitely-dimensional 
+
+-}
+
+module Multilinear.Vector (
+  -- * Generators
+  Multilinear.Vector.fromIndices, 
+  Multilinear.Vector.const,
+  Multilinear.Vector.randomDouble, 
+  Multilinear.Vector.randomDoubleSeed,
+  Multilinear.Vector.randomInt, 
+  Multilinear.Vector.randomIntSeed
+) where
+
+import           Control.Monad.Primitive
+import           Multilinear.Generic
+import           Multilinear.Tensor         as Tensor
+import           Statistics.Distribution
+
+invalidIndices :: String
+invalidIndices = "Indices and its sizes not compatible with structure of vector!"
+
+{-| Generate vector as function of indices -}
+{-# INLINE fromIndices #-}
+fromIndices :: (
+    Num a
+  ) => String        -- ^ Index name (one character)
+    -> Int           -- ^ Number of elements
+    -> (Int -> a)    -- ^ Generator function - returns a vector component at index @i@
+    -> Tensor a      -- ^ Generated vector
+
+fromIndices [i] s f = Tensor.fromIndices ([i],[s]) ([],[]) $ \[x] [] -> f x
+fromIndices _ _ _ = Err invalidIndices
+
+{-| Generate vector with all components equal to some @v@ -}
+{-# INLINE Multilinear.Vector.const #-}
+const :: (
+    Num a
+  ) => String      -- ^ Index name (one character)
+    -> Int         -- ^ Number of elements
+    -> a           -- ^ Value of each element
+    -> Tensor a    -- ^ Generated vector
+
+const [i] s = Tensor.const ([i],[s]) ([],[])
+const _ _ = \_ -> Err invalidIndices
+
+{-| Generate vector with random real components with given probability distribution.
+The vector is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDouble #-}
+randomDouble :: (
+    ContGen d
+  ) => String              -- ^ Index name (one character)
+    -> Int                 -- ^ Number of elements
+    -> d                   -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Double)  -- ^ Generated vector
+
+randomDouble [i] s = Tensor.randomDouble ([i],[s]) ([],[])
+randomDouble _ _ = \_ -> return $ Err invalidIndices
+
+{-| Generate vector with random integer components with given probability distribution.
+The vector is wrapped in the IO monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomInt #-}
+randomInt :: (
+    DiscreteGen d
+  ) => String           -- ^ Index name (one character)
+    -> Int              -- ^ Number of elements
+    -> d                -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> IO (Tensor Int)  -- ^ Generated vector
+
+randomInt [i] s = Tensor.randomInt ([i],[s]) ([],[])
+randomInt _ _ = \_ -> return $ Err invalidIndices
+
+{-| Generate vector with random real components with given probability distribution and given seed.
+The vector is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Beta : "Statistics.Distribution.BetaDistribution" -}
+{-| - Cauchy : "Statistics.Distribution.CauchyLorentz" -}
+{-| - Chi-squared : "Statistics.Distribution.ChiSquared" -}
+{-| - Exponential : "Statistics.Distribution.Exponential" -}
+{-| - Gamma : "Statistics.Distribution.Gamma" -}
+{-| - Normal : "Statistics.Distribution.Normal" -}
+{-| - StudentT : "Statistics.Distribution.StudentT" -}
+{-| - Uniform : "Statistics.Distribution.Uniform" -}
+{-| - F : "Statistics.Distribution.FDistribution" -}
+{-| - Laplace : "Statistics.Distribution.Laplace" -}
+{-# INLINE randomDoubleSeed #-}
+randomDoubleSeed :: (
+    ContGen d, PrimMonad m
+  ) => String             -- ^ Index name (one character)
+    -> Int                -- ^ Number of elements
+    -> d                  -- ^ Continuous probability distribution (as from "Statistics.Distribution")
+    -> Int                -- ^ Randomness seed
+    -> m (Tensor Double)  -- ^ Generated vector
+
+randomDoubleSeed [i] s = Tensor.randomDoubleSeed ([i],[s]) ([],[])
+randomDoubleSeed _ _ = \_ _ -> return $ Err invalidIndices
+
+{-| Generate vector with random integer components with given probability distribution and given seed.
+The vector is wrapped in a monad. -}
+{-| Available probability distributions: -}
+{-| - Binomial : "Statistics.Distribution.Binomial" -}
+{-| - Poisson : "Statistics.Distribution.Poisson" -}
+{-| - Geometric : "Statistics.Distribution.Geometric" -}
+{-| - Hypergeometric: "Statistics.Distribution.Hypergeometric" -}
+{-# INLINE randomIntSeed #-}
+randomIntSeed :: (
+    DiscreteGen d, PrimMonad m
+  ) => String          -- ^ Index name (one character)
+    -> Int             -- ^ Number of elements
+    -> d               -- ^ Discrete probability distribution (as from "Statistics.Distribution")
+    -> Int             -- ^ Randomness seed
+    -> m (Tensor Int)  -- ^ Generated vector
+
+randomIntSeed [i] s = Tensor.randomIntSeed ([i],[s]) ([],[])
+randomIntSeed _ _ = \_ _ -> return $ Err invalidIndices
+
test/Spec.hs view
@@ -1,35 +1,35 @@-{-|-Module      : Main (Spec.hs)-Description : Tests of Multilinear library-Copyright   : (c) Artur M. Brodzki, 2018-License     : BSD3-Maintainer  : artur@brodzki.org-Stability   : experimental-Portability : Windows/POSIX---}--module Main (-  main-) where--import           Control.DeepSeq-import           Criterion.Main-import           Criterion.Measurement               as Meas-import           Criterion.Types-import           Multilinear.Generic-import qualified Multilinear.Matrix                  as Matrix--m1 :: Tensor Double-m1 = Matrix.fromIndices "ij" 100 100 $ \i j -> fromIntegral (2*i) - exp (fromIntegral j)--m2 :: Tensor Double-m2 = Matrix.fromIndices "jk" 100 100 $ \i j -> sin (fromIntegral i) + cos (fromIntegral j)--main :: IO ()-main = do-  putStrLn "Two matrices 1000x1000 multiplying..."-  (meas,_)  <- Meas.measure ( nfIO $ (m1 * m2) `deepseq` putStrLn "End!" ) 1-  putStrLn $ "Measured time: " ++ show (measCpuTime meas) ++ " s."-  return ()-+{-|
+Module      : Main (Spec.hs)
+Description : Tests of Multilinear library
+Copyright   : (c) Artur M. Brodzki, 2018
+License     : BSD3
+Maintainer  : artur@brodzki.org
+Stability   : experimental
+Portability : Windows/POSIX
+
+-}
+
+module Main (
+  main
+) where
+
+import           Control.DeepSeq
+import           Criterion.Main
+import           Criterion.Measurement               as Meas
+import           Criterion.Types
+import           Multilinear.Generic
+import qualified Multilinear.Matrix                  as Matrix
+
+m1 :: Tensor Double
+m1 = Matrix.fromIndices "ij" 100 100 $ \i j -> fromIntegral (2*i) - exp (fromIntegral j)
+
+m2 :: Tensor Double
+m2 = Matrix.fromIndices "jk" 100 100 $ \i j -> sin (fromIntegral i) + cos (fromIntegral j)
+
+main :: IO ()
+main = do
+  putStrLn "Two matrices 1000x1000 multiplying..."
+  (meas,_)  <- Meas.measure ( nfIO $ (m1 * m2) `deepseq` putStrLn "End!" ) 1
+  putStrLn $ "Measured time: " ++ show (measCpuTime meas) ++ " s."
+  return ()
+