diff --git a/deps/src/CMakeLists.txt b/deps/src/CMakeLists.txt new file mode 100644 index 000000000..61be461cf --- /dev/null +++ b/deps/src/CMakeLists.txt @@ -0,0 +1,53 @@ +cmake_minimum_required(VERSION 3.01) + +# I don't know why I need the following, but it works +if(POLICY CMP0025) + cmake_policy(SET CMP0025 NEW) +endif() + +project(libsingular_julia) + +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") + +find_package(JlCxx REQUIRED) + +include(CheckCXXCompilerFlag) + +set(CMAKE_CXX_STANDARD 14) + +set(JLSINGULAR_TARGET singular_julia) + +# avoid gcc 9 internal compiler error, +# see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90998 +if(CMAKE_COMPILER_IS_GNUCC AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 9.0 + AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9.3) + SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-conversion" ) +endif() + +# to avoid lib64 dirs as binarybuilder uses lib everywhere +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") +set(CMAKE_INSTALL_LIBDIR "lib") + +get_target_property(JlCxx_location JlCxx::cxxwrap_julia LOCATION) +get_filename_component(JlCxx_location ${JlCxx_location} DIRECTORY) +set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib;${JlCxx_location}") + +message(STATUS "Found JlCxx at ${JlCxx_location}") + +include_directories(${CMAKE_INSTALL_PREFIX}) +include_directories(${Singular_PREFIX}/include/singular) + +SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g ${extra_cppflags} -I${CMAKE_INSTALL_PREFIX}/include -I${Singular_PREFIX}/include/" ) +SET( CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -v ${extra_ldflags} -L${CMAKE_INSTALL_PREFIX}/lib -Wl,-rpath,${CMAKE_INSTALL_PREFIX}/lib -L${Singular_PREFIX}/lib -Wl,-rpath,${Singular_PREFIX}/lib" ) + + +add_library(${JLSINGULAR_TARGET} SHARED singular.cpp rings.cpp coeffs.cpp ideals.cpp matrices.cpp caller.cpp coeff_rings.cpp threading.cpp) + +target_link_libraries(${JLSINGULAR_TARGET} JlCxx::cxxwrap_julia -lSingular -lpolys -lsingular_resources -lfactory -lomalloc -ldl -lgmp) + +install(TARGETS + ${JLSINGULAR_TARGET} +ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} +LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) diff --git a/deps/src/LICENSE.md b/deps/src/LICENSE.md new file mode 100644 index 000000000..7f74e1971 --- /dev/null +++ b/deps/src/LICENSE.md @@ -0,0 +1,674 @@ +############################################################################### + + IMPORTANT NOTE + + The Singular.jl package is licensed OVERALL under the GNU Public License, + Version 3.0+. See below for full details of the GPL license. + +############################################################################### + +All INDIVIDUAL Julia (.jl) files in the Singular.jl package are licensed +under the BSD license, unless explicitly noted in the file: + +> Copyright (c) 2015-2016: Oleksandr Motsak. +> Copyright (c) 2016: William Hart. +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions are met: +> +> * Redistributions of source code must retain the above copyright notice, this +> list of conditions and the following disclaimer. +> +> * Redistributions in binary form must reproduce the above copyright notice, +> this list of conditions and the following disclaimer in the documentation +> and/or other materials provided with the distribution. +> +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +> + + +> Copyright (c) 2015-2016: Oleksandr Motsak. +> Copyright (c) 2016: William Hart. +> This program is free software: you can 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. +> +> +> GNU GENERAL PUBLIC LICENSE +> Version 3, 29 June 2007 +> +> Copyright (C) 2007 Free Software Foundation, Inc. +> Everyone is permitted to copy and distribute verbatim copies +> of this license document, but changing it is not allowed. +> +> Preamble +> +> The GNU 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 +> diff --git a/deps/src/README.md b/deps/src/README.md new file mode 100644 index 000000000..f0aeda51f --- /dev/null +++ b/deps/src/README.md @@ -0,0 +1,82 @@ +# libsingular-julia + +This is the C++ library accompanying [Singular.jl](https://github.com/oscar-system/Singular.jl). +It implements the C++ interface from julia to Singular using [CxxWrap.jl](https://github.com/JuliaInterop/CxxWrap.jl) and [libcxxwrap-julia](https://github.com/JuliaInterop/libcxxwrap-julia). + +This library is compiled into a Julia artifact and shipped to the user via +the Julia JLL package +[libsingular_julia_jll](https://github.com/JuliaBinaryWrappers/libsingular_julia_jll.jl). +This JLL package in turn is generated from the sources in this repository and +the build recipe at +. + + +## Quick way to test changes in here + +To test changes you make to the C++ code here, the quickest way is to use the +`run.jl` script bundled in this repository. As a prerequisite, you need a +working C++ compiler and of course Julia. + +Start Julia from this repository as follows: + + julia --project=. run.jl + +This will install a few required Julia packages then build all C++ code, and +finally start a Julia session with an artifact override in place which ensures +that libsingular_julia_jll picks up the copy of the C++ code that was just +compiled. + +To verify the override works, check `libsingular_julia_jll.artifact_dir`; it +should point at a subdirectory of the current directory. + +You can then use the Julia package manager to install or dev `Singular.jl`, +and run its test suite or perform other tests. + + +## Building + +Compiling `libsingular-julia` from source requires a C++ enabled compiler. + +The easiest way to build it is to execute the Julia script `build.jl` (which +in turn is also used by `run.jl`). For this you need to execute it in a Julia +environment in which `Singular_jll` and `CxxWrap` are installed. + +Alternatively, you can also link it against your own `libcxxwrap-julia` +installation and a Singular installation, but this is more work; an +incantation like the following will do it: + +```bash +git clone https://github.com/oscar-system/libsingular-julia \ +cmake -DJulia_PREFIX=/home/user/path/to/julia \ + -DSingular_PREFIX=/home/user/path/to/singular + -DCMAKE_INSTALL_PREFIX=home/user/prefix/for/libsingular-julia \ + -DJlCxx_DIR=/home/user/path/to/libcxxwrap-julia/lib/cmake/JlCxx \ + -DCMAKE_BUILD_TYPE=Release \ + -S libsingular-julia -B build \ + +cmake --build build --config Release --target install -- -j${nproc} +``` + + +### Overriding the default artifacts for Singular.jl + +The `run.jl` script takes care of everything described below, but we document +it in case you need to do any of this manually for some reason. + +Put the following into `~/.julia/artifacts/Overrides.toml` to replace the `libsingular-julia` artifact: + +```toml +[ae4fbd8f-ecdb-54f8-bbce-35570499b30e] +libsingular_julia = "/home/user/prefix/for/libsingular-julia" +``` + +If you were using custom versions of `Singular` and/or `libcxxwrap-julia`, +then their directories used during the build need to be added as well, e.g.: + +```toml +[bcd08a7b-43d2-5ff7-b6d4-c458787f915c] +Singular = "/home/user/path/to/Singular" + +[3eaa8342-bff7-56a5-9981-c04077f7cee7] +libcxxwrap_julia = "/home/user/path/to/libcxxwrap-julia" +``` diff --git a/deps/src/build.jl b/deps/src/build.jl new file mode 100644 index 000000000..7dec05f43 --- /dev/null +++ b/deps/src/build.jl @@ -0,0 +1,46 @@ +import Singular_jll, CxxWrap, CMake +using Singular_jll.GMP_jll, Pkg.Artifacts + +# TODO: use ARGS to specify custom build dir? +builddir = "build" +installdir = abspath("install") +JlCxx_DIR = joinpath(CxxWrap.prefix_path(), "lib", "cmake", "JlCxx") + +# In Julia >= 1.6, there is a "fake" GMP_jll which does not include header files; +# see +function gmp_artifact_dir() + artifacts_toml = joinpath(dirname(dirname(Base.pathof(GMP_jll))), "StdlibArtifacts.toml") + + # If this file exists, it's a stdlib JLL and we must download the artifact ourselves + if isfile(artifacts_toml) + meta = artifact_meta("GMP", artifacts_toml) + hash = Base.SHA1(meta["git-tree-sha1"]) + if !artifact_exists(hash) + dl_info = first(meta["download"]) + download_artifact(hash, dl_info["url"], dl_info["sha256"]) + end + return artifact_path(hash) + end + + # Otherwise, we can just use the artifact directory given to us by GMP_jll + return GMP_jll.find_artifact_dir() +end + +const gmp_prefix = gmp_artifact_dir() +const singular_prefix = Singular_jll.artifact_dir + +rm(builddir; force=true, recursive=true) + +run(`$(CMake.cmake) + -DJulia_EXECUTABLE=$(joinpath(Sys.BINDIR, Base.julia_exename())) + -Dextra_cppflags=-I$(gmp_prefix)/include + -Dextra_ldflags=-L$(gmp_prefix)/lib + -DSingular_PREFIX=$(singular_prefix) + -DCMAKE_INSTALL_PREFIX=$(installdir) + -DJlCxx_DIR=$(JlCxx_DIR) + -DCMAKE_BUILD_TYPE=Release + -S . + -B $(builddir) +`) + +run(`$(CMake.cmake) --build $(builddir) --config Release --target install -- -j$(Sys.CPU_THREADS)`) diff --git a/deps/src/caller.cpp b/deps/src/caller.cpp new file mode 100644 index 000000000..6c3e1281c --- /dev/null +++ b/deps/src/caller.cpp @@ -0,0 +1,469 @@ +#include "caller.h" + +#include +#include +#include +#include +#include + +// Internal singular interpreter variable +extern int inerror; + +static jl_value_t * jl_int64_vector_type; +static jl_value_t * jl_int64_matrix_type; +static jl_value_t * jl_singular_number_type; +static jl_value_t * jl_singular_poly_type; +static jl_value_t * jl_singular_ring_type; +static jl_value_t * jl_singular_ideal_type; +static jl_value_t * jl_singular_matrix_type; +static jl_value_t * jl_singular_bigint_type; +static jl_value_t * jl_singular_bigintmat_type; +static jl_value_t * jl_singular_map_type; +static jl_value_t * jl_singular_resolution_type; +static jl_value_t * jl_singular_vector_type; + +static jl_value_t * get_type_mapper() +{ + // clang-format off + struct { int cmd; const char * name; } types[] = { + {BIGINT_CMD, "BIGINT_CMD"}, + {NUMBER_CMD, "NUMBER_CMD"}, + {RING_CMD, "RING_CMD"}, + {POLY_CMD, "POLY_CMD"}, + {IDEAL_CMD, "IDEAL_CMD"}, + {MATRIX_CMD, "MATRIX_CMD"}, + {INT_CMD, "INT_CMD"}, + {STRING_CMD, "STRING_CMD"}, + {LIST_CMD, "LIST_CMD"}, + {INTMAT_CMD, "INTMAT_CMD"}, + {BIGINTMAT_CMD, "BIGINTMAT_CMD"}, + {MAP_CMD, "MAP_CMD"}, + {RESOLUTION_CMD, "RESOLUTION_CMD"}, + {MODUL_CMD, "MODUL_CMD"}, + {VECTOR_CMD, "VECTOR_CMD"}, + {INTVEC_CMD, "INTVEC_CMD"}}; + // clang-format on + + jl_array_t * return_array = jl_alloc_array_1d( + jl_array_any_type, sizeof(types) / sizeof(types[0])); + JL_GC_PUSH1(&return_array); + for (int i = 0; i < sizeof(types) / sizeof(types[0]); i++) { + jl_array_t * current_return = jl_alloc_array_1d(jl_array_any_type, 2); + JL_GC_PUSH1(¤t_return); + jl_arrayset(current_return, jl_box_int64(types[i].cmd), 0); + jl_arrayset(current_return, + reinterpret_cast(jl_symbol(types[i].name)), + 1); + JL_GC_POP(); + jl_arrayset(return_array, + reinterpret_cast(current_return), i); + } + JL_GC_POP(); + return reinterpret_cast(return_array); +} + +static void initialize_jl_c_types(jl_value_t * module_value) +{ + jl_module_t * module = reinterpret_cast(module_value); + jl_int64_vector_type = + jl_apply_array_type((jl_value_t *)jl_int64_type, 1); + jl_int64_matrix_type = + jl_apply_array_type((jl_value_t *)jl_int64_type, 2); + jl_singular_number_type = jl_get_global(module, jl_symbol("number")); + jl_singular_poly_type = jl_get_global(module, jl_symbol("poly")); + jl_singular_ring_type = jl_get_global(module, jl_symbol("ring")); + jl_singular_ideal_type = jl_get_global(module, jl_symbol("ideal")); + jl_singular_matrix_type = jl_get_global(module, jl_symbol("ip_smatrix")); + jl_singular_bigint_type = + jl_get_global(module, jl_symbol("__mpz_struct")); + jl_singular_bigintmat_type = + jl_get_global(module, jl_symbol("bigintmat")); + jl_singular_map_type = jl_get_global(module, jl_symbol("sip_smap")); + jl_singular_resolution_type = + jl_get_global(module, jl_symbol("resolvente")); +} + +static inline void * get_ptr_from_cxxwrap_obj(jl_value_t * obj) +{ + return *reinterpret_cast(obj); +} + +// Safe way +// void* get_ptr_from_cxxwrap_obj(jl_value_t* obj){ +// return jl_unbox_voidpointer(jl_get_field(obj,"cpp_object")); +// } + +jl_value_t * intvec_to_jl_array(intvec * v) +{ + int size = v->length(); + jl_array_t * result = jl_alloc_array_1d(jl_int64_vector_type, size); + JL_GC_PUSH1(&result); + int * content = v->ivGetVec(); + for (int i = 0; i < size; i++) { + jl_arrayset(result, jl_box_int64(static_cast(content[i])), i); + } + JL_GC_POP(); + return reinterpret_cast(result); +} + +jl_value_t * intmat_to_jl_array(intvec * v) +{ + int rows = v->rows(); + int cols = v->cols(); + jl_array_t * result = jl_alloc_array_2d(jl_int64_matrix_type, rows, cols); + int64_t * result_ptr = reinterpret_cast jl_array_data(result); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + result_ptr[j + (i * cols)] = IMATELEM(*v, i, j); + } + } + return reinterpret_cast(result); +} + +void * jl_array_to_intvec(jl_value_t * array_val) +{ + jl_array_t * array = reinterpret_cast(array_val); + int size = jl_array_len(array); + intvec * result = new intvec(size); + int * result_content = result->ivGetVec(); + for (int i = 0; i < size; i++) { + jl_value_t * current_entry = jl_arrayref(array, i); + if (jl_is_int32(current_entry)) { + result_content[i] = + static_cast(jl_unbox_int32(current_entry)); + } + else if (jl_is_int64(current_entry)) { + int64_t current_int64 = jl_unbox_int64(current_entry); + result_content[i] = static_cast(current_int64); + if (result_content[i] != current_int64) { + jl_error("Input entry does not fit in 32 bit integer"); + } + } + } + return reinterpret_cast(result); +} + +void * jl_array_to_intmat(jl_value_t * array_val) +{ + jl_array_t * array = reinterpret_cast(array_val); + int rows = jl_array_dim(array, 0); + int cols = jl_array_dim(array, 1); + intvec * result = new intvec(rows, cols, 0); + if (!jl_subtype(reinterpret_cast(jl_typeof(array_val)), + reinterpret_cast(jl_int64_matrix_type))) { + jl_error("Input is not an Int64 matrix"); + } + int64_t * array_data = reinterpret_cast(jl_array_data(array)); + int * vec_data = result->ivGetVec(); + for (int i = 0; i < cols; i++) { + for (int j = 0; j < rows; j++) { + int64_t current_elem = array_data[j + (i * rows)]; + int current_elem_32 = static_cast(current_elem); + if (current_elem != current_elem_32) { + jl_error("Input entry does not fit in 32 bit integer"); + } + IMATELEM(*result, i + 1, j + 1) = current_elem_32; + } + } + return reinterpret_cast(result); +} + +lists jl_array_to_list_helper(jl_value_t * args_val, jl_value_t * types_val) +{ + jl_array_t * args = reinterpret_cast(args_val); + jl_array_t * types = reinterpret_cast(types_val); + int size = jl_array_len(args); + lists result = (lists)omAllocBin(slists_bin); + result->Init(size); + + for (int i = 0; i < size; i++) { + result->m[i].rtyp = static_cast(jl_unbox_int64(jl_arrayref(types, i))); + result->m[i].data = jl_unbox_voidpointer(jl_arrayref(args, i)); + } + return result; +} + +static void * get_ring_ref(ring r) +{ + // Since a call to a Singular library function destroys its arguments, + // the call will decrease the number of references to the ring. So we + // increase the reference count. + r->ref++; + return reinterpret_cast(r); +} + +static jl_value_t * copy_polyptr_to_void(poly p, ring r) +{ + poly p_copy = p_Copy(p, r); + return jl_box_voidpointer(reinterpret_cast(p_copy)); +} + +static jl_value_t * copy_idealptr_to_void(ideal i, ring r) +{ + ideal i_copy = id_Copy(i, r); + return jl_box_voidpointer(reinterpret_cast(i_copy)); +} + +static jl_value_t * copy_bigintmatptr_to_void(bigintmat * m) +{ + bigintmat * m_copy = new bigintmat(m); + return jl_box_voidpointer(reinterpret_cast(m_copy)); +} + +static void * copy_string_to_void(std::string s) +{ + return reinterpret_cast(omStrDup(s.c_str())); +} + +bool translate_singular_type(jl_value_t * obj, + void ** args, + int * argtypes, + int i) +{ + jl_array_t * array = reinterpret_cast(obj); + int cmd = static_cast(jl_unbox_int64(jl_arrayref(array, 0))); + void * arg = jl_unbox_voidpointer(jl_arrayref(array, 1)); + args[i] = arg; + argtypes[i] = cmd; + return true; +} + +jl_value_t * get_julia_type_from_sleftv(leftv ret) +{ + jl_array_t * result = jl_alloc_array_1d(jl_array_any_type, 3); + jl_arrayset(result, jl_false, 0); + jl_arrayset(result, jl_box_voidpointer(ret->data), 1); + ret->data = 0; + jl_arrayset(result, jl_box_int64(ret->Typ()), 2); + ret->rtyp = 0; + return reinterpret_cast(result); +} + +jl_value_t * get_ring_content(ring r) +{ + ring save = currRing; + rChangeCurrRing(r); + + // count elements + idhdl h = r->idroot; + int nr = 0; + while (h != NULL) { + nr++; + h = IDNEXT(h); + } + jl_array_t * result = jl_alloc_array_1d(jl_array_any_type, nr); + JL_GC_PUSH1(&result); + h = r->idroot; + nr = 0; + while (h != NULL) { + jl_array_t * current = jl_alloc_array_1d(jl_array_any_type, 3); + JL_GC_PUSH1(¤t); + jl_arrayset(current, jl_box_int64(IDTYP(h)), 0); + jl_arrayset(current, + reinterpret_cast(jl_symbol(IDID(h))), 1); + { + sleftv x; x.Copy((leftv)h); + jl_arrayset(current, jl_box_voidpointer(x.data), 2); + } + JL_GC_POP(); + jl_arrayset(result, reinterpret_cast(current), nr); + h = IDNEXT(h); + nr++; + } + JL_GC_POP(); + rChangeCurrRing(save); + return reinterpret_cast(result); +} + +jl_value_t * call_singular_library_procedure( + std::string s, ring r, jlcxx::ArrayRef arguments) +{ + int len = arguments.size(); + void * args[len]; + int argtypes[len + 1]; + argtypes[len] = 0; + for (int i = 0; i < len; i++) { + bool result = + translate_singular_type(arguments[i], args, argtypes, i); + if (!result) { + jl_error("Could not convert argument"); + } + } + BOOLEAN err; + jl_value_t * retObj; + leftv ret = ii_CallLibProcM(s.c_str(), args, argtypes, r, err); + if (err) { + inerror = 0; + errorreported = 0; + jl_error("Could not call function"); + } + if (ret->next != NULL) { + int len = ret->listLength(); + jl_array_t * list = jl_alloc_array_1d(jl_array_any_type, len + 1); + JL_GC_PUSH1(&list); + jl_arrayset(list, jl_true, 0); + for (int i = 0; i < len; ++i) { + leftv next = ret->next; + ret->next = 0; + jl_arrayset(list, get_julia_type_from_sleftv(ret), i + 1); + if (i > 0) + omFreeBin(ret, sleftv_bin); + ret = next; + } + JL_GC_POP(); + retObj = reinterpret_cast(list); + } + else { + retObj = get_julia_type_from_sleftv(ret); + omFreeBin(ret, sleftv_bin); + } + return retObj; +} + +jl_value_t * call_singular_library_procedure_wo_rng( + std::string name, void* rng, jlcxx::ArrayRef arguments) +{ + return call_singular_library_procedure(name, reinterpret_cast(rng), arguments); +} + +jl_value_t * lookup_singular_library_symbol_wo_rng( + std::string pack, + std::string name) +{ + int err = 2; + jl_value_t * res = jl_nothing; + jl_array_t * answer = jl_alloc_array_1d(jl_array_any_type, 2); + JL_GC_PUSH1(&answer); + leftv u = (leftv) IDROOT->get(pack.c_str(),0); + if (u != NULL) + { + err--; + idhdl v = ((package)(u->Data()))->idroot->get(name.c_str(), 0); + if (v != NULL) + { + err--; + sleftv x; + x.Copy((leftv)v); + res = get_julia_type_from_sleftv(&x); + } + } + // return to julia [err, res] + // err=0: no error, res is the value of the symbol + // err=1: package found but symbol not found, res is junk + // err=2: package not found, res is junk + jl_arrayset(answer, jl_box_int64(err), 0); + jl_arrayset(answer, res, 1); + JL_GC_POP(); + return reinterpret_cast(answer); +} + +jl_value_t * convert_nested_list(void * l_void) +{ + lists l = reinterpret_cast(l_void); + int len = lSize(l) + 1; + jl_array_t * result_array = jl_alloc_array_1d(jl_array_any_type, len); + JL_GC_PUSH1(&result_array); + for (int i = 0; i < len; i++) { + leftv current = &(l->m[i]); + if (current->Typ() == LIST_CMD) { + jl_arrayset( + result_array, + convert_nested_list(reinterpret_cast(current->data)), + i); + } + else { + jl_arrayset(result_array, get_julia_type_from_sleftv(current), i); + } + } + JL_GC_POP(); + return reinterpret_cast(result_array); +} + +void * create_syStrategy_data(syStrategy res, ring o) +{ + const ring origin = currRing; + rChangeCurrRing(o); + syStrategy temp = syCopy(res); + rChangeCurrRing(origin); + return reinterpret_cast(temp); +} + +void singular_define_caller(jlcxx::Module & Singular) +{ + Singular.method("load_library", [](std::string name) { + char * plib = iiConvName(name.c_str()); + idhdl h = ggetid(plib); + omFree(plib); + if (h == NULL) { + BOOLEAN bo = iiLibCmd(omStrDup(name.c_str()), TRUE, TRUE, FALSE); + if (bo) + return jl_false; + } + return jl_true; + }); + Singular.method("lookup_singular_library_symbol_wo_rng", + &lookup_singular_library_symbol_wo_rng); + Singular.method("call_singular_library_procedure", + &call_singular_library_procedure); + Singular.method("call_singular_library_procedure", + &call_singular_library_procedure_wo_rng); + Singular.method("get_type_mapper", &get_type_mapper); + Singular.method("initialize_jl_c_types", &initialize_jl_c_types); + + + Singular.method("NUMBER_CMD_CASTER", + [](void * obj) { return reinterpret_cast(obj); }); + Singular.method("RING_CMD_CASTER", + [](void * obj) { return reinterpret_cast(obj); }); + Singular.method("POLY_CMD_CASTER", + [](void * obj) { return reinterpret_cast(obj); }); + Singular.method("IDEAL_CMD_CASTER", + [](void * obj) { return reinterpret_cast(obj); }); + Singular.method("MATRIX_CMD_CASTER", + [](void * obj) { return reinterpret_cast(obj); }); + Singular.method("INT_CMD_CASTER", [](void * obj) { + return jl_box_int64(reinterpret_cast(obj)); + }); + Singular.method("STRING_CMD_CASTER", [](void * obj) { + return std::string(reinterpret_cast(obj)); + }); + Singular.method("INTVEC_CMD_CASTER", [](void * obj) { + return intvec_to_jl_array(reinterpret_cast(obj)); + }); + Singular.method("INTMAT_CMD_CASTER", [](void * obj) { + return intmat_to_jl_array(reinterpret_cast(obj)); + }); + Singular.method("BIGINT_CMD_CASTER", [](void * obj) { + return reinterpret_cast<__mpz_struct *>(obj); + }); + Singular.method("BIGINTMAT_CMD_CASTER", [](void * obj) { + return reinterpret_cast(obj); + }); + Singular.method("MAP_CMD_CASTER", [](void * obj) { + return reinterpret_cast(obj); + }); + Singular.method("RESOLUTION_CMD_CASTER", [](void * obj) { + return reinterpret_cast(obj); + }); + Singular.method("LIST_CMD_TRAVERSAL", &convert_nested_list); + Singular.method("get_ring_content", &get_ring_content); + Singular.method("get_ring_ref", &get_ring_ref); + Singular.method("copy_polyptr_to_void", ©_polyptr_to_void); + Singular.method("copy_idealptr_to_void", ©_idealptr_to_void); + Singular.method("copy_bigintmatptr_to_void", ©_bigintmatptr_to_void); + Singular.method("jl_array_to_intvec", &jl_array_to_intvec); + Singular.method("jl_array_to_intmat", &jl_array_to_intmat); + Singular.method("copy_string_to_void", ©_string_to_void); + Singular.method("jl_array_to_void", [] (jl_value_t * args_val, + jl_value_t * types_val, + ring R) { + auto origin = currRing; + rChangeCurrRing(R); + lists l = jl_array_to_list_helper(args_val, types_val); + rChangeCurrRing(origin); + return (void *) l; + }); + + Singular.method("create_syStrategy_data", &create_syStrategy_data); + +} diff --git a/deps/src/caller.h b/deps/src/caller.h new file mode 100644 index 000000000..bf49c67da --- /dev/null +++ b/deps/src/caller.h @@ -0,0 +1,8 @@ +#ifndef CALLER_INCLUDE +#define CALLER_INCLUDE + +#include "includes.h" + +void singular_define_caller(jlcxx::Module &); + +#endif diff --git a/deps/src/coeff_rings.cpp b/deps/src/coeff_rings.cpp new file mode 100644 index 000000000..c9925a1b3 --- /dev/null +++ b/deps/src/coeff_rings.cpp @@ -0,0 +1,87 @@ +#include "coeff_rings.h" + +typedef struct __singular_coeff_ring_struct { + int64_t has_simple_alloc; + int64_t has_simple_Inverse; + int64_t is_field; + int64_t is_domain; + int64_t ch; + void* data; + void* cfInit; + void* cfInt; + void* cfMPZ; + void* cfInpNeg; + void* cfCopy; + void* cfDelete; + void* cfAdd; + void* cfInpAdd; + void* cfSub; + void* cfMult; + void* cfInpMult; + void* cfDiv; + void* cfDivBy; + void* cfInvers; + void* cfAnn; + void* cfGcd; + void* cfSubringGcd; + void* cfExtGcd; + void* cfGreater; + void* cfEqual; + void* cfIsZero; + void* cfIsOne; + void* cfIsMOne; + void* cfGreaterZero; + void* cfWriteLong; + void* cfCoeffWrite; +} singular_coeff_ring_struct; + +void fill_coeffs_with_function_data(jl_value_t* coeff_struct, void* cf_void){ + + coeffs cf = reinterpret_cast(cf_void); + + singular_coeff_ring_struct* cf_input = reinterpret_cast(coeff_struct); + cf->has_simple_Alloc = (BOOLEAN)cf_input->has_simple_alloc; + cf->has_simple_Inverse = (BOOLEAN)cf_input->has_simple_Inverse; + cf->is_field = (BOOLEAN)cf_input->is_field; + cf->is_domain = (BOOLEAN)cf_input->is_domain; + cf->ch = (int)cf_input->ch; + cf->data = cf_input->data; + cf->cfInit = (number (*)(long, const coeffs)) cf_input->cfInit; + cf->cfInt = (long (*)(number &, const coeffs)) cf_input->cfInt; + cf->cfMPZ = (void (*)(__mpz_struct *, number &, const coeffs)) cf_input->cfMPZ; + cf->cfInpNeg = (number (*)(number, const coeffs)) cf_input->cfInpNeg; + cf->cfCopy = (number (*)(number, const coeffs)) cf_input->cfCopy; + cf->cfDelete = (void (*)(number *, const coeffs)) cf_input->cfDelete; + cf->cfAdd = (numberfunc) cf_input->cfAdd; + cf->cfInpAdd = (void (*)(number &, number, const coeffs)) cf_input->cfInpAdd; + cf->cfSub = (numberfunc) cf_input->cfSub; + cf->cfMult = (numberfunc) cf_input->cfMult; + cf->cfInpMult = (void (*)(number &, number, const coeffs)) cf_input->cfInpMult; + cf->cfDiv = (numberfunc) cf_input->cfDiv; + cf->cfDivBy = (BOOLEAN (*)(number, number, const coeffs)) cf_input->cfDivBy; + cf->cfInvers = (number (*)(number, const coeffs)) cf_input->cfInvers; + cf->cfAnn = (number (*)(number, const coeffs)) cf_input->cfAnn; + cf->cfGcd = (numberfunc) cf_input->cfGcd; + cf->cfSubringGcd = (numberfunc) cf_input->cfSubringGcd; + cf->cfExtGcd = (number (*)(number, number, number *, number *, const coeffs)) cf_input->cfExtGcd; + cf->cfGreater = (BOOLEAN (*)(number, number, const coeffs)) cf_input->cfGreater; + cf->cfEqual = (BOOLEAN (*)(number, number, const coeffs)) cf_input->cfEqual; + cf->cfIsZero = (BOOLEAN (*)(number, const coeffs)) cf_input->cfIsZero; + cf->cfIsOne = (BOOLEAN (*)(number, const coeffs)) cf_input->cfIsOne; + cf->cfIsMOne = (BOOLEAN (*)(number, const coeffs)) cf_input->cfIsMOne; + cf->cfGreaterZero = (BOOLEAN (*)(number, const coeffs)) cf_input->cfGreaterZero; + cf->cfWriteLong = (void (*)(number, const coeffs)) cf_input->cfWriteLong; + cf->cfCoeffWrite = (void (*)(const coeffs, BOOLEAN)) cf_input->cfCoeffWrite; + +} + + +void singular_define_coeff_rings(jlcxx::Module & singular){ + singular.method("fill_coeffs_with_function_data",fill_coeffs_with_function_data); + singular.method("nRegister",[](n_coeffType type, void* func ){ return nRegister( type, (cfInitCharProc)func );}); + singular.method("get_coeff_data",[](coeffs c){ return c->data;} ); + singular.method("get_coeff_data_void",[](void* c){ return reinterpret_cast(c)->data; }); + singular.method("cast_number_to_void",[](number n){ return reinterpret_cast(n); }); + singular.method("cast_void_to_number",[](void* n){ return reinterpret_cast(n); }); + singular.method("get_coeffs_BIGINT", []() {return coeffs_BIGINT;}); +} diff --git a/deps/src/coeff_rings.h b/deps/src/coeff_rings.h new file mode 100644 index 000000000..eeedc7f95 --- /dev/null +++ b/deps/src/coeff_rings.h @@ -0,0 +1,8 @@ +#ifndef COEFF_RINGS_INCLUDE +#define COEFF_RINGS_INCLUDE + +#include "includes.h" + +void singular_define_coeff_rings(jlcxx::Module &); + +#endif diff --git a/deps/src/coeffs.cpp b/deps/src/coeffs.cpp new file mode 100644 index 000000000..f942f90a8 --- /dev/null +++ b/deps/src/coeffs.cpp @@ -0,0 +1,443 @@ +#include "coeffs.h" + +auto transExt_helper(coeffs cf, jlcxx::ArrayRef param) +{ + auto len = param.size(); + char ** param_ptr = new char *[len]; + for (int i = 0; i < len; i++) { + param_ptr[i] = reinterpret_cast(param[i]); + } + // use lex because the ordering doesn't matter for coefficient operations + ring r = rDefault(cf, len, param_ptr, ringorder_lp); + delete[] param_ptr; + TransExtInfo extParam; + extParam.r = r; + return nInitChar(n_transExt, &extParam); +} + +poly transExt_to_poly(number a, coeffs cf, ring r) +{ + // zero is represented by nullptr + if (a == NULL || NUM((fraction)a) == NULL) + return NULL; + + assume(cf->extRing != NULL); + ring ext = cf->extRing; + nMapFunc nMap = n_SetMap(ext->cf, r->cf); + const ring origin = currRing; + rChangeCurrRing(r); + poly p = p_PermPoly(NUM((fraction)a), NULL, ext, r, nMap, NULL); + rChangeCurrRing(origin); + return p; +} + +void singular_define_coeffs(jlcxx::Module & Singular) +{ + /* initialise a coefficient ring */ + Singular.method("nInitChar", &nInitChar); + /* Helper to construct transcendental Extensions */ + Singular.method("transExt_helper", &transExt_helper); + /* Helper to convert n_transExt into a polynomial */ + Singular.method("transExt_to_poly", &transExt_to_poly); + /* get the characteristic of a coefficient domain */ + Singular.method("n_GetChar", [](coeffs n) { return n_GetChar(n); }); + + /* + given F = R(x), a univariate function field over R = QQ or Fp, + construct the number field R[x]/minpoly. + Return a new coefficient ring or a copy of the old one in case of error. + Thus, the return should be checked to see if it is a number field + (nCoeff_is_algExt) before use. + + TODO: this will be in the kernel soon + */ + Singular.method("transExt_SetMinpoly", [](coeffs F, number a) { + + if (!nCoeff_is_transExt(F) || rVar(F->extRing) != 1) + { + WerrorS("cannot set minpoly for these coeffients"); + return nCopyCoeff(F); + } + + BOOLEAN redefine_from_algext = FALSE; + + number p = n_Copy(a, F); + n_Normalize(p, F); + + if (n_IsZero(p, F)) + { + n_Delete(&p, F); + return nCopyCoeff(F); + } + + AlgExtInfo A; + + A.r = rCopy(F->extRing); // Copy ground field! + // if minpoly was already set: + if (F->extRing->qideal != NULL) + id_Delete(&A.r->qideal, A.r); + ideal q = idInit(1,1); + if (p == NULL || NUM((fraction)p) == NULL) + { + WerrorS("Could not construct the alg. extension: minpoly==0"); + // cleanup A: TODO + rDelete( A.r ); + return nCopyCoeff(F); + } + if (!redefine_from_algext && (DEN((fraction)(p)) != NULL)) // minpoly must be a fraction with poly numerator...!! + { + poly n = DEN((fraction)(p)); + if (!p_IsConstantPoly(n, F->extRing)) + { + WarnS("denominator must be constant - ignoring it"); + } + p_Delete(&n, F->extRing); + DEN((fraction)(p)) = NULL; + } + + if (redefine_from_algext) + q->m[0] = (poly)p; + else + q->m[0] = NUM((fraction)p); + A.r->qideal = q; + + // :( + // NUM((fractionObject *)p) = NULL; // makes 0/ NULL fraction - which should not happen! + // n_Delete(&p, r->F); // doesn't expect 0/ NULL :( + if (!redefine_from_algext) + { + EXTERN_VAR omBin fractionObjectBin; + NUM((fractionObject *)p) = NULL; // not necessary, but still... + omFreeBin((ADDRESS)p, fractionObjectBin); + } + + coeffs K = nInitChar(n_algExt, &A); + if (K == NULL) + { + WerrorS("Could not construct the alg. extension: llegal minpoly?"); + // cleanup A: TODO + rDelete(A.r); + return nCopyCoeff(F); + } + else + { + return K; + } + }); + + /* + if K = R[x]/minpoly(x) (with nCoeff_is_algExt(cf) = true), + return the corresponding transcendental extension R(x): this is the + parent of minpoly. + */ + Singular.method("algExt_UnsetMinpoly", [](coeffs K) { + if (nCoeff_is_algExt(K) && !nCoeff_is_GF(K)) + { + ring K0 = rCopy0(K->extRing, FALSE, TRUE); + rComplete(K0); + TransExtInfo e; + e.r = K0; + coeffs F = nInitChar(n_transExt, &e); + return F; + } + else + { + WerrorS("cannot unset minpoly for these coeffients"); + return nCopyCoeff(K); + } + }); + + /* + Given K = R[x]/minpoly(x) and the corresponding F = R(x) return + the minpoly as an element of F. + */ + Singular.method("algExt_GetMinpoly", [](coeffs K, coeffs F) { + if (nCoeff_is_algExt(K) && !nCoeff_is_GF(K)) + { + nMapFunc nMap = n_SetMap(K, F); + number minpoly = reinterpret_cast(K->extRing->qideal->m[0]); + return nMap(minpoly, K, F); + } + else + { + WerrorS("cannot get minpoly for these coeffients"); + return n_Init(0, F); + } + }); + + /* + Given an element a of K = R[x]/minpoly(x) and the corresponding + F = R(x), return the element a as an element of F. + */ + Singular.method("algExt_to_transExt", [](number a, coeffs K, coeffs F) { + if (nCoeff_is_algExt(K) && !nCoeff_is_GF(K)) + { + nMapFunc nMap = n_SetMap(K, F); + return nMap(a, K, F); + } + else + { + WerrorS("cannot use algExt_to_transExt for these coeffients"); + return n_Init(0, F); + } + }); + + /* + Given an element a of F = R(x) and K = R[x]/minpoly(x), + return a as an element of K. + */ + Singular.method("transExt_to_algExt", [](number a, coeffs K, coeffs F) { + if (nCoeff_is_algExt(K) && !nCoeff_is_GF(K)) + { + // naCopyTrans2AlgExt has a bug with zero input + if (a == NULL || NUM((fraction)a) == NULL) + return reinterpret_cast(NULL); + + nMapFunc nMap = n_SetMap(F, K); + return nMap(a, F, K); + } + else + { + WerrorS("cannot use transExt_to_algExt for these coeffients"); + return n_Init(0, F); + } + }); + + /* only used to get the order of a N_GField */ + Singular.method("nfCharQ", [](coeffs n) {return n->m_nfCharQ;}); + + Singular.method("nCoeff_is_Zp", [](coeffs n) { + return bool(nCoeff_is_Zp(n)); + }); + + Singular.method("nCoeff_is_Q", [](coeffs n) { + return bool(nCoeff_is_Q(n)); + }); + + Singular.method("nCoeff_is_Z", [](coeffs n) { + return bool(nCoeff_is_Z(n)); + }); + + Singular.method("nCoeff_is_GF", [](coeffs n) { + return bool(nCoeff_is_GF(n)); + }); + + Singular.method("nCoeff_is_transExt", [](coeffs n) { + return bool(nCoeff_is_transExt(n)); + }); + + Singular.method("nCoeff_is_algExt", [](coeffs n) { + return bool(nCoeff_is_algExt(n)); + }); + + /* make a copy of a coefficient domain (actually just increments a + * reference count) */ + Singular.method("nCopyCoeff", &nCopyCoeff); + /* kill a coefficient ring */ + Singular.method("nKillChar", &nKillChar); + /* return a function to convert between rings */ + Singular.method("n_SetMap", [](const coeffs x, const coeffs y) { + return reinterpret_cast(n_SetMap(x, y)); + }); + + /* Identity function on coefficient ring */ + Singular.method("ndCopyMap", []() { + return reinterpret_cast(ndCopyMap); + }); + + Singular.method("nApplyMapFunc", + [](void * map, snumber * x, coeffs a, coeffs b) { + return reinterpret_cast(map)(x, a, b); + }); + + Singular.method("n_Init", [](long x, coeffs n) { return n_Init(x, n); }); + + Singular.method("n_Copy", + [](snumber * x, const coeffs n) { return n_Copy(x, n); }); + + Singular.method("nCoeff_has_simple_Alloc", + [](coeffs x) { return nCoeff_has_simple_Alloc(x) > 0; }); + + Singular.method("n_GetMPZ_internal", [](void * ptr, number n, coeffs x) { + n_MPZ(reinterpret_cast<__mpz_struct *>(ptr), n, x); + }); + + Singular.method("n_InitMPZ_internal", [](void * ptr, coeffs x) { + return n_InitMPZ(reinterpret_cast<__mpz_struct *>(ptr), x); + }); + + Singular.method("n_Delete", [](snumber * n, coeffs cf) { + if (n != NULL) { + n_Delete(&n, cf); + } + }); + + Singular.method("n_Write_internal", + [](snumber * x, coeffs cf, const int d) { + return n_Write(x, cf, d); + }); + + Singular.method("n_Add", [](snumber * a, snumber * b, coeffs c) { + return n_Add(a, b, c); + }); + + Singular.method("n_Sub", [](snumber * a, snumber * b, coeffs c) { + return n_Sub(a, b, c); + }); + + Singular.method("n_Mult", [](snumber * a, snumber * b, coeffs c) { + return n_Mult(a, b, c); + }); + + Singular.method("n_Neg", [](snumber * a, coeffs c) { + number nn = n_Copy(a, c); + nn = n_InpNeg(nn, c); + return nn; + }); + + Singular.method("n_Invers", + [](snumber * a, coeffs c) { return n_Invers(a, c); }); + + Singular.method("n_ExactDiv", [](snumber * a, snumber * b, coeffs c) { + return n_ExactDiv(a, b, c); + }); + + Singular.method("n_Div", [](snumber * a, snumber * b, coeffs c) { + number z = n_Div(a, b, c); + n_Normalize(z, c); + return z; + }); + + /* return the numerator of a, possibly modifying a in the process */ + Singular.method("n_GetNumerator", [](number & a, coeffs c) { + return n_GetNumerator(a, c); + }); + + /* return the denominator of a, possibly modifying a in the process */ + Singular.method("n_GetDenom", [](number & a, coeffs c) { + return n_GetDenom(a, c); + }); + + /* + since references are such a pain on the julia side, + n_Normalize takes a non-reference and returns the modifed result + */ + Singular.method("n_Normalize", [](number a, coeffs c) { + n_Normalize(a, c); + return a; + }); + + Singular.method("n_Power", [](snumber * a, int b, coeffs c) { + number res; + n_Power(a, b, &res, c); + return res; + }); + + Singular.method("n_Gcd", [](snumber * a, snumber * b, coeffs c) { + return n_Gcd(a, b, c); + }); + + Singular.method("n_SubringGcd", [](snumber * a, snumber * b, coeffs c) { + return n_SubringGcd(a, b, c); + }); + + Singular.method("n_Lcm", [](snumber * a, snumber * b, coeffs c) { + return n_Lcm(a, b, c); + }); + + Singular.method("n_ExtGcd", [](number a, number b, + number * s, number * t, const coeffs c) { + return n_ExtGcd(a, b, s, t, c); + }); + + Singular.method("n_IsZero", [](snumber * x, const coeffs n) { + return n_IsZero(x, n) > 0; + }); + + Singular.method("n_IsOne", [](snumber * x, const coeffs n) { + return n_IsOne(x, n) > 0; + }); + + Singular.method("n_Greater", + [](snumber * x, snumber * y, const coeffs n) { + return n_Greater(x, y, n) > 0; + }); + + Singular.method("n_GreaterZero", [](snumber * x, const coeffs n) { + return n_GreaterZero(x, n) > 0; + }); + + Singular.method("n_Equal", [](snumber * x, snumber * y, const coeffs n) { + return n_Equal(x, y, n) > 0; + }); + + Singular.method("n_InpAdd", [](snumber * x, snumber * y, const coeffs n) { + n_InpAdd(x, y, n); + return x; + }); + + Singular.method("n_InpMult", [](snumber * x, snumber * y, const coeffs n) { + n_InpMult(x, y, n); + return x; + }); + + Singular.method("n_QuotRem", [](number x, number y, + number * r, const coeffs n) { + return n_QuotRem(x, y, r, n); + }); + + Singular.method("n_IntMod", &n_IntMod); + + Singular.method("n_Farey", &n_Farey); + + Singular.method("n_ChineseRemainderSym", [](void * x, void * y, int n, + int sign_flag, coeffs c) { + CFArray inv_cache(n); + return n_ChineseRemainderSym(reinterpret_cast(x), + reinterpret_cast(y), n, + sign_flag, inv_cache, c); + }); + + Singular.method("n_Param", + [](int x, const coeffs n) { return n_Param(x, n); }); + + Singular.method("n_NumberOfParameters", [](coeffs r) { + return n_NumberOfParameters(r); + }); + + Singular.method("n_ParameterName", [](int i, coeffs r) { + return std::string(n_ParameterNames(r)[i]); + }); + + Singular.method("StringSetS_internal", + [](std::string m) { return StringSetS(m.c_str()); }); + + Singular.method("StringEndS", []() { + char * m = StringEndS(); + std::string s(m); + omFree(m); + return s; + }); + + Singular.method("omAlloc0", + [](size_t siz) { return (void *)omAlloc0(siz); }); + + Singular.method("omFree_internal", [](void * m) { omFree(m); }); + + /* Setting a Ptr{number} to a number */ + Singular.method("setindex_internal", [](void * x, snumber * y) { + *reinterpret_cast(x) = y; + }); + + Singular.method("setindex_internal_void", [](void * x, void * y) { + reinterpret_cast(x)[0] = y; + }); + + Singular.method("mpz_init_set_internal", [](void* x, void* y ){ + mpz_init_set(reinterpret_cast(x),reinterpret_cast(y)); + }); + + Singular.method("mpz_init_set_si_internal", [](void* x, long y ){ + mpz_init_set_si(reinterpret_cast(x),y); + }); +} diff --git a/deps/src/coeffs.h b/deps/src/coeffs.h new file mode 100644 index 000000000..66d061270 --- /dev/null +++ b/deps/src/coeffs.h @@ -0,0 +1,9 @@ +#ifndef COEFFS_INCLUDE +#define COEFFS_INCLUDE +#define TRANSEXT_PRIVATES + +#include "includes.h" + +void singular_define_coeffs(jlcxx::Module &); + +#endif diff --git a/deps/src/ideals.cpp b/deps/src/ideals.cpp new file mode 100644 index 000000000..78a9339c7 --- /dev/null +++ b/deps/src/ideals.cpp @@ -0,0 +1,667 @@ +#include "ideals.h" + +auto id_sres_helper(sip_sideal * m, int n, ring R) +{ + auto origin = currRing; + rChangeCurrRing(R); + syStrategy s = sySchreyer(m, n); + rChangeCurrRing(origin); + auto r = s->minres; + bool minimal = true; + if (r == NULL) { + r = s->fullres; + minimal = false; + } + return std::make_tuple(s, minimal); +} + + +auto id_fres_helper(sip_sideal * I, int n, std::string method, ring R) +{ + auto origin = currRing; + rChangeCurrRing(R); + syStrategy s = syFrank(I, n, method.c_str()); + rChangeCurrRing(origin); + auto r = s->minres; + bool minimal = true; + if (r == NULL) { + r = s->fullres; + minimal = false; + } + return std::make_tuple(s, minimal); +} + +auto id_res_helper(sip_sideal * I, int n, int minimize, ring R) +{ + auto origin = currRing; + rChangeCurrRing(R); + syStrategy s = syResolution(I, n, NULL, (BOOLEAN)minimize); + rChangeCurrRing(origin); + auto r = s->minres; + bool minimal = true; + if (r == NULL) { + r = s->fullres; + minimal = false; + } + return std::make_tuple(s, minimal); +} + +ideal id_Syzygies_internal(ideal m, ring o) +{ + ideal id = NULL; + intvec * n = NULL; + tHomog h = testHomog; + const ring origin = currRing; + rChangeCurrRing(o); + id = idSyzygies(m, h, &n); + rChangeCurrRing(origin); + if (n != NULL) + delete n; + return id; +} + +auto id_Slimgb_helper(ideal a, ring b, bool complete_reduction = false) +{ + // bool complete_reduction= false; + unsigned int crbit; + if (complete_reduction) + auto crbit = Sy_bit(OPT_REDSB); + else + crbit = 0; + ideal id = NULL; + if (!idIs0(a)) { + intvec * n = NULL; + tHomog h = testHomog; + const ring origin = currRing; + unsigned int save_opt = si_opt_1; + si_opt_1 |= crbit; + rChangeCurrRing(b); + id = t_rep_gb(b, a, a->rank); + si_opt_1 = save_opt; + rChangeCurrRing(origin); + if (n != NULL) + delete n; + } + else + id = idInit(0, a->rank); + return id; +} + +auto id_InterRed_helper(ideal a, ring b) +{ + ideal id = NULL; + if (!idIs0(a)) { + const ring origin = currRing; + rChangeCurrRing(b); + id = kInterRed(a, b->qideal); + rChangeCurrRing(origin); + } + else + id = idInit(0, a->rank); + return id; +} + +auto id_Std_helper(ideal a, ring b, bool complete_reduction = false) +{ + // bool complete_reduction= false; + unsigned int crbit; + if (complete_reduction) + crbit = Sy_bit(OPT_REDSB); + else + crbit = 0; + ideal id = NULL; + if (!idIs0(a)) { + intvec * n = NULL; + tHomog h = testHomog; + const ring origin = currRing; + unsigned int save_opt = si_opt_1; + si_opt_1 |= crbit; + rChangeCurrRing(b); + id = kStd(a, b->qideal, h, &n); + si_opt_1 = save_opt; + rChangeCurrRing(origin); + if (n != NULL) + delete n; + } + else + id = idInit(0, a->rank); + return id; +} + +auto id_MinStd_helper(ideal a, ring b, bool complete_reduction = false) +{ + // bool complete_reduction= false; + unsigned int crbit; + if (complete_reduction) + crbit = Sy_bit(OPT_REDSB); + else + crbit = 0; + ideal id = NULL; + ideal m = NULL; + if (!idIs0(a)) + { + tHomog h = testHomog; + const ring origin = currRing; + unsigned int save_opt = si_opt_1; + si_opt_1 |= crbit; + rChangeCurrRing(b); + id = kMin_std(a, b->qideal, h, NULL, m); + si_opt_1 = save_opt; + rChangeCurrRing(origin); + } + else + { + id = idInit(0, a->rank); + m = idInit(0, a->rank); + } + return std::make_tuple(id, m); +} + +intvec* to_intvec(jlcxx::ArrayRef a) +{ + int sz = a.size(); + intvec * w = new intvec(sz); + int * hi = w->ivGetVec(); + for (int i=0; i h, bool complete_reduction = false) +{ + intvec* hilb = to_intvec(h); + + unsigned int crbit; + if (complete_reduction) + crbit = Sy_bit(OPT_REDSB); + else + crbit = 0; + ideal id = NULL; + if (!idIs0(a)) { + intvec * n = NULL; + tHomog h = testHomog; + const ring origin = currRing; + unsigned int save_opt = si_opt_1; + si_opt_1 |= crbit; + rChangeCurrRing(b); + id = kStd(a, b->qideal, h, &n, hilb); + si_opt_1 = save_opt; + rChangeCurrRing(origin); + if (n != NULL) + delete n; + } + else + id = idInit(0, a->rank); + delete hilb; + return id; +} + +auto id_StdHilbWeighted_helper(ideal a, ring b, jlcxx::ArrayRef h, jlcxx::ArrayRef vw, bool complete_reduction = false) +{ + intvec* hilb = to_intvec(h); + intvec* varweights = to_intvec(vw); + + unsigned int crbit; + if (complete_reduction) + crbit = Sy_bit(OPT_REDSB); + else + crbit = 0; + ideal id = NULL; + if (!idIs0(a)) { + intvec * n = NULL; + tHomog h = testHomog; + const ring origin = currRing; + unsigned int save_opt = si_opt_1; + si_opt_1 |= crbit; + rChangeCurrRing(b); + id = kStd(a, + currRing->qideal, + h, + &n, // module weights + hilb, // hilbert series + 0,0, // syzComp, newIdeal + varweights); // weights of vars + si_opt_1 = save_opt; + rChangeCurrRing(origin); + if (n != NULL) + delete n; + } + else + id = idInit(0, a->rank); + delete hilb; + delete varweights; + return id; +} + +auto id_TwoStd_helper(ideal a, ring b) +{ + const ring origin = currRing; + rChangeCurrRing(b); + ideal id = twostd(a); + rChangeCurrRing(origin); + return id; +} + +void singular_define_ideals(jlcxx::Module & Singular) +{ + Singular.method("id_Delete", + [](ideal m, ring n) { return id_Delete(&m, n); }); + + Singular.method("id_Copy", &id_Copy); + + Singular.method("idInit", &idInit); + + Singular.method("setindex_internal", + [](ideal r, poly n, int o) { return r->m[o] = n; }); + + Singular.set_override_module(jl_base_module); + Singular.method("getindex", + [](ideal r, int o) { return (poly)(r->m[o]); }); + Singular.unset_override_module(); + + Singular.method("idIs0", &idIs0); + + Singular.method("id_IsConstant", &id_IsConstant); + + Singular.method("id_IsZeroDim", &id_IsZeroDim); + + Singular.method("idElem", &idElem); + + Singular.method("id_Normalize", &id_Normalize); + + Singular.method("id_Head", &id_Head); + + Singular.method("id_MaxIdeal", + [](int m, ring n) { return id_MaxIdeal(m, n); }); + + Singular.method("id_Add", &id_Add); + + Singular.method("id_Mult", &id_Mult); + + Singular.method("id_MultP", [](ideal i, poly p, ring r) { + return (ideal) mp_MultP((matrix) i, p, r); + }); + + Singular.method("pMultId", [](poly p, ideal i, ring r) { + return (ideal) pMultMp(p, (matrix) i, r); + }); + + Singular.method("id_Power", &id_Power); + + Singular.method("id_IsEqual", [](ideal m, ideal n, ring o) { + return mp_Equal((ip_smatrix *)m, (ip_smatrix *)n, o); + }); + + Singular.method("id_FreeModule", &id_FreeModule); + + Singular.method("idSkipZeroes", &idSkipZeroes); + + Singular.method("ngens", [](ideal m) { return (int)IDELEMS(m); }); + + Singular.method("rank", [](ideal m) { return (int)m->rank; }); + + Singular.method("id_Quotient", [](ideal a, ideal b, bool c, ring d) { + const ring origin = currRing; + rChangeCurrRing(d); + ideal id = idQuot(a, b, c, TRUE); + rChangeCurrRing(origin); + return id; + }); + + Singular.method("id_Intersection", [](ideal a, ideal b, ring c) { + const ring origin = currRing; + rChangeCurrRing(c); + ideal id = idSect(a, b); + rChangeCurrRing(origin); + return id; + }); + + Singular.method("id_MultSect", [](void * ids, int len, ring r) { + const ring origin = currRing; + rChangeCurrRing(r); + ideal id = idMultSect(reinterpret_cast(ids), len); + rChangeCurrRing(origin); + return id; + }); + + Singular.method("id_Syzygies", &id_Syzygies_internal); + + Singular.method("id_sres", &id_sres_helper); + + Singular.method("id_fres", &id_fres_helper); + + Singular.method("id_res", &id_res_helper); + + Singular.method("id_Slimgb", &id_Slimgb_helper); + + Singular.method("id_MinStd", &id_MinStd_helper); + Singular.method("id_TwoStd", &id_TwoStd_helper); + Singular.method("id_Std", &id_Std_helper); + Singular.method("id_StdHilb", &id_StdHilb_helper); + Singular.method("id_StdHilbWeighted", &id_StdHilbWeighted_helper); + + Singular.method("id_InterRed", &id_InterRed_helper); + + Singular.method("id_Eliminate", [](ideal m, poly p, ring o) { + const ring origin = currRing; + rChangeCurrRing(o); + ideal res = idElimination(m, p); + rChangeCurrRing(origin); + return res; + }); + + Singular.method("id_DivRem", [](ideal m, ideal sm, ring o) { + const ring origin = currRing; + rChangeCurrRing(o); + ideal factors; + ideal res = idDivRem(sm, m, factors, NULL); + rChangeCurrRing(origin); + return std::make_tuple(res, factors); + }); + + Singular.method("id_DivRem", [](ideal m, ideal sm, ring o, int flag) { + const ring origin = currRing; + rChangeCurrRing(o); + ideal factors; + ideal res = idDivRem(sm, m, factors, NULL,flag); + rChangeCurrRing(origin); + return std::make_tuple(res, factors); + }); + + Singular.method("id_DivRem_Unit", [](ideal m, ideal sm, ring o) { + const ring origin = currRing; + rChangeCurrRing(o); + ideal factors; + ideal unit; + ideal res = idDivRem(sm, m, factors, &unit); + rChangeCurrRing(origin); + return std::make_tuple(res, factors, unit); + }); + + Singular.method("id_DivRem_Unit", [](ideal m, ideal sm, ring o, int flag) { + const ring origin = currRing; + rChangeCurrRing(o); + ideal factors; + ideal unit; + ideal res = idDivRem(sm, m, factors, &unit, flag); + rChangeCurrRing(origin); + return std::make_tuple(res, factors, unit); + }); + + Singular.method("id_Lift", [](ideal m, ideal sm, ring o) { + const ring origin = currRing; + rChangeCurrRing(o); + ideal rest; + ideal res = idLift(m, sm, &rest, FALSE, FALSE); + rChangeCurrRing(origin); + return std::make_tuple(res, rest); + }); + + Singular.method("id_Lift", [](ideal m, ideal sm, bool goodShape, + bool isSB, bool divide, ring o) { + const ring origin = currRing; + rChangeCurrRing(o); + ideal rest; + matrix unit; + ideal res = idLift(m, sm, &rest, BOOLEAN(goodShape), BOOLEAN(isSB), + BOOLEAN(divide), &unit, GbDefault); + rChangeCurrRing(origin); + return std::make_tuple(res, rest, unit); + }); + + Singular.method("id_LiftStd", [](ideal m, ring o, bool complete_reduction = false) { + const ring origin = currRing; + rChangeCurrRing(o); + matrix ma=mpNew(1,1); + unsigned int crbit; + if (complete_reduction) + crbit = Sy_bit(OPT_REDSB); + else + crbit = 0; + unsigned int save_opt = si_opt_1; + si_opt_1 |= crbit; + ideal res = idLiftStd(m, &ma, testHomog, NULL); + si_opt_1 = save_opt; + rChangeCurrRing(origin); + return std::make_tuple(res, ma); + }); + + Singular.method("id_LiftStdSyz", [](ideal m, ring o, bool complete_reduction = false) { + const ring origin = currRing; + rChangeCurrRing(o); + matrix ma=mpNew(1,1); + ideal syz=idInit(1,1); + unsigned int crbit; + if (complete_reduction) + crbit = Sy_bit(OPT_REDSB); + else + crbit = 0; + unsigned int save_opt = si_opt_1; + si_opt_1 |= crbit; + ideal res = idLiftStd(m, &ma, testHomog, &syz); + si_opt_1 = save_opt; + + rChangeCurrRing(origin); + return std::make_tuple(res, ma, syz); + }); + + Singular.method("id_Modulo", [](ideal a, ideal b, ring o) { + const ring origin = currRing; + rChangeCurrRing(o); + ideal res = idModulo(a, b, testHomog); + rChangeCurrRing(origin); + return res; + }); + + Singular.method("id_Satstd", &id_Satstd); + + Singular.method("id_Array2Vector", [](void * p, int a, ring o) { + return id_Array2Vector(reinterpret_cast(p), a, o); + }); + + Singular.method("p_Vector2Array", [](poly p, void * a, int b, ring o) { + p_Vec2Array(p, reinterpret_cast(a), b, o); + }); + + Singular.method("internal_void_to_poly_helper", + [](void * p) { return reinterpret_cast(p); }); + + Singular.method( + "maGetPreimage", [](ring trgt, ideal a, ideal b, ring src) { + sip_smap sing_map = {a->m, (char *)"julia_ring", 1, a->ncols}; + return maGetPreimage(trgt, &sing_map, b, src); + }); + + Singular.method("id_Jet", [](ideal I, int n, ring r) { + ideal res = id_Jet(I, n, r); + return res; + }); + + Singular.method("id_vdim", [](ideal I, ring r) { + const ring origin = currRing; + rChangeCurrRing(r); + int n=scMult0Int(I, r->qideal); + rChangeCurrRing(origin); + return n; + }); + + Singular.method("id_kbase", [](ideal I, ring r) { + ideal res; + const ring origin = currRing; + rChangeCurrRing(r); + res = scKBase(-1, I, r->qideal); + rChangeCurrRing(origin); + return res; + }); + + Singular.method("id_kbase", [](ideal I, int n, ring r) { + ideal res; + const ring origin = currRing; + rChangeCurrRing(r); + res = scKBase(n, I, r->qideal); + rChangeCurrRing(origin); + return res; + }); + + Singular.method("id_highcorner", [](ideal I, ring r) { + poly h; + const ring origin = currRing; + rChangeCurrRing(r); + h = iiHighCorner(I, 0); + rChangeCurrRing(origin); + return h; + }); + Singular.method("maMapIdeal", [](ideal map_id, ring pr, ideal im_id, + ring im, void * cf_map) { + const ring origin = currRing; + rChangeCurrRing(pr); + ideal I = maMapIdeal(map_id, pr, im_id, im, reinterpret_cast(cf_map)); + rChangeCurrRing(origin); + return I; + }); + Singular.method("idMinBase", [](ideal I, ring r) { + const ring origin = currRing; + rChangeCurrRing(r); + ideal J = idMinBase(I); + rChangeCurrRing(origin); + return J; + }); + Singular.method("scIndIndset", [](ideal I, ring r, jlcxx::ArrayRef a, bool all) { + const ring origin = currRing; + rChangeCurrRing(r); + lists L = scIndIndset(I, all, r->qideal); + int n = rVar(r); + int m = lSize(L); + if(all == true && m >= 0) + { + for(int i = 0; i<=m; i++) + { + intvec * v = reinterpret_cast(L->m[i].data); + int * content = v->ivGetVec(); + for(int j = 0; j < n; j++) + { + a.push_back(content[j]); + } + } + } + else if(all == false && m >= 0) + { + intvec * v = reinterpret_cast(L->m[0].data); + int * content = v->ivGetVec(); + for(int j = 0; j < n; j++) + { + a.push_back(content[j]); + } + } + rChangeCurrRing(origin); + }); + Singular.method("scDegree", [](ideal I, ring R) + { + const ring origin = currRing; + rChangeCurrRing(R); + SPrintStart(); + scDegree(I, NULL, R->qideal); + char *s = SPrintEnd(); + s[strlen(s)-1]='\0'; + std::string res(s); + omFree(s); + rChangeCurrRing(origin); + return res; + }); + Singular.method("scDegree", [](ideal I, ring R, jlcxx::ArrayRef w) + { + const ring origin = currRing; + rChangeCurrRing(R); + intvec * module_w = to_intvec(w); + SPrintStart(); + scDegree(I, module_w, R->qideal); + delete module_w; + char *s = SPrintEnd(); + s[strlen(s)-1]='\0'; + std::string res(s); + omFree(s); + rChangeCurrRing(origin); + return res; + }); + Singular.method("scMultInt", [](ideal I, ring R) { + const ring origin = currRing; + rChangeCurrRing(R); + int k = scMultInt(I, R->qideal); + rChangeCurrRing(origin); + return k; + }); + Singular.method("scDimInt", [](ideal I, ring R) { + const ring origin = currRing; + rChangeCurrRing(R); + int k = scDimInt(I, R->qideal); + rChangeCurrRing(origin); + return k; + }); + Singular.method("scDimIntRing", [](ideal I, ring R) { + const ring origin = currRing; + rChangeCurrRing(R); + int k = scDimIntRing(I, R->qideal); + rChangeCurrRing(origin); + return k; + }); + Singular.method("fglmzero", [](ideal Isrc, ring Rsrc, ring Rdest ) { + const ring origin = currRing; + rChangeCurrRing(Rdest); + ideal Idest = NULL; + bool c = fglmzero(Rsrc, Isrc, Rdest, Idest, FALSE, FALSE); + rChangeCurrRing(origin); + return Idest; + }); + Singular.method("scHilb", [](ideal I, ring r, jlcxx::ArrayRef a) { + const ring origin = currRing; + rChangeCurrRing(r); + intvec *v=hFirstSeries(I,NULL,r->qideal); + int * content = v->ivGetVec(); + for(int j = 0; j < v->length(); j++) + a.push_back(content[j]); + delete v; + rChangeCurrRing(origin); + }); + Singular.method("scHilbWeighted", [](ideal I, ring r, jlcxx::ArrayRef weights, jlcxx::ArrayRef a) { + intvec * w = to_intvec(weights); + const ring origin = currRing; + rChangeCurrRing(r); + intvec *v=hFirstSeries(I,NULL,r->qideal,w); + delete w; + int * content = v->ivGetVec(); + for(int j = 0; j < v->length(); j++) + { + a.push_back(content[j]); + } + delete v; + rChangeCurrRing(origin); + }); + Singular.method("scHilbWeighted", [](ideal I, ring r, jlcxx::ArrayRef weights, jlcxx::ArrayRef shifts, jlcxx::ArrayRef a) { + intvec * w = to_intvec(weights); + intvec * sh = to_intvec(shifts); + const ring origin = currRing; + rChangeCurrRing(r); + intvec *v=hFirstSeries(I,sh,r->qideal,w); + delete sh; + delete w; + int * content = v->ivGetVec(); + for(int j = 0; j < v->length(); j++) + { + a.push_back(content[j]); + } + delete v; + rChangeCurrRing(origin); + }); + Singular.method("id_Homogen", id_Homogen); + Singular.method("id_HomModule", [](jlcxx::ArrayRef weights, ideal I, ring r) { + intvec* w = NULL; + bool res = id_HomModule(I, r->qideal, &w, r); + if (w != NULL) + { + for (int i = 0; i < w->length(); i++) + weights.push_back((*w)[i]); + delete w; + } + return res; + }); +} diff --git a/deps/src/ideals.h b/deps/src/ideals.h new file mode 100644 index 000000000..8f596d3c2 --- /dev/null +++ b/deps/src/ideals.h @@ -0,0 +1,8 @@ +#ifndef IDEALS_INCLUDE +#define IDEALS_INCLUDE + +#include "includes.h" + +void singular_define_ideals(jlcxx::Module &); + +#endif diff --git a/deps/src/includes.h b/deps/src/includes.h new file mode 100644 index 000000000..7b96e11cf --- /dev/null +++ b/deps/src/includes.h @@ -0,0 +1,79 @@ +#ifndef MAIN_INCLUDE_FILE +#define MAIN_INCLUDE_FILE + +#include "xcode_jlcxx_workaround.h" + +#include +#include +#include +#include + +#include "jlcxx/jlcxx.hpp" +#include "jlcxx/const_array.hpp" +#include "jlcxx/array.hpp" +#include "jlcxx/tuple.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "polys/ext_fields/algext.h" +#include "polys/ext_fields/transext.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Singular/maps_ip.h" +#include +#include +#include +#include + +namespace jlcxx { +template <> struct IsMirroredType : std::true_type { +}; +template <> struct IsMirroredType : std::true_type { +}; +template <> struct IsMirroredType : std::false_type { +}; +template <> struct IsMirroredType : std::false_type { +}; +template <> struct IsMirroredType : std::false_type { +}; +template <> struct IsMirroredType : std::false_type { +}; +template <> struct IsMirroredType : std::false_type { +}; +template <> struct IsMirroredType : std::false_type { +}; +template <> struct IsMirroredType : std::false_type { +}; +template <> struct IsMirroredType<__mpz_struct> : std::false_type { +}; +} // namespace jlcxx + +#endif diff --git a/deps/src/matrices.cpp b/deps/src/matrices.cpp new file mode 100644 index 000000000..a1832b7bb --- /dev/null +++ b/deps/src/matrices.cpp @@ -0,0 +1,82 @@ +#include "matrices.h" + +void singular_define_matrices(jlcxx::Module & Singular) +{ + Singular.method("ncols", [](matrix I) { return (int)MATCOLS(I); }); + + Singular.method("nrows", [](matrix I) { return (int)MATROWS(I); }); + + Singular.method("id_Module2Matrix", &id_Module2Matrix); + + Singular.method("id_Matrix2Module", &id_Matrix2Module); + + Singular.set_override_module(jl_base_module); + Singular.method("getindex", [](matrix M, int i, int j) { + return (poly)MATELEM(M, i, j); + }); + Singular.unset_override_module(); + + Singular.method("setindex", [](matrix M, poly p, int i, int j, ring R) { + MATELEM(M, i, j) = p_Copy(p, R); + }); + + Singular.method("mp_Copy", + [](matrix M, ring R) { return mp_Copy(M, R); }); + + Singular.method("mp_Delete", + [](matrix M, ring R) { return mp_Delete(&M, R); }); + + Singular.method("mp_Add", &mp_Add); + + Singular.method("mp_Sub", &mp_Sub); + + Singular.method("mp_Transp", &mp_Transp); + + Singular.method("mp_Mult", &mp_Mult); + + Singular.method("mp_MultP", &mp_MultP); + + Singular.method("pMultMp", &pMultMp); + + Singular.method("mp_Equal", &mp_Equal); + + Singular.method("mpNew", [](int r, int c) { + return mpNew(r, c); + }); + + Singular.method("mp_InitP", [](int n, poly p, ring R) { + return mp_InitP(n, n, p_Copy(p, R), R); + }); + + Singular.method("mp_Wedge", [](matrix M,int n, ring R) { + return mp_Wedge(M, n, R); + }); + + Singular.method("irrCharSeries", &singclap_irrCharSeries); + + Singular.method("iiStringMatrix", [](matrix I, int d, ring o) { + auto str_ptr = iiStringMatrix(I, d, o); + std::string s(iiStringMatrix(I, d, o)); + omFree(str_ptr); + return s; + }); + + Singular.method("bigintmat_init", [](int r, int c) { + return new bigintmat(r, c, coeffs_BIGINT); + }); + Singular.method("bigintmat_clear", [](bigintmat * m) { + delete m; + }); + Singular.method("bigintmat_nrows", [](bigintmat * m) { + return m->rows(); + }); + Singular.method("bigintmat_ncols", [](bigintmat * m) { + return m->cols(); + }); + Singular.method("bigintmat_viewindex", [](bigintmat * m, int i, int j) { + return m->view(i, j); + }); + Singular.method("bigintmat_rawset", [](bigintmat * m, number n, int i, int j) { + m->rawset(i, j, n, NULL); + }); +} diff --git a/deps/src/matrices.h b/deps/src/matrices.h new file mode 100644 index 000000000..e68b23a10 --- /dev/null +++ b/deps/src/matrices.h @@ -0,0 +1,8 @@ +#ifndef MATRICES_INCLUDE +#define MATRICES_INCLUDE + +#include "includes.h" + +void singular_define_matrices(jlcxx::Module &); + +#endif diff --git a/deps/src/rings.cpp b/deps/src/rings.cpp new file mode 100644 index 000000000..17ff06d4f --- /dev/null +++ b/deps/src/rings.cpp @@ -0,0 +1,636 @@ +#include "rings.h" + +auto rDefault_helper(coeffs cf, + jlcxx::ArrayRef vars, + rRingOrder_t ord) +{ + auto len = vars.size(); + char ** vars_ptr = new char *[len]; + for (int i = 0; i < len; i++) { + vars_ptr[i] = new char[vars[i].length() + 1]; + std::strcpy(vars_ptr[i], vars[i].c_str()); + } + auto r = rDefault(cf, len, vars_ptr, ord); + delete[] vars_ptr; + r->ShortOut = 0; + return r; +} + +/* + calling rDefault with a non-null wvhdl argument: + All ordering data should be passed in a serialized ord_data array. It is + then deserialized into the rDefault arguments. +*/ +auto rDefault_wvhdl_helper(coeffs cf, + jlcxx::ArrayRef vars, + jlcxx::ArrayRef ord_data, + unsigned long bitmask) +{ + int nvars = vars.size(); + char ** vars_ptr = new char *[nvars]; + + for (int i = 0; i < nvars; i++) + vars_ptr[i] = reinterpret_cast(vars[i]); + + size_t j = 0; + int nord = ord_data[j++]; + + // rDefault is going to take ownership of all 4 of these pointers + rRingOrder_t * ord = (rRingOrder_t *) omAlloc0((nord + 1) * sizeof(rRingOrder_t)); + int * blk0 = (int *) omAlloc0((nord + 1) * sizeof(int)); + int * blk1 = (int *) omAlloc0((nord + 1) * sizeof(int)); + int ** wvhdl = (int **) omAlloc0((nord + 1) * sizeof(int *)); + + for (int i = 0; i < nord; i++) + { + ord[i] = (rRingOrder_t) ord_data[j++]; + blk0[i] = ord_data[j++]; + blk1[i] = ord_data[j++]; + int len = ord_data[j++]; + if (len > 0) + { + wvhdl[i] = (int *) omAlloc0(len * sizeof(int)); + for (int k = 0; k < len; k++) + wvhdl[i][k] = ord_data[j++]; + } + else + { + wvhdl[i] = nullptr; + } + } + + auto r = rDefault(cf, nvars, vars_ptr, nord, ord, blk0, blk1, wvhdl, bitmask); + delete[] vars_ptr; + r->ShortOut = 0; + + return r; +} + +/* + Serialize the ord, blk0, blk1, wvhdl data + call with ord_data.size() == 0 since ArrayRef doesn't support resize +*/ +void rOrdering_helper(jlcxx::ArrayRef ord_data, const ring r) +{ + int l; + size_t initial_size = ord_data.size(); + + ord_data.push_back(0); + + for (l = 0; r->order[l]; l++) + { + rRingOrder_t ord = r->order[l]; + ord_data.push_back(static_cast(ord)); + ord_data.push_back(r->block0[l]); + ord_data.push_back(r->block1[l]); + if (r->wvhdl[l] == nullptr) + { + ord_data.push_back(0); + } + else if (ord == ringorder_wp || ord == ringorder_Wp || + ord == ringorder_ws || ord == ringorder_Ws || + ord == ringorder_a || ord == ringorder_am || ord == ringorder_M) + { + int n = r->block1[l] - r->block0[l] + 1; + if (ord == ringorder_M) + n = n*n; + ord_data.push_back(n); + for (int i = 0; i < n; i++) + ord_data.push_back(r->wvhdl[l][i]); + } + else + { + ord_data.push_back(0); + } + } + + ord_data[initial_size] = l; +} + +auto rDefault_long_helper(coeffs cf, + jlcxx::ArrayRef vars, + jlcxx::ArrayRef ord, + int * blk0, + int * blk1, + unsigned long bitmask) +{ + auto len = vars.size(); + char ** vars_ptr = new char *[len]; + for (int i = 0; i < len; i++) { + vars_ptr[i] = reinterpret_cast(vars[i]); + // std::strcpy(vars_ptr[i],vars[i].c_str()); + } + auto len_ord = ord.size(); + rRingOrder_t * ord_ptr = + (rRingOrder_t *)omAlloc0(len_ord * sizeof(rRingOrder_t)); + for (int i = 0; i < len_ord; i++) { + ord_ptr[i] = ord[i]; + } + int ** wvhdl = NULL; + auto r = rDefault(cf, len, vars_ptr, len_ord, ord_ptr, blk0, blk1, wvhdl, + bitmask); + delete[] vars_ptr; + r->ShortOut = 0; + return r; +} + +// turn a normal commutative ring into WeylAlgebra +// ownership of r is taken, so the caller doesn't have to clean up r +ring weylAlgebra(ring r) +{ + // vars = indeterminates x1, ..., xn and then partials Dx1, ..., Dxn + int n = r->N/2; + assume(2*n == r->N); + matrix C = mpNew(2*n, 2*n); + matrix D = mpNew(2*n, 2*n); + + for (int i = 1; i <= n; i++) + for (int j = 1; j <= n; j++) + { + if (i < j) + { + // xj*xi = xi*xj + MATELEM(C,i,j) = p_One(r); + + // Dxj*Dxi = Dxi*Dxj + MATELEM(C,n+i,n+j) = p_One(r); + } + + // Dxj*xi = xi*Dxj + bool(i == j) + MATELEM(C,i,n+j) = p_One(r); + if (i == j) + MATELEM(D,i,n+j) = p_One(r); + } + + ring R = rCopy(r); + nc_CallPlural(C,D,NULL,NULL,R,true,false,true,r); + + // nc_CallPlural seems to take ownership of the matrices + //mp_Delete(&C, r); + //mp_Delete(&D, r); + + rDelete(r); + return R; +} + +// adapted from jiA_RING in ipassign.cc +ring make_qring(ring r, ideal id) +{ + const ring origin = currRing; + rChangeCurrRing(r); + + coeffs newcf = currRing->cf; + + const int cpos = idPosConstant(id); + if (rField_is_Ring(currRing)) + { + if (cpos >= 0) + { + newcf = n_CoeffRingQuot1(p_GetCoeff(id->m[cpos], currRing), currRing->cf); + if (newcf == NULL) + { + rChangeCurrRing(origin); + return NULL; + } + } + } + + ring qr = rCopy(currRing); + assume(qr->cf == currRing->cf); + + if (qr->cf != newcf) + { + nKillChar(qr->cf); // ??? + qr->cf = newcf; + } + + ideal qid; + + if((rField_is_Ring(currRing)) && (cpos != -1)) + { + int i, j; + int *perm = (int *)omAlloc0((qr->N+1)*sizeof(int)); + + for(i=qr->N;i>0;i--) + perm[i]=i; + + nMapFunc nMap = n_SetMap(currRing->cf, newcf); + qid = idInit(IDELEMS(id)-1,1); + for (i = 0, j = 0; im[j++] = p_PermPoly(id->m[i], perm, currRing, qr, nMap, NULL, 0); + } + else + { + qid = idrCopyR(id,currRing,qr); + } + + idSkipZeroes(qid); + + if (currRing->qideal!=NULL) /* we are already in a qring! */ + { + ideal tmp=idSimpleAdd(qid,currRing->qideal); + // both ideals should be GB, so dSimpleAdd is sufficient + idDelete(&qid); + qid=tmp; + // delete the qr copy of quotient ideal!!! + idDelete(&qr->qideal); + } + if (idElem(qid)==0) + { + qr->qideal = NULL; + id_Delete(&qid,currRing); + } + else + { + qr->qideal = qid; + } + + // qr is a copy of currRing with the new qideal! + #ifdef HAVE_PLURAL + if (rIsPluralRing(currRing) &&(qr->qideal!=NULL)) + { + if (nc_SetupQuotient(qr, currRing)) + { + //WarnS("error in nc_SetupQuotient"); + } + } + #endif + + rChangeCurrRing(origin); + return qr; +} + +// turn a normal commutative ring into ExteriorAlgebra +// ownership of r is taken, so the caller doesn't have to clean up r +ring exteriorAlgebra(ring r) +{ + int n = rVar(r); + // first construct relations xj*xi = -xi*xj + poly p = p_Neg(p_One(r), r); + ring R = rCopy(r); + nc_CallPlural(NULL,NULL,p,NULL,R,true,false,true,r); + // then add xi^2 = 0 + ideal q = idInit(n,1); + for (int i = 1; i <= n; i++) + q->m[i-1] = p_Power(rGetVar(i, R), 2, R); + ring S = make_qring(R, q); + id_Delete(&q, R); + p_Delete(&p, r); + rDelete(R); + rDelete(r); + return S; +} + +void singular_define_rings(jlcxx::Module & Singular) +{ + Singular.method("toPolyRef", [](void * ptr) { + return reinterpret_cast(ptr); + }); + Singular.method("freeAlgebra", &freeAlgebra); + Singular.method("weylAlgebra", &weylAlgebra); + Singular.method("exteriorAlgebra", &exteriorAlgebra); + Singular.method("rDefault_helper", &rDefault_helper); + Singular.method("rDefault_wvhdl_helper", &rDefault_wvhdl_helper); + Singular.method("rOrdering_helper", &rOrdering_helper); // inverse of rDefault_wvhdl_helper + Singular.method("rDefault_long_helper", &rDefault_long_helper); + Singular.method("nc_CallPlural", [](matrix C, matrix D, ring r) { + ring R = rCopy(r); + nc_CallPlural(mp_Copy(C,r), mp_Copy(D,r), NULL, NULL, R, true, false, true, r); + return R; + }); + Singular.method("rDelete", &rDelete); + Singular.method("rString", [](ip_sring * r) { + auto s = rString(r); + std::string ret_string(s); + omFree(s); + return ret_string; + }); + Singular.method("rChar", &rChar); + Singular.method("rGetVar", &rGetVar); + Singular.method("rVar", &rVar); + Singular.method("rIsPluralRing", [](const ring r) { + // return is an honest bool + #ifdef HAVE_PLURAL + return r->GetNC() != NULL; + #else + return false; + #endif + }); + Singular.method("rIsLPRing", [](const ring r) { + // return is 0 for not letterplace Ring + // otherwise the number of variables for this letterplace ring + #ifdef HAVE_SHIFTBBA + return r->isLPring; + #else + return short(0); + #endif + }); + Singular.method("rRingVar", [](short i, const ring r) { + return std::string(rRingVar(i, r)); + }); + Singular.method("rGetExpSize", [](unsigned long bitmask, int N) { + int bits; + return static_cast(rGetExpSize(bitmask, bits, N)); + }); + Singular.method("rCoeffPtr", [](ring r){return r->cf;}); + Singular.method("rHasGlobalOrdering", &rHasGlobalOrdering); + Singular.method("rHasMixedOrdering", &rHasMixedOrdering); + Singular.method("rRing_ord_pure_dp", &rRing_ord_pure_dp); + Singular.method("rRing_ord_pure_Dp", &rRing_ord_pure_Dp); + Singular.method("rRing_ord_pure_lp", &rRing_ord_pure_lp); + Singular.method("rIsQuotientRing", [](ring r) { + return r->qideal != NULL; + }); + Singular.method("rCopy", rCopy); + Singular.method("r_get_qideal", [](ring r) {return r->qideal;}); + Singular.method("rQuotientRing", [](ideal i, ring r) { + // This looks too simple, try make_qring if it doesn't work. + ring Q = rCopy(r); + Q->qideal = id_Copy(i, r); + return Q; + }); + Singular.method("make_qring", &make_qring); + Singular.method("rBitmask", + [](ip_sring * r) { return (unsigned int)r->bitmask; }); + Singular.method("rPar", [](coeffs cf){ + return n_NumberOfParameters(cf); + }); + Singular.method("p_Delete", [](spolyrec * p, ip_sring * r) { + return p_Delete(&p, r); + }); + Singular.method("p_Copy", + [](spolyrec * p, ip_sring * r) { return p_Copy(p, r); }); + Singular.method("p_IsOne", p_IsOne); + Singular.method("p_One", p_One); + Singular.method("p_IsUnit", p_IsUnit); + Singular.method("p_GetExp", [](spolyrec * p, int i, ip_sring * r) { + return p_GetExp(p, i, r); + }); + Singular.method("p_GetComp", [](spolyrec * p, ip_sring * r) { + return p_GetComp(p, r); + }); + Singular.method("p_String", [](spolyrec * p, ip_sring * r) { + auto s_ptr = p_String(p, r); + std::string s(s_ptr); + omFree(s_ptr); + return s; + }); + Singular.method("p_ISet", p_ISet); + Singular.method("p_NSet", p_NSet); + Singular.method("p_NSet", + [](void * p, ip_sring * r) { return p_NSet(reinterpret_cast(p), r); } + ); + Singular.method("pLength", pLength); + Singular.method("SetpNext", + [](spolyrec * p, spolyrec * q) { p->next = q; }); + Singular.method("pNext", [](spolyrec * a) { + poly p = pNext(a); + return p; + }); + Singular.method("p_Init", [](ip_sring * r) { return p_Init(r); }); + Singular.method("p_Head", [](spolyrec * a, ip_sring * r) { + poly p = p_Head(a, r); return p; }); + Singular.method("p_SetCoeff0", [](spolyrec * a, snumber * n, ip_sring * r) { + p_SetCoeff0(a, n, r); }); + Singular.method("p_SetExp", [](spolyrec * a, int i, int v, ip_sring * r) { + p_SetExp(a, i, v, r); }); + Singular.method("p_SetNext", [](spolyrec * a, spolyrec * m) { + pNext(a) = m; }); + Singular.method("p_SortMerge", [](spolyrec * a, ip_sring * r) { + return p_SortMerge(a, r); }); + Singular.method("p_SortAdd", p_SortAdd); + Singular.method("p_Setm", p_Setm); + Singular.method("p_Neg", p_Neg); + Singular.method("p_WTotaldegree", p_WTotaldegree); + Singular.method("p_Homogen", p_Homogen); + Singular.method("pGetCoeff", [](spolyrec * p) { return pGetCoeff(p); }); + Singular.method("pSetCoeff", [](poly p, long c, ring r) { + number n = n_Init(c, r->cf); + return p_SetCoeff(p, n, r); + }); + Singular.method("pSetCoeff0", [](poly p, long c, ring r) { + number n = n_Init(c, r->cf); + return p_SetCoeff0(p, n, r); + }); + Singular.method("pLDeg", [](spolyrec * a, ip_sring * r) { + long res; + int dummy; + if (a != NULL) { + res = r->pLDeg(a, &dummy, r); + } + else { + res = -1; + } + return res; + }); + Singular.method("p_Add_q", [](spolyrec * p, spolyrec * q, ip_sring * r) { + return p_Add_q(p, q, r); + }); + Singular.method("p_Sub", p_Sub); + Singular.method("p_Mult_q", p_Mult_q); + Singular.method("pp_Mult_qq", pp_Mult_qq); + Singular.method("p_Power", p_Power); + Singular.method("p_Compare", p_Compare); + Singular.method("p_EqualPolys", + [](spolyrec * p, spolyrec * q, ip_sring * r) { + return p_EqualPolys(p, q, r); + }); + Singular.method("p_Divide", p_Divide); + Singular.method("p_DivRem", [](spolyrec * a, spolyrec * b, ip_sring * r) { + poly rest; + poly q = p_DivRem(a, b, rest, r); + return std::make_tuple(reinterpret_cast(q), reinterpret_cast(rest)); + }); + Singular.method("p_Div_nn", p_Div_nn); + Singular.method("p_Mult_nn", [](poly p, number n, ring r) { + return p_Mult_nn(p, n, r); + }); + Singular.method("p_LmIsConstant", [](poly p, ring r) { + return p_LmIsConstant(p, r) != 0; + }); + Singular.method("p_LmIsConstantComp", [](poly p, ring r) { + return p_LmIsConstantComp(p, r) != 0; + }); + Singular.method("p_IsDivisibleBy", [](spolyrec * p, spolyrec * q, ip_sring * r) { + poly res; + ideal I = idInit(1, 1); + const ring origin = currRing; + I->m[0] = q; + rChangeCurrRing(r); + res = kNF(I, NULL, p, 0, KSTD_NF_LAZY); + rChangeCurrRing(origin); + I->m[0] = NULL; + id_Delete(&I, r); + if (res == NULL) + return true; + else + { + p_Delete(&res, r); + return false; + } + }); + Singular.method("singclap_gcd", singclap_gcd); + + Singular.method("singclap_extgcd", [](spolyrec * a, spolyrec * b, ip_sring * r) { + poly res, s, t; + singclap_extgcd(a, b, res, s, t, r); + return std::make_tuple(res, s, t); + }); + + /* TODO check if we can get rid of this nonsensical function */ + Singular.method("p_ExtGcd_internal", [](spolyrec * a, spolyrec * b, + void * res, void * s, void * t, + ip_sring * r) { + return singclap_extgcd(a, b, reinterpret_cast(res), + reinterpret_cast(s), + reinterpret_cast(t), r); + }); + Singular.method("singclap_sqrfree", + [](spolyrec * p, jlcxx::ArrayRef a, ip_sring * r) { + const ring origin = currRing; + rChangeCurrRing(r); + intvec * v = NULL; + ideal I = singclap_sqrfree(pCopy(p), &v, 0, currRing); + int * content = v->ivGetVec(); + for(int i=0; ilength(); i++) + { + a.push_back(content[i]); + } + rChangeCurrRing(origin); + delete v; + return I; + }); + Singular.method("singclap_factorize", + [](spolyrec * p, jlcxx::ArrayRef a, ip_sring * r) { + const ring origin = currRing; + rChangeCurrRing(r); + intvec * v = NULL; + ideal I = singclap_factorize(p_Copy(p,r), &v, 0, r); + int * content = v->ivGetVec(); + for(int i=0; ilength(); i++) + { + a.push_back(content[i]); + } + rChangeCurrRing(origin); + delete v; + return I; + }); + Singular.method("p_Content", p_Content); + Singular.method("p_GetExpVL_internal", p_GetExpVL); + Singular.method("p_GetExpVLV_internal", p_GetExpVLV); + Singular.method("p_SetExpV_internal", p_SetExpV); + Singular.method("p_SetExpVL_internal", p_SetExpVL); + Singular.method("p_SetExpVLV_internal", p_SetExpVLV); + Singular.method("p_Reduce", + [](spolyrec * p, sip_sideal * G, ip_sring * R) { + const ring origin = currRing; + rChangeCurrRing(R); + poly res = kNF(G, R->qideal, p); + rChangeCurrRing(origin); + return res; + }); + Singular.method("p_Reduce", + [](sip_sideal * p, sip_sideal * G, ip_sring * R) { + const ring origin = currRing; + rChangeCurrRing(R); + ideal res = kNF(G, R->qideal, p); + rChangeCurrRing(origin); + return res; + }); + Singular.method("p_Reduce", + [](spolyrec * p, sip_sideal * G, ip_sring * R, int flag) { + const ring origin = currRing; + rChangeCurrRing(R); + poly res = kNF(G, R->qideal, p, 0, flag); + rChangeCurrRing(origin); + return res; + }); + Singular.method("p_Reduce", + [](sip_sideal * p, sip_sideal * G, ip_sring * R, int flag) { + const ring origin = currRing; + rChangeCurrRing(R); + ideal res = kNF(G, R->qideal, p, 0, flag); + rChangeCurrRing(origin); + return res; + }); + + Singular.method("letterplace_ring_helper", + [](ip_sring * r, long block_size) { + rUnComplete(r); + r->isLPring = block_size; + r->ShortOut = FALSE; + r->CanShortOut = FALSE; + rComplete(r); + }); + + Singular.method("p_Subst", [](poly p, int i, poly q, ring r) { + poly p_cp = p_Copy(p, r); + return p_Subst(p_cp, i, q, r); + }); + Singular.method("maEvalAt", [](poly p, jlcxx::ArrayRef vals, ring r) { + number * varr = (number *) omAlloc0(vals.size() * sizeof(number)); + for (int i = 0; i < vals.size(); i++) + varr[i] = (number) vals[i]; + number res = maEvalAt(p, varr, r); + omFree(varr); + return res; + }); + Singular.method("p_PermPoly", [](poly p, int * perm, ring old_ring, + ring new_ring, void * map_func_ptr, int * par_perm) { + nMapFunc map_func = reinterpret_cast(map_func_ptr); + return p_PermPoly(p, perm, old_ring, new_ring, map_func, par_perm); + }); + Singular.method("maFindPerm", [](ring src, jlcxx::ArrayRef perm, ring dst, + jlcxx::ArrayRef par_perm){ + int *perm1 = (int *)omAlloc0((rVar(src)+1)*sizeof(int)); + int *par_perm1 = NULL; + if (rPar(src) != 0) par_perm1 = (int *)omAlloc0((rPar(src) + 1)*sizeof(int)); + maFindPerm(src->names, rVar(src), rParameter(src), rPar(src), + dst->names, rVar(dst), rParameter(dst), rPar(dst), + perm1, par_perm1, dst->cf->type); + for(int i = 0; i < rVar(src); i++) + { + perm.push_back(perm1[i]); + } + for(int j = 0; j < rPar(src); j++) + { + par_perm.push_back(par_perm1[j]); + } + }); + Singular.method("p_Jet", + [](poly p, int i, ring r) { + poly p_cp = p_Copy(p, r); + return p_Jet(p_cp, i, r); + }); + Singular.method("p_Diff", + [](poly p, int i, ring r) { + poly p_cp = p_Copy(p, r); + return p_Diff(p_cp, i, r); + }); + Singular.method("maMapPoly", + [](poly map_p, ring pr, ideal im_id, ring im, void * cf_map) { + return maMapPoly(map_p, pr, im_id, im, reinterpret_cast(cf_map)); + }); + Singular.method("p_GetOrder", + [](poly p, ring r) { + long res; + if( p != NULL) + { res = p_GetOrder(p, r);} + else + { res = -1;} + return res; + }); + + // creates an opposite algebra of R + // ring rOpposite(ring src) + Singular.method("rOpposite", rOpposite); + + // opposes a vector p from Rop to currRing (dst!) + // poly pOppose(ring Rop, poly p, const ring dst) + Singular.method("pOppose", pOppose); + + // opposes a module I from Rop to currRing(dst) + // ideal idOppose(ring Rop, ideal I, const ring dst) + Singular.method("idOppose", idOppose); +} diff --git a/deps/src/rings.h b/deps/src/rings.h new file mode 100644 index 000000000..b320c64ef --- /dev/null +++ b/deps/src/rings.h @@ -0,0 +1,8 @@ +#ifndef RINGS_INCLUDE +#define RINGS_INCLUDE + +#include "includes.h" + +void singular_define_rings(jlcxx::Module &); + +#endif diff --git a/deps/src/run.jl b/deps/src/run.jl new file mode 100644 index 000000000..60c8de30e --- /dev/null +++ b/deps/src/run.jl @@ -0,0 +1,40 @@ +# This script builds libsingular-julia, then starts a fresh Julia instances +# with an appropriate override set for e.g. running the test suite or whatever +# else you'd like. Arguments are passed on verbatim to the subprocess julia, +# so you can invokes this kinda like you'd invoke Julia + +@info "Install needed packages" +using Pkg +Pkg.add(["Singular_jll", "CxxWrap", "CMake", "libsingular_julia_jll"]) +using libsingular_julia_jll + + +@info "Build libsingular-julia" +include("build.jl") + + +mktempdir() do tmpdepot + @info "Created temporary depot at $(tmpdepot)" + + # create override file for libsingular_julia_jll + uuid = string(Base.identify_package("libsingular_julia_jll").uuid) + mkpath(joinpath(tmpdepot, "artifacts")) + open(joinpath(tmpdepot, "artifacts", "Overrides.toml"), "w") do f + write(f, """ + [$(uuid)] + libsingular_julia = "$(installdir)" + """) + end + + # prepend our temporary depot to the depot list... + withenv("JULIA_DEPOT_PATH"=>tmpdepot*":") do + # we need to make sure that precompilation is run again with the override in place + # (just running Pkg.precompile() does not seem to suffice) + run(`touch $(pathof(libsingular_julia_jll))`) + # ... and start Julia, by default with the same project environment + run(`$(Base.julia_cmd()) --project=$(Base.active_project()) $(ARGS)`) + + # TODO: perform some additional steps here, e.g. perhaps + # verify that `libsingular_julia_jll.artifact_dir` is set right? + end +end diff --git a/deps/src/singular.cpp b/deps/src/singular.cpp new file mode 100644 index 000000000..3f00e800a --- /dev/null +++ b/deps/src/singular.cpp @@ -0,0 +1,367 @@ +#include "includes.h" +#include "coeffs.h" +#include "rings.h" +#include "ideals.h" +#include "matrices.h" +#include "caller.h" +#include "coeff_rings.h" + +static std::string singular_return; +static std::string singular_error; +static std::string singular_warning; +static std::vector singular_error_log; + +// Internal singular interpreter variable +extern int inerror; + +// these are the temporary callbacks for calls to the interpreter +static void WerrorS_for_julia(const char * s) +{ + singular_error += s; +} + +static void PrintS_for_julia(const char * s) +{ + singular_return += s; +} + +static void WarningS_for_julia(const char * s) +{ + singular_warning += s; +} + +/* + This is the non-temporary callback for all errors (unless the temporary + ones are in use by call_interpreter). We would like to simultaneously: + 1. be able to check and report errors via libSingular.check_error() + 2. know when errors have been generated but uncaught by the julia code so + that libSingular.check_error() can be inserted into the right place + Unfortunately, a single call to the Singular kernel can generate multiple + calls to WerrorS_callback, thus we don't know if previous errors were + generated as a result of a missing libSingular.check_error() or if Singular + has just called WerrorS_callback 10 times in the same function. + The compromise here is to keep the full backlog of unreported errors and + start complaining to stderr once the backlog gets too long. +*/ +static void WerrorS_and_reset(const char * s) +{ + errorreported = 0; + if (singular_error_log.size() > 9) + { + for (auto & si : singular_error_log) + std::cerr << si << std::endl; + std::cerr << "!!! Singular error(s) unhandled by julia !!!" << std::endl << std::endl; + } + singular_error_log.emplace_back(s); +} + +JLCXX_MODULE define_julia_module(jlcxx::Module & Singular) +{ + Singular.add_type("coeffs"); + Singular.add_bits("n_coeffType"); + Singular.set_const("n_Z", n_Z); + Singular.set_const("n_Q", n_Q); + Singular.set_const("n_Zn", n_Zn); + Singular.set_const("n_Zp", n_Zp); + Singular.set_const("n_GF", n_GF); + Singular.set_const("n_transExt", n_transExt); + Singular.set_const("n_unknown", n_unknown); + Singular.add_type("number"); + Singular.add_type<__mpz_struct>("__mpz_struct"); + Singular.add_type("ring"); + Singular.add_type("poly"); + // Singular.add_type("nMapFunc"); + // Singular.add_type("vector"); + Singular.add_bits("rRingOrder_t"); + Singular.add_type("ideal"); + Singular.add_type("ip_smatrix"); + Singular.add_type("syStrategy"); + Singular.add_type("sip_smap"); + Singular.add_type("bigintmat"); + + /* monomial orderings */ + Singular.set_const("ringorder_no", ringorder_no); + Singular.set_const("ringorder_lp", ringorder_lp); + Singular.set_const("ringorder_rp", ringorder_rp); + Singular.set_const("ringorder_dp", ringorder_dp); + Singular.set_const("ringorder_Dp", ringorder_Dp); + Singular.set_const("ringorder_wp", ringorder_wp); + Singular.set_const("ringorder_Wp", ringorder_Wp); + Singular.set_const("ringorder_ls", ringorder_ls); + Singular.set_const("ringorder_rs", ringorder_rs); + Singular.set_const("ringorder_ds", ringorder_ds); + Singular.set_const("ringorder_Ds", ringorder_Ds); + Singular.set_const("ringorder_ws", ringorder_ws); + Singular.set_const("ringorder_Ws", ringorder_Ws); + Singular.set_const("ringorder_a", ringorder_a); + Singular.set_const("ringorder_M", ringorder_M); + Singular.set_const("ringorder_c", ringorder_c); + Singular.set_const("ringorder_C", ringorder_C); + Singular.set_const("ringorder_s", ringorder_s); + Singular.set_const("ringorder_S", ringorder_S); + Singular.set_const("ringorder_IS", ringorder_IS); + + Singular.method("ringorder_to_int", [](rRingOrder_t a) { + return static_cast(a); + }); + Singular.method("ringorder_from_int", [](int a) { + return static_cast(a); + }); + + Singular.method("siInit", [](const char * path) { + siInit(const_cast(path)); + WerrorS_callback = WerrorS_and_reset; + }); + Singular.method("versionString", []() { + return const_cast(versionString()); + }); + Singular.method("version", []() { + return SINGULAR_VERSION; + }); + + Singular.method("have_error", []() { + return !singular_error_log.empty(); + }); + + Singular.method("get_and_clear_error", []() { + std::stringstream ss; + for (auto & si : singular_error_log) + ss << si << std::endl; + singular_error_log.clear(); + return ss.str(); + }); + +#define SETTER(A, B) \ + else if (opt == #B) \ + { \ + old_value = (A & Sy_bit(B)) != 0; \ + A = value ? (A | Sy_bit(B)) : (A & ~Sy_bit(B)); \ + } + + // all of the global setters return the previous value + Singular.method("set_option", [](std::string opt, bool value) + { + bool old_value = false; + if (false); + SETTER(si_opt_2, V_QUIET) + SETTER(si_opt_2, V_QRING) + SETTER(si_opt_2, V_SHOW_MEM) + SETTER(si_opt_2, V_YACC) + SETTER(si_opt_2, V_REDEFINE) + SETTER(si_opt_2, V_LOAD_LIB) + SETTER(si_opt_2, V_DEBUG_LIB) + SETTER(si_opt_2, V_LOAD_PROC) + SETTER(si_opt_2, V_DEF_RES) + SETTER(si_opt_2, V_SHOW_USE) + SETTER(si_opt_2, V_IMAP) + SETTER(si_opt_2, V_PROMPT) + SETTER(si_opt_2, V_NSB) + SETTER(si_opt_2, V_CONTENTSB) + SETTER(si_opt_2, V_CANCELUNIT) + SETTER(si_opt_2, V_MODPSOLVSB) + SETTER(si_opt_2, V_UPTORADICAL) + SETTER(si_opt_2, V_FINDMONOM) + SETTER(si_opt_2, V_COEFSTRAT) + SETTER(si_opt_2, V_IDLIFT) + SETTER(si_opt_2, V_LENGTH) + SETTER(si_opt_2, V_ALLWARN) + SETTER(si_opt_2, V_INTERSECT_ELIM) + SETTER(si_opt_2, V_INTERSECT_SYZ) + SETTER(si_opt_2, V_DEG_STOP) + + SETTER(si_opt_1, OPT_PROT) + SETTER(si_opt_1, OPT_REDSB) + SETTER(si_opt_1, OPT_NOT_BUCKETS) + SETTER(si_opt_1, OPT_NOT_SUGAR) + SETTER(si_opt_1, OPT_INTERRUPT) + SETTER(si_opt_1, OPT_SUGARCRIT) + SETTER(si_opt_1, OPT_DEBUG) + SETTER(si_opt_1, OPT_REDTHROUGH) + SETTER(si_opt_1, OPT_NO_SYZ_MINIM) + SETTER(si_opt_1, OPT_RETURN_SB) + SETTER(si_opt_1, OPT_FASTHC) + SETTER(si_opt_1, OPT_OLDSTD) + SETTER(si_opt_1, OPT_STAIRCASEBOUND) + SETTER(si_opt_1, OPT_MULTBOUND) + SETTER(si_opt_1, OPT_DEGBOUND) + SETTER(si_opt_1, OPT_REDTAIL) + SETTER(si_opt_1, OPT_INTSTRATEGY) + SETTER(si_opt_1, OPT_FINDET) + SETTER(si_opt_1, OPT_INFREDTAIL) + SETTER(si_opt_1, OPT_SB_1) + SETTER(si_opt_1, OPT_NOTREGULARITY) + SETTER(si_opt_1, OPT_WEIGHTM) + else + { + std::cerr << "unknown option " << opt << std::endl; + } + return old_value; + }); + +#undef SETTER + + // the "printlevel" system variable in Singular + Singular.method("set_printlevel", [](int level) { + int old_level = printlevel; + printlevel = level; + return old_level; + }); + + // the "degBound" system variable in Singular + Singular.method("set_degBound", [](int degb) { + int old_degb = Kstd1_deg; + Kstd1_deg = degb; + if (Kstd1_deg != 0) + si_opt_1 |= Sy_bit(OPT_DEGBOUND); + else + si_opt_1 &= ~Sy_bit(OPT_DEGBOUND); + return old_degb; + }); + + // the "multBound" system variable in Singular + Singular.method("set_multBound", [](int mu) { + int old_mu = Kstd1_mu; + Kstd1_mu = mu; + if (Kstd1_mu != 0) + si_opt_1 |= Sy_bit(OPT_MULTBOUND); + else + si_opt_1 &= ~Sy_bit(OPT_MULTBOUND); + return old_mu; + }); + + singular_define_coeffs(Singular); + singular_define_rings(Singular); + singular_define_ideals(Singular); + singular_define_matrices(Singular); + singular_define_caller(Singular); + singular_define_coeff_rings(Singular); + + + // Calls the Singular interpreter with `input`. + // `input` needs to be valid Singular input. + // Returns a 4-tuple: + // 1. entry is a bool, indicated if an error has happened + // 2. entry is the output as a string + // 3. entry is the error output as a string + // 4. entry is the warning output as a string + Singular.method("call_interpreter", [](std::string input) { + // save callbacks + auto default_print = PrintS_callback; + auto default_error = WerrorS_callback; + auto default_warning = WarnS_callback; + + // set temporary new callbacks + PrintS_callback = PrintS_for_julia; + WerrorS_callback = WerrorS_for_julia; + WarnS_callback = WarningS_for_julia; + + // cleanup return strings + singular_return.clear(); + singular_error.clear(); + singular_warning.clear(); + + // call interpreter + std::string input_str = input + "\nreturn();"; + bool err = iiAllStart(NULL, const_cast(input_str.c_str()), + BT_proc, 0); + inerror = 0; + errorreported = 0; + + // get output + jl_array_t * result = jl_alloc_array_1d(jl_array_any_type, 4); + jl_arrayset(result, err ? jl_true : jl_false, 0); + jl_arrayset(result, jl_cstr_to_string(singular_return.c_str()), 1); + jl_arrayset(result, jl_cstr_to_string(singular_error.c_str()), 2); + jl_arrayset(result, jl_cstr_to_string(singular_warning.c_str()), 3); + + // restore old callbacks + PrintS_callback = default_print; + WerrorS_callback = default_error; + WarnS_callback = default_warning; + + return reinterpret_cast(result); + }); + + /**************************** + ** from resolutions.jl + ***************************/ + + Singular.method("res_Delete_helper", + [](syStrategy ra, ring o) { syKillComputation(ra, o); }); + + Singular.method("res_Copy", [](syStrategy ra, ring o) { + const ring origin = currRing; + rChangeCurrRing(o); + syStrategy temp = syCopy(ra); + rChangeCurrRing(origin); + return temp; + }); + + Singular.method("getindex_internal", + [](syStrategy ra, int64_t k, bool minimal) { + if (minimal) { + return ra->minres[k]; + } + return (ideal)ra->fullres[k]; + }); + + Singular.method("syMinimize", [](syStrategy ra, ring o) { + const ring origin = currRing; + rChangeCurrRing(o); + syStrategy result = syCopy(ra); + syMinimize(result); + rChangeCurrRing(origin); + return result; + }); + + Singular.method("get_minimal_res", [](syStrategy ra) { + return reinterpret_cast(ra->minres); + }); + + Singular.method("get_full_res", [](syStrategy ra) { + return reinterpret_cast(ra->fullres); + }); + + Singular.method("get_sySize", [](syStrategy ra) { + return static_cast(sySize(ra)); + }); + + Singular.method("create_SyStrategy", [](void * res_void, int64_t len, + ring r) { + resolvente res = reinterpret_cast(res_void); + syStrategy result = (syStrategy)omAlloc0(sizeof(ssyStrategy)); + result->list_length = static_cast(len); + result->length = static_cast(len); + resolvente res_cp = (resolvente)omAlloc0((len + 1) * sizeof(ideal)); + for (int i = 0; i <= len; i++) { + if (res[i] != NULL) { + res_cp[i] = id_Copy(res[i], r); + } + } + result->fullres = res_cp; + result->syRing = r; + return result; + }); + + Singular.method("syBetti_internal", [](void * ra, int len, ring o) { + const ring origin = currRing; + rChangeCurrRing(o); + int dummy; + intvec * iv = syBetti(reinterpret_cast(ra), len, &dummy, + NULL, FALSE, NULL); + rChangeCurrRing(origin); + int nrows = iv->rows(); + int ncols = iv->cols(); + auto betti = (int *)malloc(ncols * nrows * sizeof(int)); + for (int i = 0; i < ncols; i++) { + for (int j = 0; j < nrows; j++) { + betti[i * nrows + j] = IMATELEM(*iv, j + 1, i + 1); + } + } + delete (iv); + return std::make_tuple(betti, nrows, ncols); + }); + + Singular.method("PrintS",&PrintS); + Singular.method("StringAppendS",&StringAppendS); +} diff --git a/deps/src/threading.cpp b/deps/src/threading.cpp new file mode 100644 index 000000000..dd55f3262 --- /dev/null +++ b/deps/src/threading.cpp @@ -0,0 +1,5 @@ +#include "threading.h" + +namespace singularjl { + std::recursive_mutex global_singular_lock; +} diff --git a/deps/src/threading.h b/deps/src/threading.h new file mode 100644 index 000000000..7b63fd6e2 --- /dev/null +++ b/deps/src/threading.h @@ -0,0 +1,19 @@ +#include "xcode_jlcxx_workaround.h" + +#include + +#ifdef THREADSAFE_SINGULAR + +namespace singularjl { + extern std::recursive_mutex global_singular_lock; +} + +#define ENTER_SINGULAR (singularjl::global_singular_lock.lock()) +#define LEAVE_SINGULAR (singularjl::global_singular_lock.unlock()) + +#else + +#define ENTER_SINGULAR ((void) 0) +#define LEAVE_SINGULAR ((void) 0) + +#endif diff --git a/deps/src/xcode_jlcxx_workaround.h b/deps/src/xcode_jlcxx_workaround.h new file mode 100644 index 000000000..8b7c54467 --- /dev/null +++ b/deps/src/xcode_jlcxx_workaround.h @@ -0,0 +1,29 @@ +#ifndef XCODE_JLCXX_WORKAROUND +#define XCODE_JLCXX_WORKAROUND + +// This must be the very first include +#ifdef _LIBCPP_CONFIG +#error This header must be included before any system headers! +#endif + +// Work around Xcode 11.4 issue until upstream libc++ fix arrives in Xcode: +// https://github.com/llvm/llvm-project/commit/2464d8135e +// +// First include __config from libc++, then override typeinfo flag +// to force use of address as hash instead of hashing the string. + +#if defined(__APPLE__) && defined(FORCE_XCODE_TYPEINFO_MERGED) +#include <__config> +#if defined(_LIBCPP_HAS_MERGED_TYPEINFO_NAMES_DEFAULT) && \ + _LIBCPP_HAS_MERGED_TYPEINFO_NAMES_DEFAULT == 0 +#undef _LIBCPP_HAS_MERGED_TYPEINFO_NAMES_DEFAULT +#define _LIBCPP_HAS_MERGED_TYPEINFO_NAMES_DEFAULT 1 +#else +#error Trying to work around Xcode 11.4 bug but libc++ macro not set as expected! \ + Please try rebuilding and create an issue if this reappears. +#endif +#endif + +#include "jlcxx/jlcxx.hpp" + +#endif