Add files

This commit is contained in:
2025-01-14 01:15:48 +01:00
commit 2f9fcec55b
406 changed files with 87154 additions and 0 deletions

90
.gitignore vendored Normal file
View File

@@ -0,0 +1,90 @@
# http://www.gnu.org/software/automake
Makefile.in
# http://www.gnu.org/software/autoconf
/autom4te.cache
/aclocal.m4
/compile
/configure
/depcomp
/install-sh
/missing
/stamp-h1
*.sublime-workspace
libtool
Makefile
*.sublime-workspace
m4/libtool.m4
m4/ltoptions.m4
m4/ltsugar.m4
m4/ltversion.m4
m4/lt~obsolete.m4
/config
# Python folders
python/build/
/python/test/.idea
/.deps/*
# Python files
*.pyc
python/pybertini_*.log
*.dirstamp
*.deps
*~
.DS_Store
# Compiled Object files
*.slo
*.lo
*.o
*.o-*
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
python/autom4te.cache
*.bak
python/temp.py
core/serialization_basic
core/test/classes/serialization_basic
python/conftest.cpp
*.tar.gz
python/src/UNKNOWN.egg-info/dependency_links.txt
python/src/UNKNOWN.egg-info/PKG-INFO
python/src/UNKNOWN.egg-info/SOURCES.txt
python/src/UNKNOWN.egg-info/top_level.txt
*/build/

0
.gitmodules vendored Normal file
View File

7
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
// The following hides files created by and for the Sublime IDE
"files.exclude": {
"*.b2.sublime-project": true,
"**/*.sublime-project": true
}
}

66
README.md Normal file
View File

@@ -0,0 +1,66 @@
### Important note on cloning
The recommended method for getting the code for Bertini 2 is to clone from command line using git:
`git clone https://github.com/bertiniteam/b2 --recursive`
This ensures that any other repo's we depend on get cloned into their correct locations.
(As of 2023, we removed the dependency that required this, but it's still good practice.)
---
# Quick links
- [Wiki](https://github.com/bertiniteam/b2/wiki)
- [Overview](#Overview)
- [Current capabilites](#Current-capabilites)
- [Building and installing](#Building-and-installing)
- [Other information](#Other-information)
Thanks for checking out Bertini 2!
---
# Overview
The solution of arbitrary polynomial systems is an area of active research, and has many applications in math, science and engineering. This program, Bertini 2, builds on the success of the first Bertini program, and seeks to eventually replace it entirely, as a powerful numerical engine.
The theoretical basis for the solution of polynomials with Bertini is a theorem which gives a statement on the number of solutions such a system may have, together with the numerical computational tool of "homotopy continuation", the act of "continuing" from one system into another through a "homotopy", as depicted in the below diagram.
<img src="https://raw.githubusercontent.com/bertiniteam/b2/develop/doc_resources/images/homotopycontinuation_generic.png" alt="homotopy continuation"
title="homotopy continuation" width="400"/>
---
# Current capabilites
Bertini2 currently has implemented the foundations of Numerical Algebraic Geometry. Development is ongoing, but here's what we have so far:
- C++ and Python bindings for access into any functionality.
- Construction of polynomial and non-polynomial multivariate systems.
- Evaluation of systems and Jacobians in double and arbitrary multiple precision.
- Construction of the Total Degree start system.
- Construction of homotopies (they're just systems with path variables defined).
- Tracking of a start point x_0, corresponding to a particular time $t_0 \in \mathbb{C}^n$ in a homotopy $H$, from $t_0$ to $t_1$.
- Running of the Power Series and Cauchy endgames.
Development is ongoing, and we want your help!
---
# Building and Installing
Please see [the Wiki compiling section](https://github.com/bertiniteam/b2/wiki/Compilation-Guide) for instructions on compiling Bertini2's core library, and companion Python bindings, PyBertini.
---
# Other information
The offical project repository is hosted on GitHub at [github.com/bertiniteam/b2](https://github.com/bertiniteam/b2).
Please note that this is a long-term project, and is under active development. If you want to help, please see [the wiki](https://github.com/bertiniteam/b2/wiki) for contact information. We have opportinuties for all skill levels and interests.
# License
Bertini 2 is Free and Open Source Software. Source is available under GPL Version 3, with additional terms as permitted under Section 7.

52
b2.sublime-project Normal file
View File

@@ -0,0 +1,52 @@
{
"folders":
[
{
"path": ".",
"file_exclude_patterns": ["serialization_test*",
"Makefile",
"Makefile.in",
"*.la",
"libtool",
"stamp-h1",
".dirstamp",
"*.lo",
"*~",
"aclocal.m4",
"ltoptions.m4",
"ltsugar.m4",
"ltversion.m4",
"lt~obsolete.m4",
"libtool.m4",
"b2_class_test",
"b2_classic_compatibility_test",
"b2_timing_test",
"tracking_basics_test",
"settings_test",
"nag_algorithms_test",
"endgames_test",
"pool_test",
"generating_test",
"config.status",
"configure",
"*.trs",
"ltmain.sh"],
"folder_exclude_patterns": [
"__pycache__",
"pybertini.egg-info",
"_static",
"_templates",
".deps",
".libs",
"*.dtps",
"autom4te.cache",
"generated_documentation",
".pytest_cache"]
}
],
}

21
core/.gitattributes vendored Normal file
View File

@@ -0,0 +1,21 @@
# this file derived from https://help.github.com/articles/dealing-with-line-endings/
# Set the default behavior, in case people don't have core.autocrlf set.
* text eol=lf
# Explicitly declare text files you want to always be normalized and converted
# to native line endings on checkout.
*.cpp text eol=lf
*.hpp text eol=lf
# Declare files that will always have CRLF line endings on checkout.
*.am text eol=lf
*.ac text eol=lf
*/*.am text eol=lf
*/*.ac text eol=lf
*/*/*.am text eol=lf
*/*/*.ac text eol=lf
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

111
core/.gitignore vendored Normal file
View File

@@ -0,0 +1,111 @@
# http://www.gnu.org/software/automake
Makefile.in
# http://www.gnu.org/software/autoconf
autom4te.cache
aclocal.m4
compile
configure
depcomp
install-sh
missing
stamp-h1
ltmain.sh
config.h
#config.h.in
config.status
libtool
Makefile
/bertini2
b2_timing_test
b2_class_test
test_tree_interactive
settings_test
tracking_basics_test
b2_classic_compatibility_test
endgames_test
pool_test
nag_algorithms_test
generating_test
nag_datatypes_test
blackbox_test
cachegrind.out.*
callgrind.out.*
m4/libtool.m4
m4/ltoptions.m4
m4/ltsugar.m4
m4/ltversion.m4
m4/lt~obsolete.m4
ltmain.sh
serialization_test*
*.log
.libs/*
*.trs
/config
.DS_Store
*.dirstamp
*.deps
*.dtps
# these are data files from iprofiler, from osx
*~
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
*.rej
# trace objects from xcrun / instruments
*.trace
# Maple files
test/tracking_basics/*.bak
# temporary files
*.tmp
.devcontainer
*.check_cache
*.yaml

55
core/ADDITIONAL_GPL_TERMS Normal file
View File

@@ -0,0 +1,55 @@
Bertini(TM) version 2
Authors: D.J. Bates, D.A. Brake, J.D. Hauenstein, A.J. Sommese, C.W. Wampler
http://bertini.nd.edu
Copyright(C) 2016
*NOTICE*
This program is free software in that it is free to download (as source code or as a binary) and free to use on the computer(s) to which it was downloaded. You may redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation (<http://www.gnu.org/licenses/>) with the additional terms and conditions listed below which are permitted under this license.
The following software modules shipped with Bertini have their own copyright: the
GNU Multiple Precision Library (GMP) and the GNU MPFR Library (MPFR). This license covers those parts of Bertini's source code written by the Authors and Developers, excluding these particular modules. Copyrights and licenses for these modules have been included in the directory LICENSES.
ADDITIONAL TERMS AND CONDITIONS
7. Additional Terms.
All specified reasonable legal notices or author attributions in the program and source code must be preserved.
Misrepresenting the origin of the source code in this program or modified versions is prohibited. Any modified versions of the source code in this program must be marked in a reasonable way as to demonstrate that it is different from the original version. This includes providing a detailed list of the modifications.
The Authors limit the use of the name Bertini(TM) to the original version and, without written consent of all living Authors or their successors, prohibit the use of this name for any other program. Moreover, without written consent of all living Authors or their successors, the Authors decline to grant rights under trademark law for the use of the name Bertini(TM).
All programs dependent on this software must indemnify the Authors of this program against any contractual assumptions of liability to the recipient.
END OF TERMS AND CONDITIONS
In addition to the stated license, we ask that any publications which made use of any version of Bertini, directly or indirectly via a covered work, include an appropriate citation to Bertini, as described on the website http://bertini.nd.edu/policy.html, or any future Bertini page created by the Authors and/or Development Team.
Acknowledgements
================
Current members of Bertini2 Development Team:
-- Dan Bates, Colorado State University
-- Silviana Amethyst, University of Wisconsin Eau Claire
-- Jeb Collins, University of Mary Washington
-- Jonathan Hauenstein, University of Notre Dame
-- Tim Hodges, Colorado State University
-- Alan Liddell, Jr., University of Notre Dame
-- Francesco Pancaldi, University of Notre Dame
-- Hythem Sidkey, University of Notre Dame
-- Andrew Sommese, University of Notre Dame
-- Charles Wampler, General Motors Research and Development
The Authors and Development Team would like to express our gratitude for the financial support of the National Science Foundation.
Any opinions, findings, and conclusions or recommendations expressed in this material are those of the Authors and do not necessarily reflect those of the National Science Foundation.
Revision History:
updated 20170825 for affiliations and names

18
core/AUTHORS Normal file
View File

@@ -0,0 +1,18 @@
Acknowledgements
================
Current members of Bertini2 Development Team:
-- Dan Bates, Colorado State University
-- Silviana Amethyst, University of Wisconsin Eau Claire
-- Jeb Collins, University of Mary Washington
-- Jonathan Hauenstein, University of Notre Dame
-- Tim Hodges, Colorado State University
-- Alan Liddell, Jr., University of Notre Dame
-- Francesco Pancaldi, University of Notre Dame
-- Andrew Sommese, University of Notre Dame
-- Charles Wampler, General Motors Research and Development
The Authors and Development Team would like to express our gratitude for the financial support of the National Science Foundation.
Any opinions, findings, and conclusions or recommendations expressed in this material are those of the Authors and do not necessarily reflect those of the National Science Foundation.

663
core/CMakeLists.txt Normal file
View File

@@ -0,0 +1,663 @@
cmake_minimum_required(VERSION 3.22)
project(bertini2)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# In order to find conda, run 'conda activate' and then use 'cmake .. -DCMAKE_PREFIX_PATH=$CONDA_PREFIX' when cmaking
# All source files to be compiled
# We can either explicitly list all files or use glob, we chose to explicitly list files and not to glob
#file(GLOB SOURCES src/*.cpp)
include_directories(include)
include_directories("${CMAKE_CURRENT_SOURCE_DIR}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -fPIC")
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include_directories("${CMAKE_CURRENT_BINARY_DIR}/include")
find_package(GMP REQUIRED)
find_package(MPFR REQUIRED)
find_package(MPC REQUIRED)
include_directories(${GMP_INCLUDES})
include_directories(${MPC_INCLUDES})
find_package(Boost 1.82 REQUIRED
COMPONENTS
serialization
unit_test_framework
filesystem
system
chrono
regex
timer
log
thread
log_setup
)
find_package(Eigen3 3.3 REQUIRED NO_MODULE)
# This was from a makemodule.am, take the lists and define them in seperate blocks with the variables they already have, then add the variable name to library_headrs
set(endgames_headers
include/bertini2/endgames/amp_endgame.hpp
include/bertini2/endgames/base_endgame.hpp
include/bertini2/endgames/cauchy.hpp
include/bertini2/endgames/config.hpp
include/bertini2/endgames/events.hpp
include/bertini2/endgames/fixed_prec_endgame.hpp
include/bertini2/endgames/interpolation.hpp
include/bertini2/endgames/observers.hpp
include/bertini2/endgames/powerseries.hpp
include/bertini2/endgames/prec_base.hpp
)
set (basics_rootinclude_headers
include/bertini2/have_bertini.hpp
include/bertini2/mpfr_extensions.hpp
include/bertini2/mpfr_complex.hpp
include/bertini2/forbid_mixed_arithmetic.hpp
include/bertini2/double_extensions.hpp
include/bertini2/random.hpp
include/bertini2/num_traits.hpp
include/bertini2/classic.hpp
include/bertini2/eigen_extensions.hpp
include/bertini2/eigen_serialization_addon.hpp
include/bertini2/logging.hpp
include/bertini2/endgames.hpp
include/bertini2/bertini.hpp
include/bertini2/version.hpp
)
set (common_headers
include/bertini2/common/config.hpp
include/bertini2/common/stream_enum.hpp
)
set(detail_headers
include/bertini2/detail/configured.hpp
include/bertini2/detail/events.hpp
include/bertini2/detail/visitable.hpp
include/bertini2/detail/visitor.hpp
include/bertini2/detail/observer.hpp
include/bertini2/detail/observable.hpp
include/bertini2/detail/is_template_parameter.hpp
include/bertini2/detail/enable_permuted_arguments.hpp
include/bertini2/detail/typelist.hpp
)
set(function_tree_headers
include/bertini2/function_tree.hpp
include/bertini2/function_tree/node.hpp
include/bertini2/function_tree/forward_declares.hpp
include/bertini2/function_tree/simplify.hpp
include/bertini2/function_tree/operators/operator.hpp
include/bertini2/function_tree/symbols/symbol.hpp
include/bertini2/function_tree/symbols/variable.hpp
include/bertini2/function_tree/symbols/differential.hpp
include/bertini2/function_tree/symbols/special_number.hpp
include/bertini2/function_tree/symbols/number.hpp
include/bertini2/function_tree/symbols/linear_product.hpp
include/bertini2/function_tree/roots/function.hpp
include/bertini2/function_tree/roots/jacobian.hpp
include/bertini2/function_tree/operators/arithmetic.hpp
include/bertini2/function_tree/operators/trig.hpp
)
set(function_tree_headers_rootinclude_HEADERS
include/bertini2/function_tree.hpp
)
set(settings_headers
include/bertini2/settings/configIni_parse.hpp
)
set(functiontreeinclude_HEADERS
include/bertini2/function_tree/node.hpp
include/bertini2/function_tree/factory.hpp
include/bertini2/function_tree/forward_declares.hpp
include/bertini2/function_tree/simplify.hpp
)
set(functiontree_operators_HEADERS
include/bertini2/function_tree/operators/operator.hpp
include/bertini2/function_tree/operators/arithmetic.hpp
include/bertini2/function_tree/operators/trig.hpp
)
set(functiontree_symbols_HEADERS
include/bertini2/function_tree/symbols/symbol.hpp
include/bertini2/function_tree/symbols/variable.hpp
include/bertini2/function_tree/symbols/differential.hpp
include/bertini2/function_tree/symbols/special_number.hpp
include/bertini2/function_tree/symbols/number.hpp
include/bertini2/function_tree/symbols/linear_product.hpp
)
set(functiontree_roots_HEADERS
include/bertini2/function_tree/roots/function.hpp
include/bertini2/function_tree/roots/jacobian.hpp
)
set(io_headers
include/bertini2/io/file_utilities.hpp
include/bertini2/io/generators.hpp
include/bertini2/io/parsing.hpp
include/bertini2/io/splash.hpp
)
set (io_parsing_headers
include/bertini2/io/parsing/classic_utilities.hpp
include/bertini2/io/parsing/function_parsers.hpp
include/bertini2/io/parsing/function_rules.hpp
include/bertini2/io/parsing/number_parsers.hpp
include/bertini2/io/parsing/number_rules.hpp
include/bertini2/io/parsing/qi_files.hpp
include/bertini2/io/parsing/settings_parsers.hpp
include/bertini2/io/parsing/settings_rules.hpp
include/bertini2/io/parsing/system_parsers.hpp
include/bertini2/io/parsing/system_rules.hpp
)
set (io_parsing_settings_headers
include/bertini2/io/parsing/settings_parsers/algorithm.hpp
include/bertini2/io/parsing/settings_parsers/base.hpp
include/bertini2/io/parsing/settings_parsers/endgames.hpp
include/bertini2/io/parsing/settings_parsers/tracking.hpp
)
set(nag_algorithms_headers
include/bertini2/nag_algorithms/midpath_check.hpp
include/bertini2/nag_algorithms/numerical_irreducible_decomposition.hpp
include/bertini2/nag_algorithms/output.hpp
include/bertini2/nag_algorithms/sharpen.hpp
include/bertini2/nag_algorithms/trace.hpp
include/bertini2/nag_algorithms/zero_dim_solve.hpp
)
set(nag_algorithms_common_headers
include/bertini2/nag_algorithms/common/algorithm_base.hpp
include/bertini2/nag_algorithms/common/config.hpp
include/bertini2/nag_algorithms/common/policies.hpp
)
set(nag_datatypes_headers
include/bertini2/nag_datatypes/numerical_irreducible_decomposition.hpp
include/bertini2/nag_datatypes/witness_set.hpp
)
set(nag_datatypes_common_headers
include/bertini2/nag_datatypes/common/policies.hpp
)
set(parallel_headers
include/bertini2/parallel/initialize_finalize.hpp
)
set(parallel_rootinclude_HEADERS
include/bertini2/parallel.hpp
)
set(pool_headers
include/bertini2/pool/pool.hpp
include/bertini2/pool/system.hpp
)
set(system_headers
include/bertini2/system/patch.hpp
include/bertini2/system/precon.hpp
include/bertini2/system/slice.hpp
include/bertini2/system/start_base.hpp
include/bertini2/system/start_systems.hpp
include/bertini2/system/straight_line_program.hpp
include/bertini2/system/system.hpp
)
set(system_start_headers
include/bertini2/system/start/total_degree.hpp
include/bertini2/system/start/mhom.hpp
include/bertini2/system/start/user.hpp
include/bertini2/system/start/utility.hpp
)
set(system_rootinclude_HEADERS
include/bertini2/system.hpp
)
set(trackers_HEADERS
include/bertini2/trackers/adaptive_precision_utilities.hpp
include/bertini2/trackers/amp_criteria.hpp
include/bertini2/trackers/amp_tracker.hpp
include/bertini2/trackers/base_predictor.hpp
include/bertini2/trackers/base_tracker.hpp
include/bertini2/trackers/config.hpp
include/bertini2/trackers/events.hpp
include/bertini2/trackers/explicit_predictors.hpp
include/bertini2/trackers/fixed_precision_tracker.hpp
include/bertini2/trackers/fixed_precision_utilities.hpp
include/bertini2/trackers/newton_correct.hpp
include/bertini2/trackers/newton_corrector.hpp
include/bertini2/trackers/observers.hpp
include/bertini2/trackers/ode_predictors.hpp
include/bertini2/trackers/predict.hpp
include/bertini2/trackers/step.hpp
include/bertini2/trackers/tracker.hpp
)
set(tracking_rootinclude_HEADERS
include/bertini2/tracking.hpp
)
set(BERTINI2_LIBRARY_HEADERS
${endgames_headers}
${basics_headers}
${common_headers}
${details_headers}
${function_tree_headers}
${io_headers}
${io_parsing_headers}
${io_parsing_settings_headers}
${nag_algorithms_headers}
${nag_algorithms_common_headers}
${nag_datatypes_headers}
${nag_datatypes_common_headers}
${parallel_headers}
${parallel_rootinclude_HEADERS}
${pool_headers}
${system_headers}
${system_start_headers}
${system_rootinclude_HEADERS}
${systeminclude_HEADERS}
${startinclude_HEADERS}
${trackers_HEADERS}
${tracking_header_files}
${tracking_rootinclude_HEADERS}
${trackersinclude_HEADERS}
)
set(basics_sources
src/basics/random.cpp
src/basics/have_bertini.cpp
)
set(function_tree_sources
src/function_tree/node.cpp
src/function_tree/simplify.cpp
src/function_tree/operators/arithmetic.cpp
src/function_tree/operators/trig.cpp
src/function_tree/linear_product.cpp
src/function_tree/operators/operator.cpp
src/function_tree/symbols/special_number.cpp
src/function_tree/symbols/differential.cpp
src/function_tree/symbols/symbol.cpp
src/function_tree/symbols/variable.cpp
src/function_tree/symbols/number.cpp
src/function_tree/roots/jacobian.cpp
src/function_tree/roots/function.cpp
)
set(parallel_sources
src/parallel/parallel.cpp
src/parallel/initialize_finalize.cpp
)
set(system_source_files
src/system/precon.cpp
src/system/slice.cpp
src/system/start_base.cpp
src/system/system.cpp
src/system/straight_line_program.cpp
src/system/start/total_degree.cpp
src/system/start/mhom.cpp
src/system/start/user.cpp
)
set(tracking_source_files
src/tracking/explicit_predictors.cpp
)
set(BERTINI2_LIBRARY_SOURCES
${basics_sources}
${libbertini2_la_SOURCES}
${function_tree_sources}
${parallel_sources}
${system_source_files}
${tracking_source_files}
)
set(BERTINI2_EXE_SOURCES
src/blackbox/bertini.cpp
src/blackbox/main_mode_switch.cpp
src/blackbox/argc_argv.cpp
)
set(BERTINI2_EXE_HEADERS
include/bertini2/blackbox/main_mode_switch.hpp
include/bertini2/blackbox/argc_argv.hpp
include/bertini2/blackbox/config.hpp
include/bertini2/blackbox/algorithm_builder.hpp
include/bertini2/blackbox/global_configs.hpp
include/bertini2/blackbox/switches_zerodim.hpp
include/bertini2/blackbox/user_homotopy.hpp
)
add_executable(bertini2_exe ${BERTINI2_EXE_SOURCES} ${BERTINI2_EXE_HEADERS})
set_property(TARGET bertini2_exe PROPERTY OUTPUT_NAME bertini2)
# All library files
add_library(bertini2
${BERTINI2_LIBRARY_SOURCES}
${BERTINI2_LIBRARY_HEADERS}
)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DBOOST_PHOENIX_STL_TUPLE_H_")
target_link_libraries(bertini2 ${GMP_LIBRARIES})
target_link_libraries(bertini2 ${MPFR_LIBRARIES})
target_link_libraries(bertini2 ${MPC_LIBRARIES})
target_link_libraries(bertini2 Eigen3::Eigen)
target_link_libraries(bertini2 ${Boost_LIBRARIES})
target_link_libraries(bertini2_exe ${Boost_LIBRARIES} bertini2)
target_compile_options(bertini2 PRIVATE -Wall -Wextra)
install(
TARGETS bertini2
ARCHIVE DESTINATION "lib"
LIBRARY DESTINATION "lib"
COMPONENT library
)
install(
FILES ${BERTINI2_EXE_HEADERS}
DESTINATION "include/bertini2/blackbox"
)
install(
FILES ${function_tree_headers_rootinclude_HEADERS} ${parallel_rootinclude_HEADERS} ${system_rootinclude_HEADERS} ${tracking_rootinclude_HEADERS} ${parallel_rootinclude_HEADERS} ${system_rootinclude_HEADERS} ${tracking_rootinclude_HEADERS}
DESTINATION "include/bertini2"
)
install(
FILES ${endgames_headers}
DESTINATION "include/bertini2/endgames"
)
install(
FILES ${trackers_headers}
DESTINATION "include/bertini2/trackers"
)
install(
FILES ${basics_rootinclude_headers}
DESTINATION "include/bertini2"
)
install(
FILES ${common_headers}
DESTINATION "include/bertini2/common"
)
install(
FILES ${detail_headers}
DESTINATION "include/bertini2/detail"
)
install(
FILES ${function_tree_headers}
DESTINATION "include/bertini2/function_tree"
)
install(
FILES ${function_tree_headers_rootinclude_HEADERS}#
DESTINATION "include/bertini2"
)
install(
FILES ${functiontree_operators_HEADERS}
DESTINATION "include/bertini2/function_tree/operators"
)
install(
FILES ${functiontree_symbols_HEADERS}
DESTINATION "include/bertini2/function_tree/symbols"
)
install(
FILES ${functiontree_roots_HEADERS}
DESTINATION "include/bertini2/function_tree/roots/"
)
install(
FILES ${io_headers}
DESTINATION "include/bertini2/io"
)
install(
FILES ${io_parsing_headers}
DESTINATION "include/bertini2/io/parsing"
)
install(
FILES ${io_parsing_settings_headers}
DESTINATION "include/bertini2/io/parsing/settings_parsers"
)
install(
FILES ${nag_algorithms_headers}
DESTINATION "include/bertini2/nag_algorithms"
)
install(
FILES ${nag_algorithms_common_headers}
DESTINATION "include/bertini2/nag_algorithms/common"
)
install(
FILES ${nag_datatypes_headers}
DESTINATION "include/bertini2/nag_datatypes"
)
install(
FILES ${nag_datatypes_common_headers}
DESTINATION "include/bertini2/nag_datatypes/common"
)
install(
FILES ${parallel_headers}
DESTINATION "include/bertini2/parallel"
)
install(
FILES ${parallel_rootinclude_HEADERS}
DESTINATION "include/bertini2"
)
install(
FILES ${pool_headers}
DESTINATION "include/bertini2/pool"
)
install(
FILES ${system_headers}
DESTINATION "include/bertini2/system"
)
install(
FILES ${system_start_headers}
DESTINATION "include/bertini2/system/start"
)
install(
FILES ${system_rootinclude_HEADERS}
DESTINATION "include/bertini2"
)
install(
FILES ${tracking_rootinclude_HEADERS}
DESTINATION "include/bertini2"
)
install(
FILES ${trackers_HEADERS}
DESTINATION "include/bertini2/trackers"
)
install(
FILES ${settings_headers}
DESTINATION "include/bertini2/settings"
)
install(
FILES ${tracking_header_files}
DESTINATION "include/bertini2/tracking"
)
set(B2_CLASS_TEST_SOURCES
test/classes/boost_multiprecision_test.cpp
test/classes/fundamentals_test.cpp
test/classes/eigen_test.cpp
test/classes/complex_test.cpp
test/classes/function_tree_test.cpp
test/classes/function_tree_transform.cpp
test/classes/system_test.cpp
test/classes/slp_test.cpp
test/classes/differentiate_test.cpp
test/classes/differentiate_wrt_var.cpp
test/classes/homogenization_test.cpp
test/classes/start_system_test.cpp
test/classes/node_serialization_test.cpp
test/classes/patch_test.cpp
test/classes/slice_test.cpp
test/classes/m_hom_start_system.cpp
test/classes/class_test.cpp
)
add_executable(test_classes ${B2_CLASS_TEST_SOURCES})
target_include_directories(test_classes PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/test/classes)
target_link_libraries(test_classes ${Boost_LIBRARIES} bertini2)
add_test(NAME test_classes COMMAND ${CMAKE_BINARY_DIR}/test_classes)
set(B2_BLACKBOX_TEST
test/blackbox/blackbox.cpp
test/blackbox/zerodim.cpp
test/blackbox/parsing.cpp
test/blackbox/user_homotopy.cpp
)
add_executable(test_blackbox ${B2_BLACKBOX_TEST})
target_link_libraries(test_blackbox ${Boost_LIBRARIES} bertini2)
add_test(NAME test_blackbox COMMAND ${CMAKE_BINARY_DIR}/test_blackbox)
set(B2_CLASSIC_TEST
test/classic/classic_parsing_test.cpp
test/classic/classic_test.cpp
)
add_executable(test_classic ${B2_CLASSIC_TEST})
target_link_libraries(test_classic ${Boost_LIBRARIES} bertini2)
add_test(NAME test_classic COMMAND ${CMAKE_BINARY_DIR}/test_classic)
set(B2_ENDGAMES_TEST
test/endgames/endgames_test.cpp
test/endgames/generic_interpolation.hpp
test/endgames/interpolation.cpp
test/endgames/generic_pseg_test.hpp
test/endgames/amp_powerseries_test.cpp
test/endgames/fixed_double_powerseries_test.cpp
test/endgames/fixed_multiple_powerseries_test.cpp
test/endgames/generic_cauchy_test.hpp
test/endgames/amp_cauchy_test.cpp
test/endgames/fixed_double_cauchy_test.cpp
test/endgames/fixed_multiple_cauchy_test.cpp
)
add_executable(test_endgames ${B2_ENDGAMES_TEST})
target_link_libraries(test_endgames ${Boost_LIBRARIES} bertini2)
add_test(NAME test_endgames COMMAND ${CMAKE_BINARY_DIR}/test_endgames)
set(B2_GENERATING_TEST
test/generating/mpfr_float.cpp
test/generating/mpfr_complex.cpp
test/generating/double.cpp
test/generating/std_complex.cpp
test/generating/generating_test.cpp
)
add_executable(test_generating ${B2_GENERATING_TEST})
target_link_libraries(test_generating ${Boost_LIBRARIES} bertini2)
add_test(NAME test_generating COMMAND ${CMAKE_BINARY_DIR}/test_generating)
set(B2_NAG_ALGORITHMS_TEST
test/nag_algorithms/nag_algorithms_test.cpp
test/nag_algorithms/zero_dim.cpp
test/nag_algorithms/numerical_irreducible_decomposition.cpp
test/nag_algorithms/trace.cpp
)
add_executable(test_nag_algorithms ${B2_NAG_ALGORITHMS_TEST})
target_link_libraries(test_nag_algorithms ${Boost_LIBRARIES} bertini2)
add_test(NAME test_nag_algorithms COMMAND ${CMAKE_BINARY_DIR}/test_nag_algorithms)
set(B2_NAG_DATATYPES_TEST
test/nag_datatypes/witness_set.cpp
test/nag_datatypes/nag_datatypes_test.cpp
test/nag_datatypes/numerical_irreducible_decomposition.cpp
)
add_executable(test_nag_datatypes ${B2_NAG_DATATYPES_TEST})
target_link_libraries(test_nag_datatypes ${Boost_LIBRARIES} bertini2)
add_test(NAME test_nag_datatypes COMMAND ${CMAKE_BINARY_DIR}/test_nag_datatypes)
set(B2_POOLS_TEST
test/pools/pool_test.cpp
)
add_executable(test_pool ${B2_NAG_DATATYPES_TEST})
target_link_libraries(test_pool ${Boost_LIBRARIES} bertini2)
add_test(NAME test_pool COMMAND ${CMAKE_BINARY_DIR}/test_pool)
set(B2_SETTINGS_TEST
test/settings/settings_test.cpp
)
add_executable(test_settings ${B2_SETTINGS_TEST})
target_link_libraries(test_settings ${Boost_LIBRARIES} bertini2)
add_test(NAME test_settings COMMAND ${CMAKE_BINARY_DIR}/test_settings)
set(B2_TRACKING_BASICS_TEST
test/tracking_basics/newton_correct_test.cpp
test/tracking_basics/euler_test.cpp
test/tracking_basics/heun_test.cpp
test/tracking_basics/higher_predictor_test.cpp
test/tracking_basics/tracking_basics_test.cpp
test/tracking_basics/fixed_precision_tracker_test.cpp
test/tracking_basics/amp_criteria_test.cpp
test/tracking_basics/amp_tracker_test.cpp
test/tracking_basics/path_observers.cpp
)
add_executable(test_tracking_basics ${B2_TRACKING_BASICS_TEST})
target_link_libraries(test_tracking_basics ${Boost_LIBRARIES} bertini2)
add_test(NAME test_tracking_basics COMMAND ${CMAKE_BINARY_DIR}/test_tracking_basics)
enable_testing()

674
core/COPYING Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

0
core/ChangeLog Normal file
View File

368
core/INSTALL Normal file
View File

@@ -0,0 +1,368 @@
Installation Instructions
*************************
Copyright (C) 1994-1996, 1999-2002, 2004-2017, 2020-2021 Free
Software Foundation, Inc.
Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved. This file is offered as-is,
without warranty of any kind.
Basic Installation
==================
Briefly, the shell command './configure && make && make install'
should configure, build, and install this package. The following
more-detailed instructions are generic; see the 'README' file for
instructions specific to this package. Some packages provide this
'INSTALL' file but do not implement all of the features documented
below. The lack of an optional feature in a given package is not
necessarily a bug. More recommendations for GNU packages can be found
in *note Makefile Conventions: (standards)Makefile Conventions.
The 'configure' shell script attempts to guess correct values for
various system-dependent variables used during compilation. It uses
those values to create a 'Makefile' in each directory of the package.
It may also create one or more '.h' files containing system-dependent
definitions. Finally, it creates a shell script 'config.status' that
you can run in the future to recreate the current configuration, and a
file 'config.log' containing compiler output (useful mainly for
debugging 'configure').
It can also use an optional file (typically called 'config.cache' and
enabled with '--cache-file=config.cache' or simply '-C') that saves the
results of its tests to speed up reconfiguring. Caching is disabled by
default to prevent problems with accidental use of stale cache files.
If you need to do unusual things to compile the package, please try
to figure out how 'configure' could check whether to do them, and mail
diffs or instructions to the address given in the 'README' so they can
be considered for the next release. If you are using the cache, and at
some point 'config.cache' contains results you don't want to keep, you
may remove or edit it.
The file 'configure.ac' (or 'configure.in') is used to create
'configure' by a program called 'autoconf'. You need 'configure.ac' if
you want to change it or regenerate 'configure' using a newer version of
'autoconf'.
The simplest way to compile this package is:
1. 'cd' to the directory containing the package's source code and type
'./configure' to configure the package for your system.
Running 'configure' might take a while. While running, it prints
some messages telling which features it is checking for.
2. Type 'make' to compile the package.
3. Optionally, type 'make check' to run any self-tests that come with
the package, generally using the just-built uninstalled binaries.
4. Type 'make install' to install the programs and any data files and
documentation. When installing into a prefix owned by root, it is
recommended that the package be configured and built as a regular
user, and only the 'make install' phase executed with root
privileges.
5. Optionally, type 'make installcheck' to repeat any self-tests, but
this time using the binaries in their final installed location.
This target does not install anything. Running this target as a
regular user, particularly if the prior 'make install' required
root privileges, verifies that the installation completed
correctly.
6. You can remove the program binaries and object files from the
source code directory by typing 'make clean'. To also remove the
files that 'configure' created (so you can compile the package for
a different kind of computer), type 'make distclean'. There is
also a 'make maintainer-clean' target, but that is intended mainly
for the package's developers. If you use it, you may have to get
all sorts of other programs in order to regenerate files that came
with the distribution.
7. Often, you can also type 'make uninstall' to remove the installed
files again. In practice, not all packages have tested that
uninstallation works correctly, even though it is required by the
GNU Coding Standards.
8. Some packages, particularly those that use Automake, provide 'make
distcheck', which can by used by developers to test that all other
targets like 'make install' and 'make uninstall' work correctly.
This target is generally not run by end users.
Compilers and Options
=====================
Some systems require unusual options for compilation or linking that
the 'configure' script does not know about. Run './configure --help'
for details on some of the pertinent environment variables.
You can give 'configure' initial values for configuration parameters
by setting variables in the command line or in the environment. Here is
an example:
./configure CC=c99 CFLAGS=-g LIBS=-lposix
*Note Defining Variables::, for more details.
Compiling For Multiple Architectures
====================================
You can compile the package for more than one kind of computer at the
same time, by placing the object files for each architecture in their
own directory. To do this, you can use GNU 'make'. 'cd' to the
directory where you want the object files and executables to go and run
the 'configure' script. 'configure' automatically checks for the source
code in the directory that 'configure' is in and in '..'. This is known
as a "VPATH" build.
With a non-GNU 'make', it is safer to compile the package for one
architecture at a time in the source code directory. After you have
installed the package for one architecture, use 'make distclean' before
reconfiguring for another architecture.
On MacOS X 10.5 and later systems, you can create libraries and
executables that work on multiple system types--known as "fat" or
"universal" binaries--by specifying multiple '-arch' options to the
compiler but only a single '-arch' option to the preprocessor. Like
this:
./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \
CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \
CPP="gcc -E" CXXCPP="g++ -E"
This is not guaranteed to produce working output in all cases, you
may have to build one architecture at a time and combine the results
using the 'lipo' tool if you have problems.
Installation Names
==================
By default, 'make install' installs the package's commands under
'/usr/local/bin', include files under '/usr/local/include', etc. You
can specify an installation prefix other than '/usr/local' by giving
'configure' the option '--prefix=PREFIX', where PREFIX must be an
absolute file name.
You can specify separate installation prefixes for
architecture-specific files and architecture-independent files. If you
pass the option '--exec-prefix=PREFIX' to 'configure', the package uses
PREFIX as the prefix for installing programs and libraries.
Documentation and other data files still use the regular prefix.
In addition, if you use an unusual directory layout you can give
options like '--bindir=DIR' to specify different values for particular
kinds of files. Run 'configure --help' for a list of the directories
you can set and what kinds of files go in them. In general, the default
for these options is expressed in terms of '${prefix}', so that
specifying just '--prefix' will affect all of the other directory
specifications that were not explicitly provided.
The most portable way to affect installation locations is to pass the
correct locations to 'configure'; however, many packages provide one or
both of the following shortcuts of passing variable assignments to the
'make install' command line to change installation locations without
having to reconfigure or recompile.
The first method involves providing an override variable for each
affected directory. For example, 'make install
prefix=/alternate/directory' will choose an alternate location for all
directory configuration variables that were expressed in terms of
'${prefix}'. Any directories that were specified during 'configure',
but not in terms of '${prefix}', must each be overridden at install time
for the entire installation to be relocated. The approach of makefile
variable overrides for each directory variable is required by the GNU
Coding Standards, and ideally causes no recompilation. However, some
platforms have known limitations with the semantics of shared libraries
that end up requiring recompilation when using this method, particularly
noticeable in packages that use GNU Libtool.
The second method involves providing the 'DESTDIR' variable. For
example, 'make install DESTDIR=/alternate/directory' will prepend
'/alternate/directory' before all installation names. The approach of
'DESTDIR' overrides is not required by the GNU Coding Standards, and
does not work on platforms that have drive letters. On the other hand,
it does better at avoiding recompilation issues, and works well even
when some directory options were not specified in terms of '${prefix}'
at 'configure' time.
Optional Features
=================
If the package supports it, you can cause programs to be installed
with an extra prefix or suffix on their names by giving 'configure' the
option '--program-prefix=PREFIX' or '--program-suffix=SUFFIX'.
Some packages pay attention to '--enable-FEATURE' options to
'configure', where FEATURE indicates an optional part of the package.
They may also pay attention to '--with-PACKAGE' options, where PACKAGE
is something like 'gnu-as' or 'x' (for the X Window System). The
'README' should mention any '--enable-' and '--with-' options that the
package recognizes.
For packages that use the X Window System, 'configure' can usually
find the X include and library files automatically, but if it doesn't,
you can use the 'configure' options '--x-includes=DIR' and
'--x-libraries=DIR' to specify their locations.
Some packages offer the ability to configure how verbose the
execution of 'make' will be. For these packages, running './configure
--enable-silent-rules' sets the default to minimal output, which can be
overridden with 'make V=1'; while running './configure
--disable-silent-rules' sets the default to verbose, which can be
overridden with 'make V=0'.
Particular systems
==================
On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC
is not installed, it is recommended to use the following options in
order to use an ANSI C compiler:
./configure CC="cc -Ae -D_XOPEN_SOURCE=500"
and if that doesn't work, install pre-built binaries of GCC for HP-UX.
HP-UX 'make' updates targets which have the same timestamps as their
prerequisites, which makes it generally unusable when shipped generated
files such as 'configure' are involved. Use GNU 'make' instead.
On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot
parse its '<wchar.h>' header file. The option '-nodtk' can be used as a
workaround. If GNU CC is not installed, it is therefore recommended to
try
./configure CC="cc"
and if that doesn't work, try
./configure CC="cc -nodtk"
On Solaris, don't put '/usr/ucb' early in your 'PATH'. This
directory contains several dysfunctional programs; working variants of
these programs are available in '/usr/bin'. So, if you need '/usr/ucb'
in your 'PATH', put it _after_ '/usr/bin'.
On Haiku, software installed for all users goes in '/boot/common',
not '/usr/local'. It is recommended to use the following options:
./configure --prefix=/boot/common
Specifying the System Type
==========================
There may be some features 'configure' cannot figure out
automatically, but needs to determine by the type of machine the package
will run on. Usually, assuming the package is built to be run on the
_same_ architectures, 'configure' can figure that out, but if it prints
a message saying it cannot guess the machine type, give it the
'--build=TYPE' option. TYPE can either be a short name for the system
type, such as 'sun4', or a canonical name which has the form:
CPU-COMPANY-SYSTEM
where SYSTEM can have one of these forms:
OS
KERNEL-OS
See the file 'config.sub' for the possible values of each field. If
'config.sub' isn't included in this package, then this package doesn't
need to know the machine type.
If you are _building_ compiler tools for cross-compiling, you should
use the option '--target=TYPE' to select the type of system they will
produce code for.
If you want to _use_ a cross compiler, that generates code for a
platform different from the build platform, you should specify the
"host" platform (i.e., that on which the generated programs will
eventually be run) with '--host=TYPE'.
Sharing Defaults
================
If you want to set default values for 'configure' scripts to share,
you can create a site shell script called 'config.site' that gives
default values for variables like 'CC', 'cache_file', and 'prefix'.
'configure' looks for 'PREFIX/share/config.site' if it exists, then
'PREFIX/etc/config.site' if it exists. Or, you can set the
'CONFIG_SITE' environment variable to the location of the site script.
A warning: not all 'configure' scripts look for a site script.
Defining Variables
==================
Variables not defined in a site shell script can be set in the
environment passed to 'configure'. However, some packages may run
configure again during the build, and the customized values of these
variables may be lost. In order to avoid this problem, you should set
them in the 'configure' command line, using 'VAR=value'. For example:
./configure CC=/usr/local2/bin/gcc
causes the specified 'gcc' to be used as the C compiler (unless it is
overridden in the site shell script).
Unfortunately, this technique does not work for 'CONFIG_SHELL' due to an
Autoconf limitation. Until the limitation is lifted, you can use this
workaround:
CONFIG_SHELL=/bin/bash ./configure CONFIG_SHELL=/bin/bash
'configure' Invocation
======================
'configure' recognizes the following options to control how it
operates.
'--help'
'-h'
Print a summary of all of the options to 'configure', and exit.
'--help=short'
'--help=recursive'
Print a summary of the options unique to this package's
'configure', and exit. The 'short' variant lists options used only
in the top level, while the 'recursive' variant lists options also
present in any nested packages.
'--version'
'-V'
Print the version of Autoconf used to generate the 'configure'
script, and exit.
'--cache-file=FILE'
Enable the cache: use and save the results of the tests in FILE,
traditionally 'config.cache'. FILE defaults to '/dev/null' to
disable caching.
'--config-cache'
'-C'
Alias for '--cache-file=config.cache'.
'--quiet'
'--silent'
'-q'
Do not print messages saying which checks are being made. To
suppress all normal output, redirect it to '/dev/null' (any error
messages will still be shown).
'--srcdir=DIR'
Look for the package's source code in directory DIR. Usually
'configure' can determine that directory automatically.
'--prefix=DIR'
Use DIR as the installation prefix. *note Installation Names:: for
more details, including other options available for fine-tuning the
installation locations.
'--no-create'
'-n'
Run the configure checks, but stop before creating any output
files.
'configure' also accepts some other, not widely useful, options. Run
'configure --help' for more details.

110
core/Makefile.am Normal file
View File

@@ -0,0 +1,110 @@
#this is the main Makefile.am for Bertini 2.
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# this project uses non-recursive make.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
AM_YFLAGS = -d -p `basename $* | sed 's,y$$,,'`
AM_LFLAGS = -s -P`basename $* | sed 's,l$$,,'` -olex.yy.c
ACLOCAL_AMFLAGS = -I m4
####################################
### set up the empty variables. these are added onto by the below included files,
### and are deliberately blank here.
#################################
bin_PROGRAMS =
BUILT_SOURCES =
CLEANFILES =
#installed headers
include_HEADERS =
rootinclude_HEADERS =
#installed libraries, both free-standing and libtool
lib_LTLIBRARIES =
lib_LIBRARIES =
#helper libraries, both free-standing and libtool
noinst_LIBRARIES =
noinst_LTLIBRARIES =
#programs which are not installed, but are optional targets for building.
EXTRA_PROGRAMS =
EXTRA_LTLIBRARIES =
TESTS =
core_all =
core_sources =
core_headers =
############################################
###### end deliberately blank items ##
##########################################
#see https://www.gnu.org/software/automake/manual/html_node/Suffixes.html
SUFFIXES = .cpp .hpp
rootincludedir = $(includedir)/bertini2
#initialize to empty and add to it in the Makemodule.am files below
############
#
# a note for developers:
#
######
#
# if you need to add an executable to the core,
# add a Makemodule.am file in the source folder for the `main()` file
# and include it below.
#
# see the b2 github wiki for detailed instructions.
# https://github.com/bertiniteam/b2
##############
############################
### now include the Makemodule.am files from the subdirectories;
### they will add on to the variables which are set above.
### note that the name `Makemodule.am` is arbitrary.
##################################
# include the bertini2 Makemodule first, as it defines some useful groups of files which are used later
# in other files.
include src/basics/Makemodule.am
include src/common/Makemodule.am
include src/function_tree/Makemodule.am
include src/system/Makemodule.am
include src/tracking/Makemodule.am
include src/endgames/Makemodule.am
include src/detail/Makemodule.am
include src/io/Makemodule.am
include src/nag_algorithms/Makemodule.am
include src/nag_datatypes/Makemodule.am
include src/pool/Makemodule.am
include src/parallel/Makemodule.am
include src/corelibrary/Makemodule.am
include src/blackbox/Makemodule.am
###
# and finally test suites, built as extras
####
include test/classes/Makemodule.am
include test/tracking_basics/Makemodule.am
include test/classic/Makemodule.am
include test/settings/Makemodule.am
include test/endgames/Makemodule.am
include test/pools/Makemodule.am
include test/generating/Makemodule.am
include test/nag_algorithms/Makemodule.am
include test/nag_datatypes/Makemodule.am
include test/blackbox/Makemodule.am

0
core/NEWS Normal file
View File

66
core/README Normal file
View File

@@ -0,0 +1,66 @@
This README contains brief instructions for how to build the core of Bertini2. For more extensive instructions, visit the wiki for the GitHub repo: https://github.com/bertiniteam/b2/wiki
If you struggle, find errors, or have comments, please let the dev team know. We want this process to be as painless as possible! Contact information can be found on the wiki.
-------------
BUILDING THE CORE OF BERTINI2
-------------
Before getting started, please note that these instructions are for Linux and Mac only. Windows build instructions are yet to come. If you want to help write those instructions (and indeed create the process), please let the devteam know!
-------------
Prerequisites:
- Compiler capable of compiling C++ code using C++14 features.
- Eigen 3.2.x or later.
- Boost 1.56 or later. To take advantage of expression templates for multiprecision real numbers (an important optimization), Boost versions prior to 1.61 must be patched. See https://github.com/boostorg/multiprecision/commit/f57bd6b31a64787425ec891bd2ceb536c9036f72 If you do not wish to patch Boost, and are using a version prior to 1.61, please disable expression templates when configuring. If you don't, you'll see a pair of errors, and comments basically saying this same message. The configure flag is --disable-expression_templates.
- Plenty of RAM. Since there are many templates in play in Bertini2, Eigen, and Boost, compilation is slower than Bertini1, and takes a lot of memory. GCC (g++) tends to use around 1 GB per thread when compiling the core, Clang perhaps 250MB. Plan your use of parallel make accordingly, and consider getting a cup of coffee while compiling. Enjoy!
-------------
Steps to compile:
-------------
1) Generate the ./configure script, and some other m4 macros, etc, so that the build system is complete. This requires the autotools, modern versions. The command for this is
autoreconf -vfi
The -vfi flags are for (v)erbose, (f)orce, and (i)nstall. If this step fails, you almost certainly have outdated autotools software, most namely automake, autoconf, and libtool. Update your tools as necessary.
Important note: on Linux machines, you typically have to run the command
libtoolize
in order to get autoreconf to work.
--------------
2) Engage in the standard build process for any software built using the autotools.
./configure (with your options)
make (consider using multiple threads [-j #] if you have enough memory)
Then, if you want to, you can run the test programs.
make check (again consider running in parallel)
The test programs are built using the Boost.UnitTest library, and can produce a variety of output files, and be run in a variety of modes. These options are not documented here. Rather, if you ask for --help on them, they will tell you more.
Finally, you probably want to install the core, particularly if you intend to build the Python bindings (b2/python).
[sudo] make install
-------------
Notes for developers:
If you add files to the project, or wish to add a compiled program, etc, you modify the b2/core/Makefile.am, and a b2/core/path/to/Makemodule.am file, or possibly create a Makemodule.am file at the correct location. If you need help with this, please contact Silviana Amethyst amethyst@uwec.edu
Please do not commit autotools-built files to the repository, including the configure script, any file in the created b2/core/config/ folder, or the others. There is a chance you may have to add a m4 macro or something, and this is ok. Do what you need, but commit only the source files, not generated files.
Please maintain this file by editing it as necessary.

28
core/cmake/FindGMP.cmake Normal file
View File

@@ -0,0 +1,28 @@
# Borrowed from https://github.com/libigl/eigen/tree/master
# By Jack Hagen (December 2023)
# Try to find the GNU Multiple Precision Arithmetic Library (GMP)
# See http://gmplib.org/
# In order to find gmp installed with conda, run 'conda activate' and use 'cmake .. -DCMAKE_PREFIX_PATH=$CONDA_PREFIX'
if (GMP_INCLUDES AND GMP_LIBRARIES)
set(GMP_FIND_QUIETLY TRUE)
endif (GMP_INCLUDES AND GMP_LIBRARIES)
find_path(GMP_INCLUDES
NAMES
gmp.h
PATHS
$ENV{GMP_INC}
${INCLUDE_INSTALL_DIR}
)
find_library(GMP_LIBRARIES gmp PATHS $ENV{GMP_LIB} ${LIB_INSTALL_DIR})
include(FindPackageHandleStandardArgs)
# Makes sure that gmp_include and gmp_libraries are valid
# https://cmake.org/cmake/help/latest/module/FindPackageHandleStandardArgs.html
find_package_handle_standard_args(GMP DEFAULT_MSG
GMP_INCLUDES GMP_LIBRARIES)
mark_as_advanced(GMP_INCLUDES GMP_LIBRARIES)

25
core/cmake/FindMPC.cmake Normal file
View File

@@ -0,0 +1,25 @@
# Borrowed from https://github.com/libigl/eigen/tree/master
# By Jack Hagen (December 2023)
# Try to find the Multiple Precision Complex (MPC)
if (MPC_INCLUDES AND MPC_LIBRARIES)
set(MPC_FIND_QUIETLY TRUE)
endif (MPC_INCLUDES AND MPC_LIBRARIES)
find_path(MPC_INCLUDES
NAMES
mpc.h
PATHS
$ENV{MPC_INC}
${INCLUDE_INSTALL_DIR}
)
find_library(MPC_LIBRARIES mpc PATHS $ENV{MPC_LIB} ${LIB_INSTALL_DIR})
include(FindPackageHandleStandardArgs)
# Makes sure that mpc_include and mpc_libraries are valid
# https://cmake.org/cmake/help/latest/module/FindPackageHandleStandardArgs.html
find_package_handle_standard_args(MPC DEFAULT_MSG
MPC_INCLUDES MPC_LIBRARIES)
mark_as_advanced(MPC_INCLUDES MPC_LIBRARIES)

85
core/cmake/FindMPFR.cmake Normal file
View File

@@ -0,0 +1,85 @@
# Try to find the MPFR library
# See http://www.mpfr.org/
#
# This module supports requiring a minimum version, e.g. you can do
# find_package(MPFR 2.3.0)
# to require version 2.3.0 to newer of MPFR.
#
# Once done this will define
#
# MPFR_FOUND - system has MPFR lib with correct version
# MPFR_INCLUDES - the MPFR include directory
# MPFR_LIBRARIES - the MPFR library
# MPFR_VERSION - MPFR version
# Copyright (c) 2006, 2007 Montel Laurent, <montel@kde.org>
# Copyright (c) 2008, 2009 Gael Guennebaud, <g.gael@free.fr>
# Copyright (c) 2010 Jitse Niesen, <jitse@maths.leeds.ac.uk>
# Redistribution and use is allowed according to the terms of the BSD license.
# Borrowed by Jack Hagen (December 2023)
# Set MPFR_INCLUDES
find_path(MPFR_INCLUDES
NAMES
mpfr.h
PATHS
$ENV{GMPDIR}
${INCLUDE_INSTALL_DIR}
)
# Set MPFR_FIND_VERSION to 1.0.0 if no minimum version is specified
if(NOT MPFR_FIND_VERSION)
if(NOT MPFR_FIND_VERSION_MAJOR)
set(MPFR_FIND_VERSION_MAJOR 1)
endif(NOT MPFR_FIND_VERSION_MAJOR)
if(NOT MPFR_FIND_VERSION_MINOR)
set(MPFR_FIND_VERSION_MINOR 0)
endif(NOT MPFR_FIND_VERSION_MINOR)
if(NOT MPFR_FIND_VERSION_PATCH)
set(MPFR_FIND_VERSION_PATCH 0)
endif(NOT MPFR_FIND_VERSION_PATCH)
set(MPFR_FIND_VERSION "${MPFR_FIND_VERSION_MAJOR}.${MPFR_FIND_VERSION_MINOR}.${MPFR_FIND_VERSION_PATCH}")
endif(NOT MPFR_FIND_VERSION)
if(MPFR_INCLUDES)
# Set MPFR_VERSION
file(READ "${MPFR_INCLUDES}/mpfr.h" _mpfr_version_header)
string(REGEX MATCH "define[ \t]+MPFR_VERSION_MAJOR[ \t]+([0-9]+)" _mpfr_major_version_match "${_mpfr_version_header}")
set(MPFR_MAJOR_VERSION "${CMAKE_MATCH_1}")
string(REGEX MATCH "define[ \t]+MPFR_VERSION_MINOR[ \t]+([0-9]+)" _mpfr_minor_version_match "${_mpfr_version_header}")
set(MPFR_MINOR_VERSION "${CMAKE_MATCH_1}")
string(REGEX MATCH "define[ \t]+MPFR_VERSION_PATCHLEVEL[ \t]+([0-9]+)" _mpfr_patchlevel_version_match "${_mpfr_version_header}")
set(MPFR_PATCHLEVEL_VERSION "${CMAKE_MATCH_1}")
set(MPFR_VERSION ${MPFR_MAJOR_VERSION}.${MPFR_MINOR_VERSION}.${MPFR_PATCHLEVEL_VERSION})
# Check whether found version exceeds minimum version
if(${MPFR_VERSION} VERSION_LESS ${MPFR_FIND_VERSION})
set(MPFR_VERSION_OK FALSE)
message(STATUS "MPFR version ${MPFR_VERSION} found in ${MPFR_INCLUDES}, "
"but at least version ${MPFR_FIND_VERSION} is required")
else(${MPFR_VERSION} VERSION_LESS ${MPFR_FIND_VERSION})
set(MPFR_VERSION_OK TRUE)
endif(${MPFR_VERSION} VERSION_LESS ${MPFR_FIND_VERSION})
endif(MPFR_INCLUDES)
# Set MPFR_LIBRARIES
find_library(MPFR_LIBRARIES mpfr PATHS $ENV{GMPDIR} ${LIB_INSTALL_DIR})
# Epilogue
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(MPFR DEFAULT_MSG
MPFR_INCLUDES MPFR_LIBRARIES MPFR_VERSION_OK)
mark_as_advanced(MPFR_INCLUDES MPFR_LIBRARIES)

14
core/compile_all_tests.sh Executable file
View File

@@ -0,0 +1,14 @@
#! /bin/bash
if [ $# -ne 1 ]
then
numprocs=1
else
numprocs=$1
fi
printf "\n\n\ncompiling with %d processor(s)\n\n\n" $numprocs | tee -a "compile_all.log"
while read suite; do
printf "\n\n%s\n\n" $suite | tee -a "compile_all.log"
make -j $numprocs $suite | tee -a "compile_all.log"
done <test/available_tests.txt

45
core/core.sublime-project Normal file
View File

@@ -0,0 +1,45 @@
{
"folders":
[
{
"path": ".",
"file_exclude_patterns": ["serialization_test*",
"Makefile",
"Makefile.in",
"*.la",
"libtool",
"stamp-h1",
".dirstamp",
"*.lo",
"*~",
"aclocal.m4",
"ltoptions.m4",
"ltsugar.m4",
"ltversion.m4",
"lt~obsolete.m4",
"libtool.m4",
"b2_class_test",
"b2_classic_compatibility_test",
"b2_timing_test",
"tracking_basics_test",
"settings_test",
"nag_algorithms_test",
"endgames_test",
"pool_test",
"generating_test",
"config.status",
"configure",
"*.trs",
"ltmain.sh",
"*.tmp"],
"folder_exclude_patterns": [
".deps",
".libs",
"*.dtps",
"autom4te.cache",
"generated_documentation",
"Launch*"]
}
],
}

View File

@@ -0,0 +1,160 @@
\documentclass{article}
\usepackage{amssymb,amsmath}
\oddsidemargin 0.0in
\textwidth 6.5in
\headheight -0.5in
\topmargin 0.5in
\headsep 0.0in
\textheight 9.2in
\parskip 3mm
\pagestyle{empty}
%%%%%%%%%%%%%%%%%%%
%%%%% INSTRUCTIONS %%%%%
%%%%%%%%%%%%%%%%%%%
% REVIEWER: Please fill out the following fields. The form will then be filled in automatically upon compilation.
% The goal of this review is to determine whether the code under review is adequate for inclusion into the develop branch of b2.
% If you have any hesitations on any yes/no question, mark no and explain your concerns.
% Please work with the author(s) of the code under review to resolve any issues.
% A final copy of all reviews must be submitted to Dan Bates before the pull request for the code under review is accepted.
% Copies of the final review forms will be kept in the repo for future reference.
%
% If you have questions, please contact Dan Bates.
\newcommand\you{ Dan Bates, bates@math.colostate.edu } %your name, email
\newcommand\class{ Example Class } %name of the class, file, or module you are reviewing
\newcommand\revdate{ 21 February 2015 } %date you are completing the review
%SCOPE
\newcommand\goals{ a,b,c } %brief but complete list of goals for the code under review
\newcommand\goalsAppropriate{ y/n } %Are these goals appropriate for this code -- yes or no?
\newcommand\goalsMet{ y/n } %Were all goals met -- yes or no?
\newcommand\goalsComments{ asdf } %Comments about goals and scope
%COMPILATION
\newcommand\compileSuccess{ y/n } %Does the code compile -- yes or no?
\newcommand\compileComments{ asdf } %Comments about compilation
%TESTING
\newcommand\testSuccess{ y/n } %Does the code pass the provided tests -- yes or no?
\newcommand\testGeneral{ y/n } %Do the provided tests adequately measure general circumstances -- yes or no?
\newcommand\testEdge { y/n } %Do the provided tests adequately include edge cases -- yes or no?
\newcommand\testComments{ asdf } %Comments about tests
%DOCUMENTATION
\newcommand\docAdequate{ y/n } %Is the code adequately commented -- yes or no?
\newcommand\docComments{ asdf } %Comments about documentation
%STYLE
\newcommand\styleAdequate{ y/n } %Does the code conform adequately to the b2 style conventions -- yes or no?
\newcommand\styleComments{ asdf } %Comments about style
%OTHER COMMENTS
\newcommand\otherComments{ asdf } %Other comments
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% END OF REVIEWER SECTION %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\bb{{bertini2\ }}
\begin{document}
\noindent
{\bf \bb review}\\
Code: \class\\
Reviewer: \you \\
Date: \revdate
\noindent\hrulefill
\noindent
{\bf Scope}
\noindent
\underbar{Goals}: \goals
\noindent
\underbar{Are these goals appropriate}? \goalsAppropriate
\noindent
\underbar{Were these goals met}? \goalsMet
\noindent
\underbar{Comments}: \\ \goalsComments
\noindent\hrulefill
\noindent
{\bf Compilation}
\noindent
\underbar{Does the code compile?} \compileSuccess
\noindent
\underbar{Comments}:\\ \compileComments
\noindent\hrulefill
\noindent
{\bf Testing}
\noindent
\underbar{Does the code pass the provided tests?} \testSuccess
\noindent
\underbar{Do the provided tests adequately measure general circumstances?} \testGeneral
\noindent
\underbar{Do the provided tests adequately include edge cases?} \testEdge
\noindent
\underbar{Comments}: \\ \testComments
\noindent\hrulefill
\noindent
{\bf Documentation}
\noindent
\underbar{Is the code adequately commented?} \docAdequate
\noindent
\underbar{Comments}: \\ \docComments
\noindent\hrulefill
\noindent
{\bf Style}
\noindent
\underbar{Does the code conform adequately to the b2 style conventions?} \styleAdequate
\noindent
\underbar{Comments}:\\ \styleComments
\noindent\hrulefill
\noindent
{\bf Other comments}\\ \otherComments
\end{document}

2569
core/doc/bertini.doxy.config Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
[^.]*

1
core/doc/images_common Symbolic link
View File

@@ -0,0 +1 @@
../../doc_resources/images/

1
core/example/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
CMakeFiles/

View File

@@ -0,0 +1 @@
build/

View File

@@ -0,0 +1,68 @@
cmake_minimum_required (VERSION 3.4)
project (parameter_homotopy_example)
IF( NOT CMAKE_BUILD_TYPE )
SET( CMAKE_BUILD_TYPE debug)
ENDIF()
message("CMAKE_BUILD_TYPE = ${CMAKE_BUILD_TYPE}")
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -g -O0")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -O2 -g")
include_directories (include)
set(MY_HEADERS
include/parameter_homotopy.hpp
)
set(MY_SOURCES
src/main.cpp
)
include(GenerateExportHeader)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
find_library(B2_LIBRARIES
NAMES "bertini2"
)
find_library(GMP_LIBRARIES
NAMES "gmp"
)
find_library(MPFR_LIBRARIES
NAMES "mpfr"
)
#Prep for compiling against boost
find_package(Boost REQUIRED
COMPONENTS system log)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
LINK_DIRECTORIES(${Boost_LIBRARY_DIRS})
find_package (Eigen3 3.3 REQUIRED NO_MODULE)
include_directories(${B2_INCLUDE_DIRS})
add_executable(parameter_homotopy_example ${MY_SOURCES})
target_link_libraries (parameter_homotopy_example ${B2_LIBRARIES} ${MPFR_LIBRARIES} ${GMP_LIBRARIES} Eigen3::Eigen ${Boost_LIBRARIES})
#set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -ltcmalloc")
#set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lprofiler")

View File

@@ -0,0 +1,14 @@
This example illustrates a way to use Bertini2 as an engine to run parameter homotopies.
--
### Compiling
Uses CMake.
1. `cd b2/core/example/parameter_homotopy`
2. `mkdir build && cd build`
3. `cmake ..`
4. `make`
Resulting product `parameter_homotopy` is in `build/bin/`

View File

@@ -0,0 +1,108 @@
#pragma once
#include <bertini2/system.hpp>
namespace demo{
using Node = std::shared_ptr<bertini::node::Node>;
using Variable = std::shared_ptr<bertini::node::Variable>;
using dbl = bertini::dbl;
using mpfr = bertini::mpfr;
auto MakeStep1Parameters()
{
using bertini::Variable::Make;
// make symbolic objects for the parameters
auto param_A = MakeFloat(bertini::RandomComplex(30));
auto param_B = MakeFloat(bertini::RandomComplex(30));
auto param_C = MakeFloat(bertini::RandomComplex(30));
auto param_D = MakeFloat(bertini::RandomComplex(30));
return std::vector<Node>{param_A, param_B, param_C, param_D};
}
template<typename ParamContT>
auto MakeStep2Parameters(ParamContT const& step1_params, Node const& time)
{
using bertini::Variable::Make;
std::vector<Node> steptwo_param_funcs;
std::vector<Variable> steptwo_params;
std::string suffix = "A";
for (const auto& p: step1_params)
{
auto new_param = Variable::Make("param_"+suffix);
steptwo_params.push_back(new_param);
steptwo_param_funcs.push_back((1-time)*new_param + time*p);
++suffix[0];
}
return std::make_tuple(steptwo_param_funcs, steptwo_params);
}
template <typename ParamContT>
auto ConstructSystem(ParamContT const& params)
{
using bertini::Variable::Make;
auto x1 = Variable::Make("x1");
auto x2 = Variable::Make("x2");
auto x3 = Variable::Make("x3");
auto x4 = Variable::Make("x4");
auto f1 = x1*x1*x1*params[0] + x1*x1*x2*params[1] + x1*x2*x2*params[2] + x1*x3*x3*params[3] + x1*x4*x4*params[0]
+ x1*params[1]+ x2*x2*x2*params[2] + x2*x3*x3*params[3] + x2*x4*x4*params[0] + x2*params[1] + 1;
auto f2 = x1*x1*x1*params[2] + x1*x1*x2*params[3] + x1*x2*x2*params[0] + x1*x3*x3*params[1] + x1*x4*x4*params[2]
+ x1*params[3] + x2*x2*x2*params[0] + x2*x3*x3*params[1] + x2*x4*x4*params[2] + x2*params[3] - 1;
auto f3 = x1*x1*x3*params[0] + x1*x2*x3*params[1] + x2*x2*x3*params[2] + x3*x3*x3*params[3] + x3*x4*x4*params[0] + x3*params[1] + 2;
auto f4 = x1*x1*x4*params[2] + x1*x2*x4*params[3] + x2*x2*x4*params[0] + x3*x3*x4*params[1] + x4*x4*x4*params[2] + x4*params[3] - 3;
// make an empty system
bertini::System Sys;
// add the functions. we could elide the `auto` construction above and construct directly into the system if we wanted
Sys.AddFunction(f1);
Sys.AddFunction(f2);
Sys.AddFunction(f3);
Sys.AddFunction(f4);
// make an affine variable group
bertini::VariableGroup vg{x1, x2, x3, x4};
Sys.AddVariableGroup(vg);
return Sys;
}
auto ConstructStart(bertini::System const& sys)
{
return bertini::start_system::TotalDegree(sys);
}
template <typename StartT>
auto ConstructHomotopy(bertini::System const& target_sys, StartT const& start_sys)
{
using bertini::Variable::Make;
auto t = Variable::Make("t");
auto gamma = bertini::Rational::Make(bertini::node::Rational::Rand());
return (1-t)*target_sys + gamma*t*start_sys;
}
} // namespace demo

View File

@@ -0,0 +1,82 @@
#pragma once
#include <bertini2/nag_algorithms/zero_dim_solve.hpp>
#include <bertini2/nag_algorithms/output.hpp>
#include <bertini2/endgames.hpp>
#include <bertini2/system.hpp>
namespace demo{
using TrackerT = bertini::tracking::AMPTracker;
using Tolerances = bertini::algorithm::TolerancesConfig;
using EndgameConfT = bertini::endgame::EndgameConfig;
auto StepOne(bertini::System const& sys)
{
using namespace bertini;
using namespace algorithm;
using EndgameT = typename endgame::EndgameSelector<TrackerT>::Cauchy;
auto zd = bertini::algorithm::ZeroDim<TrackerT, EndgameT, bertini::System, bertini::start_system::TotalDegree>(sys);
zd.DefaultSetup();
auto tols = zd.Get<Tolerances>();
tols.newton_before_endgame = 1e-5;
tols.newton_during_endgame = 1e-6;
zd.Set(tols);
auto& tr = zd.GetTracker();
tr.SetPredictor(bertini::tracking::Predictor::HeunEuler);
tracking::GoryDetailLogger<TrackerT> tr_logger;
// tr.AddObserver(&tr_logger);
endgame::GoryDetailLogger<EndgameT> eg_logger;
zd.GetEndgame().AddObserver(&eg_logger);
auto eg = zd.GetFromEndgame<EndgameConfT>();
eg.final_tolerance = 1e-11;
zd.SetToEndgame(eg);
zd.Solve();
return output::NonsingularSolutions::Extract(zd);
}
template <typename SolnContT>
auto StepTwo(bertini::System const& target_sys, bertini::System const& start_sys, bertini::System const& homotopy, SolnContT const& solns)
{
using namespace bertini;
using namespace tracking;
using namespace algorithm;
auto userss = bertini::start_system::User(start_sys, solns);
auto zd = bertini::algorithm::ZeroDim<TrackerT, typename bertini::endgame::EndgameSelector<TrackerT>::Cauchy, bertini::System, bertini::start_system::User, bertini::policy::RefToGiven>(target_sys, userss, homotopy);
zd.DefaultSetup();
zd.GetTracker().SetPredictor(bertini::tracking::Predictor::HeunEuler);
auto tols = zd.Get<Tolerances>();
tols.newton_before_endgame = 1e-6;
tols.newton_during_endgame = 1e-7;
zd.Set(tols);
auto eg = zd.GetFromEndgame<EndgameConfT>();
eg.final_tolerance = 1e-12;
zd.SetToEndgame(eg);
zd.Solve();
return output::AllSolutions::Extract(zd);
}
} // namespace demo

View File

@@ -0,0 +1,46 @@
// a little bit of code to generate random real numbers, either integral or floating point.
#include <random>
#include <iostream>
#pragma once
namespace demo{
template<typename T>
struct Random
{
static
T Generate()
{
static_assert(std::is_arithmetic<T>::value, "must use an arithmetic type");
return Generate(std::is_integral<T>());
}
private:
static
T Generate(std::true_type)
{
static std::random_device rd;
static std::default_random_engine gen(rd());
static std::uniform_int_distribution<T> dist(std::numeric_limits<T>::min(),std::numeric_limits<T>::max());
return dist(gen);
}
static
T Generate(std::false_type)
{
static std::random_device rd;
static std::default_random_engine gen(rd());
static std::uniform_real_distribution<T> dist(T{-1},T{1});
return dist(gen);
}
};
}

View File

@@ -0,0 +1,72 @@
#include "parameter_homotopy.hpp"
#include "random.hpp"
#include "my_system.hpp"
#include <chrono>
int main()
{
bertini::LoggingInit();
auto step1_params = demo::MakeStep1Parameters();
auto target_sys_step1 = demo::ConstructSystem(step1_params);
std::cout << "your target_system for step 1:\n\n";
std::cout << target_sys_step1 << '\n';
std::cout << "\n\nwith parameter values:\n\n";
for (const auto& p : step1_params)
std::cout << p << " ";
std::cout << '\n';
// now to solve the start system.
auto stepone_solutions = demo::StepOne(target_sys_step1);
std::cout << "done computing the " << stepone_solutions.size() << " step1 solutions, and here they are: \n";
for (auto& iter : stepone_solutions)
std::cout << iter << '\n' << '\n';
auto t = bertini::Variable::Make("t");
auto step2_stuff = demo::MakeStep2Parameters(step1_params, t);
auto homotopy_sys_step2 = demo::ConstructSystem(std::get<0>(step2_stuff));
homotopy_sys_step2.AddPathVariable(t);
auto target_sys_step2 = demo::ConstructSystem(std::get<1>(step2_stuff));
int num_to_step2s = 100;
auto start_allstep2 = std::chrono::high_resolution_clock::now();
for (int ii=0; ii<num_to_step2s; ii++)
{
auto start_iteration = std::chrono::high_resolution_clock::now();
bertini::DefaultPrecision(30);
// iterate over the parameter values. set the
for (auto& p : std::get<1>(step2_stuff))
{
bertini::mpfr v;
bertini::RandomReal(v, 30);
p->precision(30);
p->set_current_value(bertini::dbl(v));
p->set_current_value(v);
}
bertini::DefaultPrecision(16);
// std::cout << "your target system for step2:\n" << target_sys_step2 << '\n';
// for (auto& p : std::get<1>(step2_stuff))
// std::cout << "solving for parameter values " << *p << " " << p->Eval<bertini::dbl>() << '\n';
auto steptwo_solutions = demo::StepTwo(target_sys_step2, target_sys_step1, homotopy_sys_step2, stepone_solutions);
// std::cout << "done computing the " << steptwo_solutions.size() << " step2 solutions, and here they are: \n";
// for (auto& iter : steptwo_solutions)
// std::cout << iter << '\n' << '\n';
std::cout << (std::chrono::high_resolution_clock::now() - start_iteration).count() << '\n';
}
std::cout << "solving " << num_to_step2s << " " << (std::chrono::high_resolution_clock::now() - start_allstep2).count() << '\n';
return 0;
}

View File

@@ -0,0 +1 @@
build/

View File

@@ -0,0 +1,68 @@
cmake_minimum_required (VERSION 3.4)
project (performance_numbers)
IF( NOT CMAKE_BUILD_TYPE )
SET( CMAKE_BUILD_TYPE release)
ENDIF()
message("CMAKE_BUILD_TYPE = ${CMAKE_BUILD_TYPE}")
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -g -O0")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -O2 -g")
include_directories (include)
set(MY_HEADERS
include/construct_system.hpp
)
set(MY_SOURCES
src/main.cpp
)
include(GenerateExportHeader)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
find_library(B2_LIBRARIES
NAMES "bertini2"
)
find_library(GMP_LIBRARIES
NAMES "gmp"
)
find_library(MPFR_LIBRARIES
NAMES "mpfr"
)
#Prep for compiling against boost
find_package(Boost REQUIRED
COMPONENTS system log)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
LINK_DIRECTORIES(${Boost_LIBRARY_DIRS})
find_package (Eigen3 3.3 REQUIRED NO_MODULE)
include_directories(${B2_INCLUDE_DIRS})
add_executable(performance_numbers ${MY_SOURCES})
target_link_libraries (performance_numbers ${B2_LIBRARIES} ${MPFR_LIBRARIES} ${GMP_LIBRARIES} Eigen3::Eigen ${Boost_LIBRARIES})
#set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -ltcmalloc")
#set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lprofiler")

View File

@@ -0,0 +1,14 @@
This example illustrates a way to use Bertini2 as an engine to run parameter homotopies.
--
### Compiling
Uses CMake.
1. `cd b2/core/example/parameter_homotopy`
2. `mkdir build && cd build`
3. `cmake ..`
4. `make`
Resulting product `parameter_homotopy` is in `build/bin/`

View File

@@ -0,0 +1,120 @@
#pragma once
#include <bertini2/system.hpp>
template<typename NumType> using Vec = Eigen::Matrix<NumType, Eigen::Dynamic, 1>;
template<typename NumType> using Mat = Eigen::Matrix<NumType, Eigen::Dynamic, Eigen::Dynamic>;
using dbl = bertini::dbl;
using mpfr = bertini::mpfr;
namespace demo{
using Node = std::shared_ptr<bertini::node::Node>;
using Variable = std::shared_ptr<bertini::node::Variable>;
auto ConstructSystem1()
{
using bertini::Variable::Make;
using bertini::Integer::Make;
using bertini::MakeFloat;
auto x1 = Variable::Make("x1");
auto x2 = Variable::Make("x2");
auto x3 = Variable::Make("x3");
auto x4 = Variable::Make("x4");
auto p1 = MakeFloat("3.2");
auto p2 = MakeFloat("-2.8");
auto p3 = bertini::MakeFloat("3.5");
auto p4 = MakeFloat("-3.6");
std::vector<Node> params{p1, p2, p3, p4};
auto f1 = pow(x1,3)*params[0] + x1*x1*x2*params[1] + x1*x2*x2*params[2] + x1*x3*x3*params[3] + x1*x4*x4*params[0]
+ x1*params[1]+ x2*x2*x2*params[2] + x2*pow(x3,2)*params[3] + x2*x4*x4*params[0] + x2*params[1] + 1;
auto f2 = x1*x1*x1*params[2] + x1*x1*x2*params[3] + x1*x2*x2*params[0] + x1*x3*x3*params[1] + x1*x4*x4*params[2]
+ x1*params[3] + x2*x2*x2*params[0] + x2*x3*x3*params[1] + x2*x4*x4*params[2] + x2*params[3] - 1;
auto f3 = x1*x1*x3*params[0] + x1*x2*x3*params[1] + x2*x2*x3*params[2] + x3*x3*x3*params[3] + x3*pow(x4,2)*params[0] + x3*params[1] + 2;
auto f4 = pow(x1,2)*x4*params[2] + x1*x2*x4*params[3] + x2*x2*x4*params[0] + x3*x3*x4*params[1] + x4*x4*x4*params[2] + x4*params[3] - 3;
// make an empty system
bertini::System Sys;
// add the functions. we could elide the `auto` construction above and construct directly into the system if we wanted
Sys.AddFunction(f1);
Sys.AddFunction(f2);
Sys.AddFunction(f3);
Sys.AddFunction(f4);
// make an affine variable group
bertini::VariableGroup vg{x1, x2, x3, x4};
Sys.AddVariableGroup(vg);
Sys.Differentiate();
return Sys;
}
template<typename CType>
auto GenerateSystemInput(bertini::System S, unsigned int prec=16)
{
int num_variables = S.NumVariables();
Vec<CType> v(num_variables);
bertini::DefaultPrecision(prec);
for(int ii = 0; ii < num_variables; ++ii)
{
v(ii) = CType(3)*bertini::RandomUnit<CType>();
}
return v;
}
template<typename CType>
auto GenerateRHS(bertini::System S, unsigned int prec=16)
{
auto num_functions = S.NumFunctions();
Vec<CType> b(num_functions);
bertini::DefaultPrecision(prec);
for(int ii = 0; ii < num_functions; ++ii)
{
b(ii) = CType(3)*bertini::RandomUnit<CType>();
}
return b;
}
template<typename CType>
auto GenerateMatrix(int N, unsigned int prec=16)
{
Mat<CType> A(N,N);
bertini::DefaultPrecision(prec);
for(int ii = 0; ii < N; ++ii)
{
for(int jj = 0; jj < N; ++jj)
{
A(ii,jj) = CType(3)*bertini::RandomUnit<CType>();
}
}
return A;
}
} // namespace demo

View File

@@ -0,0 +1,34 @@
//
// performance_tests.hpp
// Xcode_b2
//
// Created by Jeb Collins University of Mary Washington. All rights reserved.
//
#ifndef performance_tests_h
#define performance_tests_h
#include "construct_system.hpp"
template<typename CType>
void EvalAndLUTests(const bertini::System& S, const bertini::Vec<CType>& v,
const bertini::Vec<CType>& b, int num_times)
{
auto J = S.Jacobian(v);
for(int ii = 0; ii < num_times; ++ii)
{
S.Reset();
J = S.Jacobian(v);
J.lu().solve(b);
}
}
template<typename CType>
void MatrixMultTests(const Mat<CType>& A, int num_times)
{
for(int ii = 0; ii < num_times; ++ii)
{
A*A;
}
}
#endif /* performance_tests_h */

View File

@@ -0,0 +1,110 @@
#include "performance_tests.hpp"
#include <ctime>
int main()
{
int num_evaluations = 1; ///> Number of times to evaluate the Jacobian in each run
int num_test_runs = 5000; ///> number of times to run the test for average
int num_precisions = 20 ; ///> number of different precisions to use
int max_precision = 308; ///> maximum precision used for testing
int matrix_N = 500; ///> size of matrix for matrix multiplication
std::vector<int> precisions(num_precisions-1);
for(int P = 0; P < num_precisions-1; ++P)
{
precisions[P] = std::floor(16 + ((max_precision)-16.0)/num_precisions*(P));
}
precisions.push_back(max_precision);
// Compute the time using CPU clock time, not wall clock time.
auto start = std::clock();
auto end = std::clock();
auto sys1 = demo::ConstructSystem1();
auto v_d = demo::GenerateSystemInput<dbl>(sys1);
auto b_d = demo::GenerateRHS<dbl>(sys1);
auto A_d = demo::GenerateMatrix<dbl>(matrix_N);
auto v_mp = demo::GenerateSystemInput<mpfr>(sys1);
auto b_mp = demo::GenerateRHS<mpfr>(sys1);
auto A_mp = demo::GenerateMatrix<mpfr>(matrix_N);
//Get base number for double precision
std::cout << "\n\n\nTesting Jacobian evaluation, matrix multiplication, and LU decomposition in double precision:\n\n";
double time_delta_d = 0;
for(int ii = 0; ii < num_test_runs; ++ii)
{
start = std::clock();
EvalAndLUTests(sys1, v_d, b_d, num_evaluations);
MatrixMultTests(A_d, 100*num_evaluations);
end = std::clock();
time_delta_d += (double)(end-start)/(double)(CLOCKS_PER_SEC);
}
time_delta_d = time_delta_d/num_test_runs;
std::cout << "Average time taken:\n";
std::cout << time_delta_d << std::endl << std::endl;
// Now work with various precisions for mpfr
std::cout << "Testing Jacobian evaluation, matrix multiplication, and LU decomposition in multiple precision:\n\n";
Vec<double> time_delta_mp(num_precisions);
for(int PP = 0; PP < num_precisions; ++PP)
{
std::cout << "Evaluating with precision " << precisions[PP] << "...\n";
time_delta_mp(PP) = 0;
v_mp = demo::GenerateSystemInput<mpfr>(sys1, precisions[PP]);
b_mp = demo::GenerateRHS<mpfr>(sys1, Precision(v_mp));
sys1.precision(Precision(v_mp));
for(int ii = 0; ii < num_test_runs; ++ii)
{
start = std::clock();
EvalAndLUTests(sys1, v_mp, b_mp, num_evaluations);
MatrixMultTests(A_mp, 100*num_evaluations);
end = std::clock();
time_delta_mp(PP) += (double)(end-start)/(double)(CLOCKS_PER_SEC);
}
time_delta_mp(PP) = time_delta_mp(PP)/num_test_runs;
}
// std::cout << time_delta_mp << std::endl;
auto time_factors = time_delta_mp/time_delta_d;
// Compute coefficient for linear fit
Mat<double> M(2,2);
Vec<double> b(2);
M(0,0) = num_precisions;
M(0,1) = 0;
M(1,1) = 0;
b(0) = 0; b(1) = 0;
for(int ii = 0; ii < num_precisions; ++ii)
{
M(0,1) += precisions[ii];
M(1,1) += pow(precisions[ii],2);
b(0) += time_factors(ii);
b(1) += precisions[ii]*time_factors(ii);
}
M(1,0) = M(0,1);
Vec<double> x = M.lu().solve(b);
// std::cout << x(0) << std::endl;
std::cout << "y(P) = "<< x(1)<<"*P + "<< x(0) << std::endl;
return 0;
}

View File

@@ -0,0 +1,41 @@
//This file is part of Bertini 2.
//
//bertini.hpp 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.
//
//bertini.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2017 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
/**
\file bertini.hpp
\brief The main file for including the entirety of Bertini's header files.
*/
#ifndef BERTINI_HPP
#define BERTINI_HPP
#include "bertini2/blackbox/argc_argv.hpp"
#include "bertini2/blackbox/main_mode_switch.hpp"
#include "bertini2/parallel.hpp"
#endif

View File

@@ -0,0 +1,74 @@
//This file is part of Bertini 2.
//
//bertini2/blackbox/algorithm_builder.hpp 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.
//
//bertini2/blackbox/algorithm_builder.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/blackbox/algorithm_builder.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2017-2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
//
// individual authors of this file include
//
// silviana amethyst, university of wisconsin-eau claire
/**
\file include/bertini2/blackbox/algorithm_builder.hpp
\brief A type which determines which algorithms etc, to run, and sets them up.
*/
#pragma once
#include "bertini2/io/file_utilities.hpp"
namespace bertini {
namespace blackbox {
/**
\brief A de-serializer, whose responsibility it is to construct runnable objects based on input files.
This class is inspired by the SimBuilder class from Hythem Sidky's SAPHRON package for molecular dynamics.
*/
class AlgoBuilder
{
public:
AlgoBuilder() = default;
/**
\brief Method for constructing an algorithm from a bertini classic input file
*/
int ClassicBuild(boost::filesystem::path const& input_file);
/**
\brief Returns a non-owning pointer to the built algorithm
*/
AnyAlgorithm* GetAlg()
{
return alg_.get();
}
private:
std::unique_ptr<AnyAlgorithm> alg_;
};
} // blackbox
} //namespace bertini

View File

@@ -0,0 +1,41 @@
//This file is part of Bertini 2.
//
//bertini2/blackbox/argc_argv.hpp 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.
//
//bertini2/blackbox/argc_argv.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/blackbox/argc_argv.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
/**
\file bertini2/blackbox/argc_argv.hpp
\brief Provides the methods for parsing the command-line arguments.
*/
#pragma once
namespace bertini{
/**
Main initial function for doing stuff to interpret the command-line arguments for invokation of the program.
\param argc The number of arguments to the program. Must be at least one.
\param argv array of character arrays, the arguments to the program when called.
*/
void ParseArgcArgv(int argc, char** argv);
} //namespace bertini

View File

@@ -0,0 +1,73 @@
//This file is part of Bertini 2.
//
//bertini2/blackbox/config.hpp 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.
//
//bertini2/blackbox/config.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/blackbox/config.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2017-2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
//
// silviana amethyst, university of wisconsin-eau claire
/**
\file bertini2/blackbox/config.hpp
\brief Configs for the blackbox whatnot
*/
#pragma once
namespace bertini{
namespace blackbox{
namespace type{
enum class Start{ TotalDegree, MHom, User};
enum class Tracker{ FixedDouble, FixedMultiple, Adaptive};
enum class Endgame{ PowerSeries, Cauchy};
}
template<typename T>
struct StorageSelector{};
template<>
struct StorageSelector<start_system::User>
{
using ShouldClone = typename std::false_type;
// typename algorithm::StorageSelector<StartType>::Storage
// using Storage = typename policy::RefToGiven<System, start_system::User>;
};
template<>
struct StorageSelector<start_system::TotalDegree>
{
// using Storage = typename policy::CloneGiven<System, start_system::TotalDegree>;
// typedef policy::CloneGiven Storage;
using ShouldClone = typename std::true_type;
// using Storage = typename policy::CloneGiven;
};
template<>
struct StorageSelector<start_system::MHomogeneous>
{
using ShouldClone = typename std::true_type;
// template < typename T, typename S>
// using Storage = typename policy::CloneGiven<T,S>;
};
}
}

View File

@@ -0,0 +1,83 @@
//This file is part of Bertini 2.
//
//bertini2/blackbox/global_configs.hpp 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.
//
//bertini2/blackbox/global_configs.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/blackbox/global_configs.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2017-2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
//
// silviana amethyst, university of wisconsin-eau claire
/**
\file bertini2/blackbox/global_configs.hpp
\brief Provides types and utilities for dealing with global defaults for the blackbox routines
*/
#pragma once
#include "bertini2/detail/typelist.hpp"
#include "bertini2/detail/configured.hpp"
#include "bertini2/trackers/config.hpp"
#include "bertini2/endgames/config.hpp"
#include "bertini2/nag_algorithms/common/config.hpp"
namespace bertini{
namespace blackbox{
namespace config {
namespace {
using namespace tracking;
using namespace endgame;
using namespace algorithm;
}
struct Configs
{
using Tracking = detail::TypeList<SteppingConfig, NewtonConfig, FixedPrecisionConfig, AdaptiveMultiplePrecisionConfig, tracking::PrecisionType, Predictor>;
using Endgame = detail::TypeList<SecurityConfig, EndgameConfig, PowerSeriesConfig, CauchyConfig, TrackBackConfig>;
template<typename T>
using Algorithm = detail::TypeList<TolerancesConfig, MidPathConfig, AutoRetrackConfig, SharpeningConfig, RegenerationConfig, PostProcessingConfig, ZeroDimConfig<T>, classic::AlgoChoice>;
template<typename T>
using All = detail::ListCat<Tracking, Endgame, Algorithm<T>>;
};
struct Defaults :
detail::Configured<Configs::All<bertini::dbl>, Configs::All<bertini::mpfr_complex>>
{
};
}
} // namespace blackbox
} // namespace bertini

View File

@@ -0,0 +1,40 @@
//This file is part of Bertini 2.
//
//bertini2/blackbox/main_mode_switch.hpp 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.
//
//bertini2/blackbox/main_mode_switch.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/blackbox/main_mode_switch.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
//
// silviana amethyst, university of wisconsin-eau claire
/**
\file bertini2/blackbox/main_mode_switch.hpp
\brief Provides the main mode switch for the Bertini2 executable program.
*/
#pragma once
namespace bertini{
void MainModeSwitch();
}

View File

@@ -0,0 +1,135 @@
//This file is part of Bertini 2.
//
//bertini2/blackbox/switches_zerodim.hpp 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.
//
//bertini2/blackbox/switches_zerodim.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/blackbox/switches_zerodim.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2017-2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
//
// silviana amethyst, university of wisconsin-eau claire
/**
\file bertini2/blackbox/switches_zerodim.hpp
\brief A sequence of switches for getting a particular instantiation of a ZeroDim algorithm, based on runtime options.
*/
#pragma once
#include "bertini2/system.hpp"
#include "bertini2/nag_algorithms/zero_dim_solve.hpp"
#include "bertini2/endgames.hpp"
#include "bertini2/blackbox/config.hpp"
namespace bertini{
namespace blackbox{
struct ZeroDimRT
{
type::Start start = type::Start::TotalDegree;
type::Tracker tracker = type::Tracker::Adaptive;
type::Endgame endgame = type::Endgame::Cauchy;
};
template <typename StartType, typename TrackerType, typename EndgameType, template<typename,typename> class SystemManagementPol, typename ... ConstTs>
std::unique_ptr<algorithm::AnyZeroDim> ZeroDimSpecifyComplete(ConstTs const& ...ts)
{
return std::make_unique<
algorithm::ZeroDim<
TrackerType,
EndgameType,
System,
StartType,
SystemManagementPol>
>(ts...);
}
template <typename StartType, typename TrackerType, typename EndgameType, typename ... ConstTs>
std::unique_ptr<algorithm::AnyZeroDim> ZeroDimSpecifyShouldClone(std::true_type, ConstTs const& ...ts)
{
return ZeroDimSpecifyComplete<StartType, TrackerType,
typename endgame::EndgameSelector<TrackerType>::Cauchy, policy::CloneGiven>(ts...);
}
template <typename StartType, typename TrackerType, typename EndgameType, typename ... ConstTs>
std::unique_ptr<algorithm::AnyZeroDim> ZeroDimSpecifyShouldClone(std::false_type, ConstTs const& ...ts)
{
return ZeroDimSpecifyComplete<StartType, TrackerType,
typename endgame::EndgameSelector<TrackerType>::Cauchy, policy::RefToGiven>(ts...);
}
template <typename StartType, typename TrackerType, typename ... ConstTs>
std::unique_ptr<algorithm::AnyZeroDim> ZeroDimSpecifyEndgame(ZeroDimRT const& rt, ConstTs const& ...ts)
{
switch (rt.endgame)
{
case type::Endgame::PowerSeries:
return ZeroDimSpecifyShouldClone<StartType, TrackerType,
typename endgame::EndgameSelector<TrackerType>::PSEG>(typename StorageSelector<StartType>::ShouldClone(), ts...);
case type::Endgame::Cauchy:
return ZeroDimSpecifyShouldClone<StartType, TrackerType,
typename endgame::EndgameSelector<TrackerType>::Cauchy>(typename StorageSelector<StartType>::ShouldClone(), ts...);
}
}
template <typename StartType, typename ... ConstTs>
std::unique_ptr<algorithm::AnyZeroDim> ZeroDimSpecifyTracker(ZeroDimRT const& rt, ConstTs const& ...ts)
{
switch (rt.tracker)
{
case type::Tracker::FixedDouble:
return ZeroDimSpecifyEndgame<StartType, tracking::DoublePrecisionTracker>(rt, ts...);
case type::Tracker::FixedMultiple:
return ZeroDimSpecifyEndgame<StartType, tracking::MultiplePrecisionTracker>(rt, ts...);
case type::Tracker::Adaptive:
return ZeroDimSpecifyEndgame<StartType, tracking::AMPTracker>(rt, ts...);
}
}
template <typename ... ConstTs>
std::unique_ptr<algorithm::AnyZeroDim> ZeroDimSpecifyStart(ZeroDimRT const& rt, ConstTs const& ...ts)
{
switch (rt.start)
{
case type::Start::TotalDegree:
return ZeroDimSpecifyTracker<start_system::TotalDegree>(rt, ts...);
case type::Start::MHom:
return ZeroDimSpecifyTracker<start_system::MHomogeneous>(rt, ts...);
case type::Start::User:
throw std::runtime_error("trying to use generic zero dim with user homotopy. use the specific UserBlaBla instead");
}
}
template <typename ... ConstTs>
std::unique_ptr<algorithm::AnyZeroDim> MakeZeroDim(ZeroDimRT const& rt, ConstTs const& ...ts)
{
return ZeroDimSpecifyStart(rt, ts...);
}
} //ns blackbox
} //ns bertini

View File

@@ -0,0 +1,63 @@
//This file is part of Bertini 2.
//
//bertini2/blackbox/switches_zerodim.hpp 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.
//
//bertini2/blackbox/switches_zerodim.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/blackbox/switches_zerodim.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2017-2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
//
// silviana amethyst, university of wisconsin-eau claire
/**
\file bertini2/blackbox/switches_zerodim.hpp
\brief A sequence of switches for getting a particular instantiation of a ZeroDim algorithm, based on runtime options.
*/
#pragma once
#include "bertini2/system.hpp"
#include "bertini2/nag_algorithms/zero_dim_solve.hpp"
#include "bertini2/endgames.hpp"
#include "bertini2/blackbox/config.hpp"
namespace bertini{
namespace blackbox{
template <typename ... ConstTs>
std::unique_ptr<algorithm::AnyZeroDim> UserHomSpecifyStart(ZeroDimRT const& rt, ConstTs const& ...ts)
{
return ZeroDimSpecifyTracker<start_system::User>(rt, ts...);
}
template <typename ... ConstTs>
std::unique_ptr<algorithm::AnyZeroDim> MakeUserHom(ZeroDimRT const& rt, ConstTs const& ...ts)
{
return UserHomSpecifyStart(rt, ts...);
}
} //ns blackbox
} //ns bertini

View File

@@ -0,0 +1,40 @@
//This file is part of Bertini 2.
//
//classic.hpp 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.
//
//classic.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with classic.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2017 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, University of Wisconsin Eau Claire
/**
\file classic.hpp
\brief Includes for classic compatibility
*/
#ifndef BERTINI_CLASSIC_HPP
#define BERTINI_CLASSIC_HPP
#include "bertini2/classic/split_parsing.hpp"
#endif

View File

@@ -0,0 +1,74 @@
//This file is part of Bertini 2.
//
//bertini2/common/config.hpp 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.
//
//bertini2/common/config.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with tracking/include/bertini2/trackers/config.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of notre dame, university of wisconsin eau claire
// Tim Hodges, Colorado State University
#ifndef BERTINI2_COMMON_CONFIG
#define BERTINI2_COMMON_CONFIG
#pragma once
namespace bertini
{
// aliases for the types used to contain space and time samples, and random vectors for the endgames.
template<typename T> using SampCont = std::deque<Vec<T> >;
template<typename T> using TimeCont = std::deque<T>;
enum class ContStart{
Front,
Back
};
enum class SuccessCode
{
NeverStarted = -1,
Success = 0,
HigherPrecisionNecessary,
ReduceStepSize,
GoingToInfinity,
FailedToConverge,
MatrixSolveFailure,
MatrixSolveFailureFirstPartOfPrediction,
MaxNumStepsTaken,
MaxPrecisionReached,
MinStepSizeReached,
Failure,
SingularStartPoint,
ExternallyTerminated,
MinTrackTimeReached,
SecurityMaxNormReached,
CycleNumTooHigh,
};
using NumErrorT = double;
} // namespace bertini
#include "bertini2/common/stream_enum.hpp"
#endif // include guard

View File

@@ -0,0 +1,60 @@
//This file is part of Bertini 2.
//
//bertini2/common/stream_enum.hpp 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.
//
//bertini2/common/stream_enum.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with tracking/include/bertini2/trackers/config.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of notre dame, university of wisconsin eau claire
// Tim Hodges, Colorado State University
#ifndef BERTINI2_STREAM_ENUM
#define BERTINI2_STREAM_ENUM
#pragma once
namespace bertini
{
/**
\brief Method for printing class enums to streams.
This was adapted from https://stackoverflow.com/questions/11421432/how-can-i-output-the-value-of-an-enum-class-in-c11
asked by user Adi, answered by James Adkison. This code was provided CC-BY-SA 3.
This code does NOT work for streaming enum classes to Boost.Log streams.
\param stream The stream to print to.
\param e The enum value to print
\return The stream you are writing to.
*/
template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
return stream << static_cast<typename std::underlying_type<T>::type>(e);
}
} // namespace bertini
#endif // include guard

View File

@@ -0,0 +1,130 @@
//This file is part of Bertini 2.
//
//configured.hpp 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.
//
//configured.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with configured.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2016 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
//
// detail/configured.hpp
/**
\file detail/configured.hpp
\brief Contains the detail/configured helper type, for templated getting/setting/storage of config structs
*/
#pragma once
#include "bertini2/detail/is_template_parameter.hpp"
namespace bertini {
namespace detail{
/**
This templated struct allows one to provide a variable typelist of config structs (or anything else for that matter), and provides a way to get and set these configs by looking up the structs by type.
I will add lookup by index if it is needed. If you need to look up by index, try type first. If your types are non-unique, consider making a struct to hold the things you are storing.
## On nested configs. If two or more things in your inheritance tree require Configured,
consider the following code, which can help determine whether to Get or Set from here, or to pass
down the tree to a base class.
\code
template <typename T>
const
typename std::enable_if<detail::IsTemplateParameter<T, config::Cauchy<typename TrackerTraits<TrackerType>::BaseRealType>>::value, T>::type
& Get() const
{
return Config::template Get<T>();
}
template <typename T>
const
typename std::enable_if<not detail::IsTemplateParameter<T, config::Cauchy<typename TrackerTraits<TrackerType>::BaseRealType>>::value, T>::type
& Get() const
{
return EndgameBase<TrackerType, FinalEGT, UsedNumTs...>::template Get<T>();
}
template <typename T>
typename std::enable_if<detail::IsTemplateParameter<T, config::Cauchy<typename TrackerTraits<TrackerType>::BaseRealType>>::value, void>::type
Set(T const& t)
{
Config::template Set(t);
}
template <typename T>
typename std::enable_if<not detail::IsTemplateParameter<T, config::Cauchy<typename TrackerTraits<TrackerType>::BaseRealType>>::value, void>::type
Set(T const& t)
{
EndgameBase<TrackerType, FinalEGT, UsedNumTs...>::template Set(t);
}
\endcode
*/
template<typename ...Ts>
struct Configured
{
std::tuple<Ts...> configuration_;
template<typename ... T>
Configured(T const& ...t) : configuration_(t...)
{}
template<typename T, typename = typename std::enable_if<IsTemplateParameter<T,Ts...>::value>::type>
const T& Get() const
{
return std::get<T>(configuration_);
}
template<typename T, typename = typename std::enable_if<IsTemplateParameter<T,Ts...>::value>::type>
void Set(T const& t)
{
std::get<T>(configuration_) = t;
}
using UsedConfigs = TypeList<Ts...>;
}; // Configured
template<typename ...Ts>
struct Configured<TypeList<Ts...>> : public Configured<Ts...>
{
template<typename ... T>
Configured(T const& ...t) : Configured<Ts...>(t...)
{}
Configured() : Configured<Ts...>() {}
};
#define FORWARD_GET_CONFIGURED \
template <typename T> \
const T& Get() const \
{ return Config::template Get<T>();}
} // namespace detail
}

View File

@@ -0,0 +1,141 @@
//This file is part of Bertini 2.
//
//enable_permuted_arguments.hpp 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.
//
//enable_permuted_arguments.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with enable_permuted_arguments.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
// additionally, this file contains code
// based on and refined from SO post
// https://stackoverflow.com/questions/19329297/constructor-permutations-for-passing-parameters-in-arbitrary-order
// by user Daniel Frey.
/**
\file enable_permuted_arguments.hpp
Contains helper templates, based on and refined from SO post
https://stackoverflow.com/questions/19329297/constructor-permutations-for-passing-parameters-in-arbitrary-order
by user Daniel Frey.
*/
#ifndef BERTINI_ENABLE_PERMUTED_ARGUMENTS
#define BERTINI_ENABLE_PERMUTED_ARGUMENTS
#include <type_traits>
#include <tuple>
namespace bertini {
namespace detail {
// find the index of a type in a list of types,
// return sizeof...(Remaining) if T is not found
template< typename T, typename... Remaining >
struct IndexByType : std::integral_constant< std::size_t, 0 >
{};
// template specialization, enforcing the equality of the number of variadic arguments, and the corresponding index.
// if two types are the same, this template will be preferred since it's a closer match, and the static_assert will fail, preventing compilation.
template< typename T, typename... RemainingT >
struct IndexByType< T, T, RemainingT... > : std::integral_constant< std::size_t, 0 >
{
static_assert( IndexByType< T, RemainingT... >::value == sizeof...( RemainingT ), "No duplicates are allowed when enabling permuted arguments" );
};
// template specialization on two types. looks for the index of T in the latter arguments. If T1==T2, this template will not be used, but instead the above will.
template< typename T1, typename T2, typename... RemainingT >
struct IndexByType< T1, T2, RemainingT... > : std::integral_constant< std::size_t, IndexByType< T1, RemainingT... >::value + 1 >
{};
// a free function which gets a type from a tuple with no duplicates. Remember, duplicates are not allowed.
template< std::size_t I, std::size_t J,
typename T, typename... PresentT, typename... GivenT >
auto GetByIndex( const std::tuple< PresentT... >&,
const std::tuple< GivenT... >& absent_args )
-> typename std::enable_if< I == sizeof...( PresentT ), const T& >::type
{
return std::get< J >( absent_args );
}
// the other half of the get by index function
template< std::size_t I, std::size_t J,
typename T, typename... PresentT, typename... GivenT >
auto GetByIndex(const std::tuple< PresentT... >& present_args,
const std::tuple< GivenT... >& ) // these arguments will have to be default constructed
-> typename std::enable_if< I != sizeof...( PresentT ), const T& >::type /* remember, `I != sizeof...( PresentT )` means it found T in PresentT */
{
return std::get< I >( present_args );
}
// helper to validate that all Us are in Ts...
template< bool > struct AreValidArguments;
// the false one is never instantiated, so the 'false' template parameter will fail, deliberately
template<> struct AreValidArguments< true > : std::true_type
{};
// a proxy function which to ensure that the types are distinct, and that we can indeed get the index by type.
template< std::size_t... >
void ValidateTypes()
{}
// default construct the objects not present in the arguments, but required by the unpermute function
template< typename T >
struct DefaultConstruct
{ static const T value; };
template< typename T >
const T DefaultConstruct< T >::value
{};
} // namespace detail
// helper template which reorders parameters
template< typename... UnpermutedT, // these must be declared when using the function
typename... PermutedPresentT > // these are inferred, cannot be declared
std::tuple< const UnpermutedT&... > Unpermute( const PermutedPresentT&... present_permuted_args )
{
using namespace detail;
auto present_args = std::tie( present_permuted_args... );
auto absent_args = std::tie( DefaultConstruct< UnpermutedT >::value... );
//next we validate that the input arguments are valid for unpermuting. must have all distinct types.
ValidateTypes< AreValidArguments< IndexByType< const PermutedPresentT&,
const UnpermutedT&... >::value != sizeof...( UnpermutedT )
>::value...
>(); // this will fail if AreValidArguments are not valid ('true')
// finally, we return a tie of the unpermuted types, default constructed if necessary
return std::tie( GetByIndex< IndexByType< const UnpermutedT&, const PermutedPresentT&... >::value,
IndexByType< const UnpermutedT&, const UnpermutedT&... >::value, UnpermutedT >
( present_args, absent_args )... );
}
} // re: namespace bertini
#endif

View File

@@ -0,0 +1,165 @@
//This file is part of Bertini 2.
//
//events.hpp 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.
//
//events.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with events.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
//
// detail/events.hpp
/**
\file detail/events.hpp
\brief Contains the detail/events base types
*/
#ifndef BERTINI_DETAIL_EVENTS_HPP
#define BERTINI_DETAIL_EVENTS_HPP
#include <boost/type_index.hpp>
namespace bertini {
/**
\brief Strawman Event type, enabling polymorphism.
This class is abstract, and should never actually be created.
*/
class AnyEvent
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
virtual ~AnyEvent() = default;
};
template<class ObsT, bool IsConst = true>
class Event;
/**
\brief For emission of events from observables.
An observable object probably wants to emit events to notify observers that things are happening. The observers filter the events, at this time by dynamic casting (slow, I know, but it works for now. Premature optimization, etc.) A better method than dynamic casting would be to filter based on a union of bits or something. If you, the reader, want to help make this better, please contact a developer!
Say I am an observable object, and I want to emit an event. Events attach the type of object emitting them, and in fact (a refence to) the emitter itself. So if my type is `T`, I would do something like `NotifyObservers(Event<T>(*this))`. Then an Observer can filter based on a heirarchy of event types, etc.
\tparam ObsT The Observed type. When emitting an event, you pass in the type of object emitting the event, and the object itself. Then the observer can `Get` the emitting object, and do (const) stuff to it.
\see Observable, Observable::NotifyObservers, ADD_BERTINI_EVENT_TYPE, AMPPathAccumulator, AnyEvent
*/
template<class ObsT>
class Event<ObsT, true> : public AnyEvent
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
/**
\brief Constructor for an event.
\param obs The observable emitting the event to observers. Passed by const reference, this permits arbitrary `const` function calls by the observer.
*/
Event(ObsT const& obs) : current_observable_(obs)
{}
virtual ~Event() = default;
/**
\brief Get the emitting object, by `const` reference.
\return The observable who emitted the event. This permits calls of arbitrary const functions, particularly getters.
\see AMPPathAccumulator for simple example of filtering using `dynamic_cast`s
*/
ObsT const& Get() const
{return current_observable_;}
Event() = delete;
using HeldT = const ObsT&;
protected:
const ObsT& current_observable_;
};
/**
\brief For emission of events from observables.
An observable object probably wants to emit events to notify observers that things are happening. The observers filter the events, at this time by dynamic casting (slow, I know, but it works for now. Premature optimization, etc.) A better method than dynamic casting would be to filter based on a union of bits or something. If you, the reader, want to help make this better, please contact a developer!
Say I am an observable object, and I want to emit an event. Events attach the type of object emitting them, and in fact (a refence to) the emitter itself. So if my type is `T`, I would do something like `NotifyObservers(Event<T>(*this))`. Then an Observer can filter based on a heirarchy of event types, etc.
\tparam ObsT The Observed type. When emitting an event, you pass in the type of object emitting the event, and the object itself. Then the observer can `Get` the emitting object, and do (const) stuff to it.
\see Observable, Observable::NotifyObservers, ADD_BERTINI_EVENT_TYPE, AMPPathAccumulator, AnyEvent
*/
template<class ObsT>
class Event<ObsT,false> : public AnyEvent
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
/**
\brief Constructor for an event.
\param obs The observable emitting the event to observers. Passed by const reference, this permits arbitrary `const` function calls by the observer.
*/
Event(ObsT & obs) : current_observable_(obs)
{}
virtual ~Event() = default;
/**
\brief Get the emitting object, by `const` reference.
\return The observable who emitted the event. This permits calls of arbitrary const functions, particularly getters.
\see AMPPathAccumulator for simple example of filtering using `dynamic_cast`s
*/
ObsT & Get()
{return current_observable_;}
Event() = delete;
using HeldT = ObsT&;
protected:
ObsT& current_observable_;
};
template<typename ObsT>
using ConstEvent = Event<ObsT,true>;
template<typename ObsT>
using MutableEvent = Event<ObsT,false>;
/**
\brief Defines a new event type in a hierarchy
\param event_name The name of the new Event type you are making.
\param event_parenttype The name of the parent Event type in the heirarchy.
*/
#define ADD_BERTINI_EVENT_TYPE(event_name,event_parenttype) template<class ObservedT> \
class event_name : public event_parenttype<ObservedT> \
{ BOOST_TYPE_INDEX_REGISTER_CLASS \
public: \
using HeldT = typename event_parenttype<ObservedT>::HeldT; \
event_name(HeldT obs) : event_parenttype<ObservedT>(obs){} \
virtual ~event_name() = default; \
event_name() = delete; }
} //re: namespace bertini
#endif

View File

@@ -0,0 +1,72 @@
//This file is part of Bertini 2.
//
//is_template_parameter.hpp 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.
//
//is_template_parameter.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with is_template_parameter.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
//
// detail/is_template_parameter.hpp
/**
\file detail/is_template_parameter.hpp
\brief Contains the detail/is_template_parameter helper, for checking whether a type is a template parameter in a variable template
*/
#pragma once
#include "bertini2/detail/typelist.hpp"
namespace bertini {
namespace detail{
/**
Base template, which says 'no', it's not in the pack.
*/
template <typename...>
struct IsTemplateParameter {
static constexpr bool value = false;
};
/**
Specialized template, which says 'yes', if it is in the pack, by recursively expanding the pack.
*/
template <typename F, typename S, typename... T>
struct IsTemplateParameter<F, S, T...> {
static constexpr bool value =
std::is_same<F, S>::value || IsTemplateParameter<F, T...>::value;
// either it is the same as the first one in the pack, or we need to expand to the right in the pack.
};
template < typename T, typename ...Ts>
struct IsTemplateParameter<T, TypeList<Ts...>>
{
static constexpr bool value = IsTemplateParameter<T, Ts...>::value;
};
} // namespace detail
}

View File

@@ -0,0 +1,115 @@
//This file is part of Bertini 2.
//
//bertini2/detail/observable.hpp 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.
//
//bertini2/detail/observable.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/detail/observable.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
//
/**
\file bertini2/detail/observable.hpp
\brief Contains the observable base types
*/
#ifndef BERTINI_DETAIL_OBSERVABLE_HPP
#define BERTINI_DETAIL_OBSERVABLE_HPP
#include "bertini2/detail/observer.hpp"
#include "bertini2/detail/events.hpp"
namespace bertini{
/**
\brief An abstract observable type, maintaining a list of observers, who can be notified in case of Events.
Some known observable types are Tracker and Endgame.
*/
class Observable
{
public:
virtual ~Observable() = default;
/**
\brief Add an observer, to observe this observable.
*/
void AddObserver(AnyObserver& new_observer) const
{
if (find_if(begin(current_watchers_), end(current_watchers_), [&](const auto& held_obs)
{ return &held_obs.get() == &new_observer; })==end(current_watchers_))
current_watchers_.push_back(std::ref(new_observer));
}
/**
\brief Remove an observer from this observable.
*/
void RemoveObserver(AnyObserver& observer) const
{
auto new_end = std::remove_if(current_watchers_.begin(), current_watchers_.end(),
[&](const auto& held_obs)
{ return &held_obs.get() == &observer; });
current_watchers_.erase(new_end, current_watchers_.end());
// current_watchers_.erase(std::remove(current_watchers_.begin(), current_watchers_.end(), std::ref(observer)), current_watchers_.end());
}
protected:
/**
\brief Sends an Event (more particularly, AnyEvent) to all watching observers of this object.
This function could potentially be improved by filtering on the observer's desired event types, if known at compile time. This could potentially be a performance bottleneck (hopefully not!) since filtering can use `dynamic_cast`ing. One hopes this cost is overwhelmed by things like linear algebra and system evaluation.
\param e The event to emit. Its type should be derived from AnyEvent.
*/
void NotifyObservers(AnyEvent const& e) const
{
for (auto& obs : current_watchers_)
obs.get().Observe(e);
}
void NotifyObservers(AnyEvent & e) const
{
for (auto& obs : current_watchers_)
obs.get().Observe(e);
}
private:
using ObserverContainer = std::vector<std::reference_wrapper<AnyObserver>>;
mutable ObserverContainer current_watchers_;
};
} // namespace bertini
#endif

View File

@@ -0,0 +1,123 @@
//This file is part of Bertini 2.
//
//bertini2/detail/observer.hpp 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.
//
//bertini2/detail/observer.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/detail/observer.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
//
/**
\file bertini2/detail/observer.hpp
\brief Contains the observer base types.
*/
#ifndef BERTINI_DETAIL_OBSERVER_HPP
#define BERTINI_DETAIL_OBSERVER_HPP
#include <tuple>
#include <utility>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/include/for_each.hpp>
#include "bertini2/detail/events.hpp"
namespace bertini{
/**
\brief Strawman base class for Observer objects.
\see Observer
*/
class AnyObserver
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
virtual ~AnyObserver() = default;
/**
\brief Observe the observable object being observed. This is probably in response to NotifyObservers.
This virtual function must be overridden by actual observers, defining how they observe the observable they are observing, probably filtering events and doing something specific for different ones.
\param e The event which was emitted by the observed object.
*/
virtual void Observe(AnyEvent const& e) = 0;
};
/**
\brief Actual observer type, which you should derive from to extract custom information from observable types.
\tparam ObservedT The type of object the observer observes.
\tparam RetT The type of object the observer returns when it visits.
\see PrecisionAccumulator, GoryDetailLogger, MultiObserver
*/
template<class ObservedT>
class Observer : public AnyObserver
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
virtual ~Observer() = default;
};
/**
\brief A class which can glob together observer types into a new, single observer type.
If there are pre-existing observers for the object you wish to observe, rather than making one of each, and attaching each to the observable, you can make many things one.
https://frinkiac.com/?q=many%20guns%20into%20five
\tparam ObservedT The type of thing the observer types you are gluing together observe. They must all observe the same type of object.
\tparam ObserverTypes The already-existing observer types you are gluing together. You can put as many of them together as you want!
*/
template<class ObservedT, template<class> class... ObserverTypes>
class MultiObserver : public Observer<ObservedT>
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
/**
\brief Observe override which calls the overrides for the types you glued together.
\param e The emitted event which caused observation.
*/
void Observe(AnyEvent const& e) override
{
using namespace boost::fusion;
auto f = [&e](auto &obs) { obs.Observe(e); };
for_each(observers_, f);
}
std::tuple<ObserverTypes<ObservedT>...> observers_;
virtual ~MultiObserver() = default;
};
}
#endif

View File

@@ -0,0 +1,62 @@
//This file is part of Bertini 2.
//
//bertini2/detail/singleton.hpp 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.
//
//bertini2/detail/singleton.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/detail/singleton.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
/**
\file bertini2/detail/singleton.hpp
\brief Provides types and utilities for dealing with global defaults for the detail routines
*/
#pragma once
namespace bertini{
namespace detail{
/**
\brief A virtual singleton base class which can be used in a heirarchy to require a class to be singleton.
\note
This class is virtual, so make sure you mark destructors as virtual.
*/
struct Singleton {
virtual ~Singleton() = default;
private:
// mark both the default and copy constructor as private
Singleton(){}
Singleton(Singleton const&){}
};
} // namespace detail
} // namespace bertini

View File

@@ -0,0 +1,98 @@
//This file is part of Bertini 2.
//
//typelist.hpp 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.
//
//typelist.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with typelist.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
/**
\file detail/typelist.hpp
\brief Contains the detail/typelist helper type, for templated getting/setting/storage of config structs
*/
#pragma once
#include "bertini2/detail/enable_permuted_arguments.hpp"
#include "bertini2/eigen_extensions.hpp"
namespace bertini {
namespace detail {
/**
\brief A basic typelist, in the style of Modern C++ Design, but using variadic templates
To construct one, feed the types you want into the template arguments of the TypeList
*/
template <typename... Ts>
struct TypeList {
using ToTuple = std::tuple<Ts...>;
using ToTupleOfVec = std::tuple<Vec<Ts>...>;
using ToTupleOfReal = std::tuple<typename Eigen::NumTraits<Ts>::Real...>;
template <template<typename> class ContT>
using ToTupleOfCont = std::tuple<ContT<Ts>...>;
template<typename ...Rs>
static
std::tuple<Ts...> Unpermute(const Rs& ...rs)
{
return bertini::Unpermute<Ts...>(rs...);
}
};
/**
\brief Concatenate two typelists
Get resulting TypeList via something like `ListCat< TypeList<int>,TypeList<double> >::type`
*/
template <typename ...Ts>
struct ListCat {};
/**
\brief A specialization of ListCat for joining two lists
*/
template <typename ...Ts, typename ... Rs>
struct ListCat <TypeList<Ts...>, TypeList<Rs...>>
{
using type = TypeList<Ts..., Rs...>;
};
/**
\brief A specialization of ListCat for joining 3+ lists
This specialization works via recursion
*/
template <typename ...Ps, typename ... Qs, typename ... Rs>
struct ListCat <TypeList<Ps...>, TypeList<Qs...>, TypeList<Rs...>>
{
using type = TypeList<Ps..., Qs..., Rs...>;
};
}} // close namespaces

View File

@@ -0,0 +1,129 @@
//This file is part of Bertini 2.
//
//visitable.hpp 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.
//
//visitable.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with visitable.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
//
/**
\file visitable.hpp
\brief Contains the visitable base types
*/
#ifndef BERTINI_DETAIL_VISITABLE_HPP
#define BERTINI_DETAIL_VISITABLE_HPP
#include "bertini2/detail/visitor.hpp"
#include "bertini2/detail/events.hpp"
namespace bertini{
namespace policy{
/**
\brief A policy for what to do when a visited type is encoutered by a visitor it doesn't know.
Defines the default behaviour when an unknown visitor is encountered during visitation.
Assumes the return type is default constructible.
*/
template<class VisitedT, typename RetT>
struct DefaultConstruct
{
static RetT OnUnknownVisitor(VisitedT&a, VisitorBase&) // VisitorBase is inherited from using CRTP -- it's not a template parameter to this function, so its typeid name is useless.
{
std::cout << "unknown visitor: " << a << " of type " << typeid(VisitedT).name() << ". Make sure you've added it in all three places! two in the class definition (type inheritance listing as visiting, and virtual function declaration), and one in cpp source (function definition)." << std::endl;
return VisitedT();
}
};
template<class VisitedT, typename RetT>
struct RaiseExceptionWithTypeNamesInMessage
{
static RetT OnUnknownVisitor(VisitedT&a, VisitorBase&)
{
std::stringstream err_msg;
err_msg << "unknown visitor: " << a << " of type " << typeid(VisitedT).name() << ". Make sure you've added it in all three places! two in the class definition (type inheritance listing as visiting, and virtual function declaration), and one in cpp source (function definition)." << std::endl;
throw std::runtime_error(err_msg.str());
}
};
/**
The default policy for what to do when a visitable is visited by an unknown visitor.
*/
template<class VisitedT, typename RetT>
using DefaultCatchAll = RaiseExceptionWithTypeNamesInMessage<VisitedT, RetT>;
} // namespace policy
/**
\brief The base class for visitable types.
Implemented based on Alexandrescu, 2001, and Hythem Sidky's SAPHRON package, with his permission.
\see BERTINI_DEFAULT_VISITABLE
*/
template< typename RetT = void, template<class,class> class CatchAll = policy::DefaultCatchAll>
class VisitableBase
{
public:
typedef RetT VisitReturnType;
virtual ~VisitableBase() = default;
virtual VisitReturnType Accept(VisitorBase&) = 0; // the implementation will either be provided by a macro, or by hand, for each class which is visitable.
protected:
/**
\brief Abstract method for how to accept a visitor.
This function simply Forwards to the Visit method of the visitor, if the visitor's type is known. If known, invokes the behaviour defined by the CatchAll template parameter.
\tparam T The type of the visited object. Should be inferred by the compiler.
\param visited The visited visitable object.
\param guest The visiting object.
*/
template<typename T>
static
VisitReturnType AcceptBase(T& visited, VisitorBase& guest)
{
if (auto p = dynamic_cast<Visitor<T>*>(&guest))
return p->Visit(visited);
else
return CatchAll<T,RetT>::OnUnknownVisitor(visited, guest);
}
};
/**
\brief macro for classes which want default Accept implementation, having nothing fancy to do when accepting.
*/
#define BERTINI_DEFAULT_VISITABLE() \
virtual VisitReturnType Accept(VisitorBase& guest) override \
{ return AcceptBase(*this, guest); }
} // namespace bertini
#endif

View File

@@ -0,0 +1,73 @@
//This file is part of Bertini 2.
//
//visitor.hpp 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.
//
//visitor.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with visitor.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
//
/**
\file visitor.hpp
\brief Contains the visitor base types.
*/
#ifndef BERTINI_DETAIL_VISITOR_HPP
#define BERTINI_DETAIL_VISITOR_HPP
#include <boost/type_index.hpp>
namespace bertini{
/**
\brief A strawman class for implementing the visitor pattern.
Deliberately empty, the non-base visitors must derive from it.
\see Visitor, Observer, AnyObserver, MultiObserver
*/
class VisitorBase
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
virtual ~VisitorBase() = default;
};
/**
\brief The first non-trivial visitor class.
Derive from this when creating new visitor types.
\tparam VisitedT The type of object the visitor visits.
\tparam RetT The type of object to be returned when visiting. Default is `void`.
*/
template<class VisitedT, typename RetT = void>
class Visitor
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
typedef RetT ReturnType;
virtual ReturnType Visit(VisitedT const &) = 0;
virtual ~Visitor() = default;
};
}
#endif

View File

@@ -0,0 +1,121 @@
//This file is part of Bertini 2.
//
//bertini2/double_extensions.hpp 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.
//
//bertini2/double_extensions.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/double_extensions.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2017 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, University of Wisconsin Eau Claire
/**
\file bertini2/double_extensions.hpp
\brief Provides bertini extensions to the double and complex<double> types.
*/
#ifndef BERTINI_DOUBLE_EXTENSIONS_HPP
#define BERTINI_DOUBLE_EXTENSIONS_HPP
#pragma once
#include <random>
#include <complex>
namespace bertini{
using dbl = std::complex<double>;
using dbl_complex = std::complex<double>;
/**
\brief Overload * for unsigned * complex<double>
*/
inline
std::complex<double> operator*(unsigned i, std::complex<double> z)
{
z*=i;
return z;
}
/**
an overload of isnan, for std::complex<double>
*/
inline
bool isnan(std::complex<double> const& z)
{
using std::isnan;
return isnan(z.real()) || isnan(z.imag());
}
/**
\brief Gets you a random real number between -1 and 1, fwiw
*/
inline
double RandReal()
{
static std::default_random_engine generator;
static std::uniform_real_distribution<double> distribution(-1.0,1.0);
return distribution(generator);
}
namespace{
using dbl = std::complex<double>;
}
/**
Compute +,- integral powers of a std::complex<double> number.
This function recursively calls itself if the power is negative, by computing the power on the inverse.
\note This overload was removed from C++ in C++11, for some insane reason. Here it is, back in black.
*/
inline dbl pow(const dbl & z, int power)
{
if (power < 0) {
return pow(1./z, -power);
}
else if (power==0)
return dbl(1,0);
else if(power==1)
return z;
else if(power==2)
return z*z;
else if(power==3)
return z*z*z;
else
{
unsigned int p(power);
dbl result(1,0), z_to_the_current_power_of_two = z;
// have copy of p in memory, can freely modify it.
do {
if ( (p & 1) == 1 ) { // get the lowest bit of the number
result *= z_to_the_current_power_of_two;
}
z_to_the_current_power_of_two *= z_to_the_current_power_of_two; // square z_to_the_current_power_of_two
} while (p >>= 1);
return result;
}
}
} // namespace bertini
#endif // include guard

View File

@@ -0,0 +1,597 @@
//This file is part of Bertini 2.
//
//eigen_extensions.hpp 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.
//
//eigen_extensions.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with eigen_extensions.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, University of Wisconsin Eau Claire
/**
\file eigen_extensions.hpp
\brief Bertini extensions of the Eigen linear algebra library.
*/
#ifndef BERTINI_EIGEN_EXTENSIONS_HPP
#define BERTINI_EIGEN_EXTENSIONS_HPP
#include "bertini2/num_traits.hpp"
#include <boost/serialization/complex.hpp>
#include <boost/serialization/array.hpp>
#include <boost/serialization/split_member.hpp>
#define EIGEN_DENSEBASE_PLUGIN "bertini2/eigen_serialization_addon.hpp"
#include <Eigen/Core>
namespace {
using mpfr_real = bertini::mpfr_float;
using mpfr_complex = bertini::mpfr_complex;
}
namespace Eigen {
template<> struct NumTraits<mpfr_real> : GenericNumTraits<mpfr_real> // permits to get the epsilon, dummy_precision, lowest, highest functions
{
typedef mpfr_real Real;
typedef mpfr_real NonInteger;
typedef mpfr_real Nested;
enum {
IsComplex = 0,
IsInteger = 0,
IsSigned = 1,
RequireInitialization = 1, // yes, require initialization, otherwise get crashes
ReadCost = 20,
AddCost = 30,
MulCost = 40
};
inline static Real highest() {
return (mpfr_real(1) - epsilon()) * pow(mpfr_real(2),mpfr_get_emax()-1);//);//DefaultPrecision());
}
inline static Real lowest() {
return -highest();
}
inline static Real dummy_precision()
{
using bertini::DefaultPrecision;
return pow( mpfr_real(10),-int(DefaultPrecision()-3));
}
inline static Real epsilon()
{
using bertini::DefaultPrecision;
return pow(mpfr_real(10),-int(DefaultPrecision()));
}
static inline int digits10()
{
return bertini::DefaultPrecision();
// return internal::default_digits10_impl<T>::run();
}
//http://www.manpagez.com/info/mpfr/mpfr-2.3.2/mpfr_31.php
};
template<typename Expr1,typename Expr2, typename Expr3>
struct NumTraits<
boost::multiprecision::detail::expression<Expr1,
Expr2, Expr3, void, void>
> : NumTraits<mpfr_real> // permits to get the epsilon, dummy_precision, lowest, highest functions
{
typedef mpfr_real Real;
typedef mpfr_real NonInteger;
typedef mpfr_real Nested;
//http://www.manpagez.com/info/mpfr/mpfr-2.3.2/mpfr_31.php
};
/**
\brief This templated struct permits us to use the mpfr_complex type in Eigen matrices.
Provides methods to get the epsilon, dummy_precision, lowest, highest functions, largely by inheritance from the NumTraits<mpfr_real> contained in mpfr_extensions.
*/
template<> struct NumTraits<mpfr_complex> : NumTraits<mpfr_real>
{
typedef mpfr_real Real;
typedef mpfr_real NonInteger;
typedef mpfr_complex Nested;// Nested;
enum {
IsComplex = 1,
IsInteger = 0,
IsSigned = 1,
RequireInitialization = 1, // yes, require initialization, otherwise get crashes
ReadCost = 2 * NumTraits<Real>::ReadCost,
AddCost = 2 * NumTraits<Real>::AddCost,
MulCost = 4 * NumTraits<Real>::MulCost + 2 * NumTraits<Real>::AddCost
};
};
namespace internal {
template<>
struct abs2_impl<mpfr_complex>
{
static inline mpfr_real run(const mpfr_complex& x)
{
return real(x)*real(x) + imag(x)*imag(x);
}
};
template<> inline mpfr_complex random<mpfr_complex>()
{
return bertini::multiprecision::rand();
}
template<> inline mpfr_complex random<mpfr_complex>(const mpfr_complex& a, const mpfr_complex& b)
{
return a + (b-a) * random<mpfr_complex>();
}
template<>
struct conj_helper<mpfr_complex, mpfr_complex, false, true>
{
typedef mpfr_complex Scalar;
EIGEN_STRONG_INLINE Scalar pmadd(const Scalar& x, const Scalar& y, const Scalar& c) const
{ return c + pmul(x,y); }
EIGEN_STRONG_INLINE Scalar pmul(const Scalar& x, const Scalar& y) const
{ return Scalar(real(x)*real(y) + imag(x)*imag(y), imag(x)*real(y) - real(x)*imag(y)); }
};
template<>
struct conj_helper<mpfr_complex, mpfr_complex, true, false>
{
typedef mpfr_complex Scalar;
EIGEN_STRONG_INLINE Scalar pmadd(const Scalar& x, const Scalar& y, const Scalar& c) const
{ return c + pmul(x,y); }
EIGEN_STRONG_INLINE Scalar pmul(const Scalar& x, const Scalar& y) const
{ return Scalar(real(x)*real(y) + imag(x)*imag(y), real(x)*imag(y) - imag(x)*real(y)); }
};
// see https://forum.kde.org/viewtopic.php?f=74&t=111176
//int
template<>
struct scalar_product_traits<int,mpfr_complex>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
template<>
struct scalar_product_traits<mpfr_complex, int>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
//long
template<>
struct scalar_product_traits<long,mpfr_complex>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
template<>
struct scalar_product_traits<mpfr_complex, long>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
//long long
template<>
struct scalar_product_traits<long long,mpfr_complex>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
template<>
struct scalar_product_traits<mpfr_complex, long long>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
//mpfr_real
template<>
struct scalar_product_traits<mpfr_real,mpfr_complex>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
template<>
struct scalar_product_traits<mpfr_complex, mpfr_real>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
//mpz_int
template<>
struct scalar_product_traits<bertini::mpz_int,mpfr_complex>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
template<>
struct scalar_product_traits<mpfr_complex, bertini::mpz_int>
{
enum { Defined = 1 };
typedef mpfr_complex ReturnType;
};
} // re: namespace internal
} // re: namespace Eigen
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <Eigen/Eigenvalues>
#include <Eigen/SVD>
#include <Eigen/Dense>
namespace bertini {
template<typename NumType> using Vec = Eigen::Matrix<NumType, Eigen::Dynamic, 1>;
template<typename NumType> using Mat = Eigen::Matrix<NumType, Eigen::Dynamic, Eigen::Dynamic>;
/**
\brief Checks whether the number of rows and columns are either 0
*/
template<typename Derived>
inline
bool IsEmpty(Eigen::MatrixBase<Derived> const & v)
{
return (v.rows()==0) || (v.cols()==0);
}
/**
\brief Get the precision of an Eigen object. If the object is empty, it's the precision of a default-constructed Scalar. If it actually has content, then it's the precision of the first element.
If you require that the object be of uniform precision when you check, use PrecisionRequireUniform
*/
template<typename Derived>
inline
unsigned Precision(Eigen::MatrixBase<Derived> const & v)
{
if (IsEmpty(v))
throw std::runtime_error("getting precision of empty object");
return Precision(v(0,0));
}
/**
\brief Query the precision of an Eigen object, requiring it to be non-empty, and of uniform precision
\throw runtime_error if not uniform precision
Dies in an Eigen assert if empty (assuming you didn't disable these)
*/
template<typename Derived>
unsigned PrecisionRequireUniform(Eigen::MatrixBase<Derived> const & v)
{
const auto a = Precision(v(0,0));
for (int ii=0; ii<v.cols(); ++ii)
for (int jj=0; jj<v.rows(); ++jj)
{
if (a!=Precision(v(jj,ii)))
{
std::stringstream ss;
ss << "non-uniform precision in object! (" << a << "!=" << Precision(v(jj,ii)) << ") at position " << jj << "," << ii;
throw std::runtime_error(ss.str());
}
}
return a;
}
/**
\brief Set the precision of an Eigen object.
\param v the matrix to change
\param prec the new precision
*/
template<typename Derived>
void Precision(Eigen::MatrixBase<Derived> & v, unsigned prec)
{
using bertini::Precision;
for (int ii=0; ii<v.cols(); ++ii)
for (int jj=0; jj<v.rows(); ++jj)
Precision(v(jj,ii),prec);
}
/**
Test a numbers being very small.
Compares the number against machine epsilon (or software epsilon if a multiple precision type), times 100.
\note Machine epsilon for doubles is about 1e-16, for mpfr_real, it's 10^-current precision.
\param testme The number to test
\return true, if the number is very small. False otherwise.
*/
template<typename T>
inline
bool IsSmallValue(T const& testme)
{
using std::abs;
return abs(testme) <= Eigen::NumTraits<T>::epsilon()*100;
}
/**
\brief Check whether two values are very close to each other.
\e The tolerance for being close
See \url http://www.boost.org/doc/libs/1_34_0/libs/test/doc/components/test_tools/floating_point_comparison.html, for example.
*/
template<typename T>
inline
bool IsSymmRelDiffSmall(T const& a, T const& b, typename Eigen::NumTraits<T>::Real const& e)
{
using std::abs;
if (a==b)
return true;
typename Eigen::NumTraits<T>::Real c = abs(a-b);
return (c/abs(a) <= e) || (c/abs(b) <= e) ;
}
/**
Test two numbers for having large ratio.
The basis for comparison is Eigen's fuzzy precision, Eigen::NumTraits<T>::dummy_precision();
\note For doubles, the threshold is 1e-12, for mpfr_real is 1e3*current precision.
\param numerator The numerator for the ratio.
\param denomenator The denomenator for the ratio.
\return true, if the ratio is very large, false otherwise
*/
template<typename T>
inline
bool IsLargeChange(T const& numerator, T const& denomenator)
{
static_assert(!Eigen::NumTraits<T>::IsInteger, "IsLargeChange cannot be used safely on non-integral types");
using std::abs;
return abs(numerator/denomenator) >= 1/Eigen::NumTraits<T>::dummy_precision();
}
enum class MatrixSuccessCode
{
Success,
LargeChange,
SmallValue
};
/**
\brief Check the diagonal elements of an LU decomposition for small values and large ratios.
\return Success if things are ok. LargeChange or SmallValue if one is found.
This function requires a square non-empty matrix.
\tparam Derived Matrix type from Eigen.
*/
template <typename Derived>
MatrixSuccessCode LUPartialPivotDecompositionSuccessful(Eigen::MatrixBase<Derived> const& LU)
{
#ifndef BERTINI_DISABLE_ASSERTS
assert(LU.rows()==LU.cols() && "non-square matrix in LUPartialPivotDecompositionSuccessful");
assert(LU.rows()>0 && "empty matrix in LUPartialPivotDecompositionSuccessful");
#endif
// this loop won't test entry (0,0). it's tested separately after.
for (unsigned int ii = LU.rows()-1; ii > 0; ii--)
{
if (IsSmallValue(LU(ii,ii)))
{
return MatrixSuccessCode::SmallValue;
}
if (IsLargeChange(LU(ii-1,ii-1),LU(ii,ii)))
{
return MatrixSuccessCode::LargeChange;
}
}
// this line is the reason for the above assert on non-empty matrix.
if (IsSmallValue(LU(0,0)))
{
return MatrixSuccessCode::SmallValue;
}
return MatrixSuccessCode::Success;
}
/**
\brief Make a Kahan matrix with a given number type.
*/
template <typename NumberType>
Eigen::Matrix<NumberType, Eigen::Dynamic, Eigen::Dynamic> KahanMatrix(unsigned int mat_size, NumberType c)
{
using std::sqrt;
NumberType s, scale(1.0);
s = sqrt( (NumberType(1.0)-c) * (NumberType(1.0)+c) );
Eigen::Matrix<NumberType, Eigen::Dynamic, Eigen::Dynamic> A(mat_size,mat_size);
for (unsigned int ii=0; ii<mat_size; ii++) {
for (unsigned int jj=0; jj<ii; jj++) {
A(ii,jj) = NumberType(0.0);
}
for (unsigned int jj=ii; jj<mat_size; jj++) {
A(ii,jj) = -c * NumberType(1.0);
}
}
for (unsigned int ii=0; ii<mat_size; ii++) {
A(ii,ii) += NumberType(1)+c;
}
for (unsigned int jj=0; jj<mat_size; jj++){
for (unsigned int kk=0;kk<mat_size;kk++){
A(jj,kk) *= scale;
}
scale *= s;
}
for (unsigned int jj=0;jj<mat_size;jj++){
for (unsigned int kk=0;kk<mat_size;kk++){
A(kk,jj)/= NumberType(jj) + NumberType(1);
}
}
return A;
}
/**
\brief Make a random matrix of units (numbers with norm 1).
\return The random matrix of units.
\param rows The number of rows.
\param cols The number of columns.
\tparam NumberType the type of number to fill the matrix with.
*/
template <typename NumberType>
inline
Mat<NumberType> RandomOfUnits(uint rows, uint cols)
{
return Mat<NumberType>(rows,cols).unaryExpr([](NumberType const& x) { return RandomUnit<NumberType>(); });
}
/**
\brief Make a random vector of units (numbers with norm 1).
\return The random vector of units.
\param size The length of the vector.
\tparam NumberType the type of number to fill the vector with.
*/
template <typename NumberType>
inline
Vec<NumberType> RandomOfUnits(uint size)
{
return Vec<NumberType>(size).unaryExpr([](NumberType const& x) { return RandomUnit<NumberType>(); });
}
}
// // the following code comes from
// // https://stackoverflow.com/questions/18382457/eigen-and-boostserialize
// // and adds support for serialization of Eigen types
// //
// // question asked by user Gabriel and answered by Shmuel Levine
// // answer code repeated here verbatim.
// // please update this comment if this code is changed,
// // and post the modifications to the above referenced post on SO.
// namespace boost{
// namespace serialization{
// template< class Archive,
// class S,
// int Rows_,
// int Cols_,
// int Ops_,
// int MaxRows_,
// int MaxCols_>
// inline void save(
// Archive & ar,
// const Eigen::Matrix<S, Rows_, Cols_, Ops_, MaxRows_, MaxCols_> & g,
// const unsigned int version)
// {
// int rows = g.rows();
// int cols = g.cols();
// ar & rows;
// ar & cols;
// ar & boost::serialization::make_array(g.data(), rows * cols);
// }
// template< class Archive,
// class S,
// int Rows_,
// int Cols_,
// int Ops_,
// int MaxRows_,
// int MaxCols_>
// inline void load(
// Archive & ar,
// Eigen::Matrix<S, Rows_, Cols_, Ops_, MaxRows_, MaxCols_> & g,
// const unsigned int version)
// {
// int rows, cols;
// ar & rows;
// ar & cols;
// g.resize(rows, cols);
// ar & boost::serialization::make_array(g.data(), rows * cols);
// }
// template< class Archive,
// class S,
// int Rows_,
// int Cols_,
// int Ops_,
// int MaxRows_,
// int MaxCols_>
// inline void serialize(
// Archive & ar,
// Eigen::Matrix<S, Rows_, Cols_, Ops_, MaxRows_, MaxCols_> & g,
// const unsigned int version)
// {
// split_free(ar, g, version);
// }
// } // namespace serialization
// } // namespace boost
#endif

View File

@@ -0,0 +1,55 @@
// the following code comes from
// https://stackoverflow.com/questions/18382457/eigen-and-boostserialize
// and adds support for serialization of Eigen types
//
// question asked by user Gabriel and answered by iNFINITEi
//
// answer code repeated here verbatim.
// please update this comment if this code is changed,
// and post the modifications to the above referenced post on SO.
/**
* @file eigen_serialization_addon.hpp
*/
#ifndef EIGEN_SERIALIZATION_ADDON_HPP
#define EIGEN_SERIALIZATION_ADDON_HPP
#pragma once
friend class boost::serialization::access;
template<class Archive>
void save(Archive & ar, const unsigned int version) const {
derived().eval();
const Eigen::Index rows = derived().rows(), cols = derived().cols();
ar & rows;
ar & cols;
for (Index j = 0; j < cols; ++j )
for (Index i = 0; i < rows; ++i )
ar & derived().coeff(i, j);
}
template<class Archive>
void load(Archive & ar, const unsigned int version) {
Eigen::Index rows, cols;
ar & rows;
ar & cols;
if (rows != derived().rows() || cols != derived().cols() )
derived().resize(rows, cols);
ar & boost::serialization::make_array(derived().data(), derived().size());
}
template<class Archive>
void serialize(Archive & ar, const unsigned int file_version) {
boost::serialization::split_member(ar, *this, file_version);
}
#endif // EIGEN_SERIALIZATION_ADDON_HPP

View File

@@ -0,0 +1,42 @@
//This file is part of Bertini 2.
//
//bertini2/endgames.hpp 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.
//
//bertini2/endgames.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/endgames.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2017-2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of notre dame
/**
\file bertini2/endgames.hpp
\brief Collects the various header files which define the Bertini2 endgames.
*/
#pragma once
#include "bertini2/endgames/amp_endgame.hpp"
#include "bertini2/endgames/fixed_prec_endgame.hpp"
#include "bertini2/endgames/powerseries.hpp"
#include "bertini2/endgames/cauchy.hpp"
#include "bertini2/endgames/observers.hpp"

View File

@@ -0,0 +1,169 @@
//This file is part of Bertini 2.
//
//amp_endgame.hpp 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.
//
//amp_endgame.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with amp_endgame.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
// Tim Hodges, Colorado State University
#pragma once
/**
\file base_endgame.hpp
\brief Contains parent class, Endgame, the parent class for all endgames.
*/
#include "bertini2/trackers/amp_tracker.hpp"
#include "bertini2/trackers/adaptive_precision_utilities.hpp"
#include "bertini2/endgames/config.hpp"
#include "bertini2/endgames/prec_base.hpp"
#include "bertini2/endgames/events.hpp"
#include "bertini2/detail/observable.hpp"
namespace bertini{ namespace endgame {
/**
\brief Specifies some necessaries for AMP style endgame implementations, which differ from the fixed precision ones.
*/
class AMPEndgame : public virtual EndgamePrecPolicyBase<tracking::AMPTracker>
{
public:
using TrackerT = tracking::AMPTracker;
using EmitterType = AMPEndgame;
template<typename... T>
static
unsigned EnsureAtUniformPrecision(T& ...args)
{
return tracking::adaptive::EnsureAtUniformPrecision(args...);
}
static
void EnsureAtPrecision(double & obj, unsigned prec)
{
if (prec!=DoublePrecision())
throw std::runtime_error("attempting to adjust precision of double to non-double precision");
}
static
void EnsureAtPrecision(std::complex<double> & obj, unsigned prec)
{
if (prec!=DoublePrecision())
throw std::runtime_error("attempting to adjust precision of std::complex<double> to non-double precision");
}
static
void EnsureAtPrecision(mpfr_float & obj, unsigned prec)
{
using bertini::Precision;
Precision(obj,prec);
}
static
void EnsureAtPrecision(mpfr_complex & obj, unsigned prec)
{
using bertini::Precision;
Precision(obj,prec);
}
SuccessCode RefineSampleImpl(Vec<mpfr_complex> & result, Vec<mpfr_complex> const& current_sample, mpfr_complex const& current_time, NumErrorT tol, unsigned max_iterations) const
{
using bertini::Precision;
assert(Precision(current_time)==Precision(current_sample) && "precision of sample and time to be refined in AMP endgame must match");
using RT = mpfr_float;
using std::max;
auto& TR = this->GetTracker();
TR.ChangePrecision(Precision(current_time));
auto refinement_success = this->GetTracker().Refine(result,current_sample,current_time,
tol,
max_iterations);
if (refinement_success==SuccessCode::HigherPrecisionNecessary ||
refinement_success==SuccessCode::FailedToConverge)
{
using bertini::Precision;
auto prev_precision = DefaultPrecision();
auto higher_precision = max(prev_precision,LowestMultiplePrecision())+ PrecisionIncrement();
DefaultPrecision(higher_precision);
this->GetTracker().ChangePrecision(higher_precision);
NotifyObservers(PrecisionChanged<EmitterType>(*this, prev_precision, higher_precision));
auto next_sample_higher_prec = current_sample;
Precision(next_sample_higher_prec, higher_precision);
auto result_higher_prec = Vec<mpfr_complex>(current_sample.size());
auto time_higher_precision = current_time;
Precision(time_higher_precision,higher_precision);
assert(time_higher_precision.precision()==DefaultPrecision());
refinement_success = this->GetTracker().Refine(result_higher_prec,
next_sample_higher_prec,
time_higher_precision,
tol,
max_iterations);
Precision(result, higher_precision);
result = result_higher_prec;
assert(Precision(result)==DefaultPrecision());
}
return refinement_success;
}
explicit
AMPEndgame(TrackerT const& new_tracker) : EndgamePrecPolicyBase<TrackerT>(new_tracker)
{}
virtual ~AMPEndgame() = default;
}; // re: class AMPEndgame
template<>
struct EGPrecSelector<tracking::AMPTracker>
{
using type = AMPEndgame;
};
} } // end namespaces

View File

@@ -0,0 +1,381 @@
//This file is part of Bertini 2.
//
//base_endgame.hpp 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.
//
//base_endgame.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with base_endgame.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
// Tim Hodges, Colorado State University
#ifndef BERTINI_BASE_ENDGAME_HPP
#define BERTINI_BASE_ENDGAME_HPP
#pragma once
/**
\file base_endgame.hpp
\brief Contains base class, Endgame.
*/
#include <iostream>
#include <typeinfo>
#include "bertini2/mpfr_complex.hpp"
#include "bertini2/system/system.hpp"
#include "bertini2/detail/enable_permuted_arguments.hpp"
#include "bertini2/trackers/config.hpp"
#include "bertini2/endgames/config.hpp"
#include "bertini2/endgames/interpolation.hpp"
#include "bertini2/endgames/events.hpp"
#include "bertini2/logging.hpp"
#include "bertini2/detail/configured.hpp"
namespace bertini{ namespace endgame {
/**
\class Endgame
\brief Base endgame class for all endgames offered in Bertini2.
\see PowerSeriesEndgame
\see CauchyEndgame
## Using an endgame
Endgames in Bertini2 are the engine for finishing homotopy continuation where we may encounter singular solutions.
The path is implicitly described by the system being tracked.
## Purpose
Since the Bertini Endgames have common functionality, and we want to be able to call arbitrary algorithms using and tracker type, we use inheritance. That is, there is common functionality in all endgames, such as
ComputeInitialSamples
Also, there are settings that will be kept at this level to not duplicate code.
## Creating a new endgame type
To create a new endgame type, inherit from this class.
*/
template<class FlavorT, class PrecT>
class EndgameBase :
public detail::Configured< typename AlgoTraits<FlavorT>::NeededConfigs >,
public PrecT,
public virtual Observable
{
public:
using TrackerType = typename PrecT::TrackerType;
using BaseComplexType = typename tracking::TrackerTraits<TrackerType>::BaseComplexType;
using BaseRealType = typename tracking::TrackerTraits<TrackerType>::BaseRealType;
using EmitterType = FlavorT;
protected:
using BCT = BaseComplexType;
using BRT = BaseRealType;
using Configured = detail::Configured< typename AlgoTraits<FlavorT>::NeededConfigs >;
using Configs = typename AlgoTraits<FlavorT>::NeededConfigs;
using ConfigsAsTuple = typename Configs::ToTuple;
// a list of all the needed arithemtic types (complex for complex trackers)
using NeededTypes = detail::TypeList<BCT>;
using TupOfVec = typename NeededTypes::ToTupleOfVec;
using TupOfReal = typename NeededTypes::ToTupleOfReal;
using TupleOfTimes = typename NeededTypes::template ToTupleOfCont<TimeCont>;
using TupleOfSamps = typename NeededTypes::template ToTupleOfCont<SampCont>;
// universal endgame state variables
mutable Vec<BCT> final_approximation_;
mutable Vec<BCT> previous_approximation_;
mutable unsigned int cycle_number_ = 0;
mutable NumErrorT approximate_error_;
/**
\brief convert the base endgame into the derived type.
This enables the CRPT as used by the endgames
*/
const FlavorT& AsFlavor() const
{
return dynamic_cast<const FlavorT&>(*this);
}
/**
\brief Non-const version of AsFlavor
*/
FlavorT& AsFlavor()
{
return dynamic_cast<FlavorT&>(*this);
}
public:
/**
\brief The main function for running an endgame, from time to time, from a given point to a possibly singular solution.
*/
SuccessCode Run(const BCT & start_time, const Vec<BCT> & start_point, BCT const& target_time)
{
return this->AsFlavor().RunImpl(start_time, start_point, target_time);
}
/**
\brief Run the endgame, shooting for default time of t=0.
\see Run
*/
SuccessCode Run(BCT const& start_time, Vec<BCT> const& start_point)
{
return Run(start_time, start_point, static_cast<BCT>(0));
}
template<typename CT>
SuccessCode RefineAllSamples(SampCont<CT> & samples, TimeCont<CT> & times)
{
for (size_t ii=0; ii<samples.size(); ++ii)
{
auto refine_success = this->RefineSample(samples[ii], samples[ii], times[ii],
this->FinalTolerance() * this->EndgameSettings().sample_point_refinement_factor,
this->EndgameSettings().max_num_newton_iterations);
if (refine_success != SuccessCode::Success)
{
// BOOST_LOG_TRIVIAL(severity_level::trace) << "refining failed, code " << int(refine_success);
return refine_success;
}
NotifyObservers(SampleRefined<EmitterType>(AsFlavor()));
}
if (tracking::TrackerTraits<TrackerType>::IsAdaptivePrec) // known at compile time
{
auto max_precision = this->EnsureAtUniformPrecision(times, samples);
this->GetSystem().precision(max_precision);
}
return SuccessCode::Success;
}
/**
A function passed off to the precision-specific endgame part
*/
SuccessCode RefineSample(Vec<BCT> & result, Vec<BCT> const& current_sample, BCT const& current_time, NumErrorT tol, unsigned max_iterations) const
{
return this->RefineSampleImpl(result, current_sample, current_time, tol, max_iterations);
}
void ChangePrecision(unsigned p)
{
AsFlavor().ChangePrecision(p);
PrecT::ChangePrecision(p);
ChangePrecision(this->final_approximation_,p);
ChangePrecision(this->previous_approximation_,p);
}
/**
\brief This function is inferior to the templated Get<ConfigT> function provided
*/
inline
const auto & EndgameSettings() const
{
return Configured::template Get<EndgameConfig>();
}
inline
const auto & SecuritySettings() const
{
return this->template Get<SecurityConfig>();
}
explicit EndgameBase(TrackerType const& tr, const ConfigsAsTuple& settings ) :
Configured( settings ), PrecT(tr), EndgamePrecPolicyBase<TrackerType>(tr)
{}
template< typename... Ts >
explicit
EndgameBase(TrackerType const& tr, const Ts&... ts ) : EndgameBase(tr, Configs::Unpermute( ts... ) )
{}
inline unsigned CycleNumber() const { return cycle_number_;}
inline void CycleNumber(unsigned c) { cycle_number_ = c;}
inline void IncrementCycleNumber(unsigned inc) { cycle_number_ += inc;}
/**
\brief Get the final tolerance to which we are tracking the solution.
*/
inline
const auto& FinalTolerance() const
{
return this->template Get<EndgameConfig>().final_tolerance;
}
/**
\brief Setter for the final tolerance.
*/
inline
void SetFinalTolerance(BRT const& ft){this->template Get<EndgameConfig>().final_tolerance = ft;}
/**
\brief Get the most-recent approximation
*/
template<typename CT>
inline
const Vec<CT>& FinalApproximation() const
{
return final_approximation_;
}
/**
\brief Get the second-most-recent approximation
*/
template<typename CT>
inline
const Vec<CT>& PreviousApproximation() const
{
return previous_approximation_;
}
/**
\brief Get the most recent accuracy estimate
*/
inline
NumErrorT ApproximateError() const
{
return approximate_error_;
}
/**
Get the latest time at which a point on the path was computed
*/
inline
const BCT& LatestTime() const
{
return AsFlavor().LatestTimeImpl();
}
// /**
// \brief Get the system being tracked on, which is referred to by the tracker.
// */
// inline
// const System& GetSystem() const
// {
// return GetTracker().GetSystem();
// }
/**
\brief Populates time and space samples so that we are ready to start the endgame.
## Input
start_time: is the time when we start the endgame process usually this is .1
x_endgame_start: is the space value at start_time
times: a deque of time values. These values will be templated to be CT
samples: a deque of sample values that are in correspondence with the values in times. These values will be vectors with entries of CT.
## Output
SuccessCode indicating whether tracking to all samples was successful.
## Details
The first sample will be (x_endgame_start) and the first time is start_time.
From there we do a geometric progression using the sample factor (which by default is 1/2).
Hence, next_time = start_time * sample_factor.
We track then to the next_time and construct the next_sample.
\param start_time The time value at which we start the endgame.
\param target_time The time value that we are trying to find a solution to.
\param x_endgame_start The current space point at start_time.
\param times A deque that will hold all the time values of the samples we are going to use to start the endgame.
\param samples a deque that will hold all the samples corresponding to the time values in times.
\tparam CT The complex number type.
*/
template<typename CT>
SuccessCode ComputeInitialSamples(const CT & start_time,const CT & target_time, const Vec<CT> & x_endgame_start, TimeCont<CT> & times, SampCont<CT> & samples) // passed by reference to allow times to be filled as well.
{
using RT = typename Eigen::NumTraits<CT>::Real;
assert(this->template Get<EndgameConfig>().num_sample_points>0 && "number of sample points must be positive");
if (tracking::TrackerTraits<TrackerType>::IsAdaptivePrec)
{
assert(Precision(start_time)==Precision(x_endgame_start) && "Computing initial samples requires input time and space with uniform precision");
}
samples.clear();
times.clear();
samples.push_back(x_endgame_start);
times.push_back(start_time);
auto num_vars = this->GetSystem().NumVariables();
//start at 1, because the input point is the 0th element.
for(int ii=1; ii < this->template Get<EndgameConfig>().num_sample_points; ++ii)
{
times.emplace_back((times[ii-1] + target_time) * RT(this->template Get<EndgameConfig>().sample_factor)); // next time is a point between the previous time and target time.
samples.emplace_back(Vec<CT>(num_vars)); // sample_factor gives us some point between the two, usually the midpoint.
auto tracking_success = this->GetTracker().TrackPath(samples[ii],times[ii-1],times[ii],samples[ii-1]);
this->EnsureAtPrecision(times[ii],Precision(samples[ii]));
if (tracking_success!=SuccessCode::Success)
return tracking_success;
}
return SuccessCode::Success;
}
virtual ~EndgameBase() = default;
};
} }// end namespaces bertini
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,184 @@
//This file is part of Bertini 2.
//
//include/bertini2/endgames/config.hpp 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.
//
//include/bertini2/endgames/config.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with include/bertini2/endgames/config.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015-2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
/**
\file include/bertini2/endgames/config.hpp
\brief Configs and settings for endgames.
*/
#pragma once
#include "bertini2/detail/typelist.hpp"
#include "bertini2/common/config.hpp"
namespace bertini{ namespace endgame{
// // some forward declarations
// base
template<class FlavorT, class PrecT>
class EndgameBase;
// flavors
template<typename PrecT>
class PowerSeriesEndgame;
template<typename PrecT>
class CauchyEndgame;
// precision types
template<typename TrackerT>
class FixedPrecEndgame;
class AMPEndgame;
// end forward declarations
/**
Base empty class
*/
template <typename TrackerT>
struct EGPrecSelector;
// specialize this in the specific files it goes in, please
/**
\brief Facilitates lookup of required endgame type based on tracker type
Your current choices are PSEG or Cauchy.
To get the Power Series Endgame for Adaptive Precision Tracker, use the following example code:
\code
using EGT = EndgameSelector<AMPTracker>::PSEG
\endcode
\tparam TrackerT The type of tracker you want to use.
*/
template<typename TrackerT>
struct EndgameSelector
{
using EGPrecT = typename EGPrecSelector<TrackerT>::type;
using PSEG = endgame::PowerSeriesEndgame<EGPrecT>;
using Cauchy = endgame::CauchyEndgame<EGPrecT>;
};
struct SecurityConfig
{
int level = 0; //SecurityLevel
NumErrorT max_norm = NumErrorT(1e4); //SecurityMaxNorm wrong default value
};
struct EndgameConfig
{
using T = NumErrorT;
T sample_point_refinement_factor = 1e-2; ///* Extra amount of tolerance for refining before computing the final approximation, during endgame.
unsigned num_sample_points = 3; //NumSamplePoints default = 2
T min_track_time = T(1e-100); //nbrh radius in Bertini book. NbhdRadius
mpq_rational sample_factor = mpq_rational(1,2); //SampleFactor
unsigned max_num_newton_iterations = 15; // the maximum number allowable iterations during endgames, for points used to approximate the final solution.
T final_tolerance = 1e-11;///< The tolerance to which to compute the endpoint using the endgame.
};
struct PowerSeriesConfig
{
unsigned max_cycle_number = 6; //MaxCycleNum
unsigned cycle_number_amplification = 5;
};
struct CauchyConfig
{
using T = NumErrorT;
T cycle_cutoff_time = T(1)/T(100000000); //CycleTimeCutoff
T ratio_cutoff_time = T(1)/T(100000000000000); //RatioTimeCutoff
T minimum_for_c_over_k_stabilization = T(3)/T(4);
unsigned int num_needed_for_stabilization = 3;
T maximum_cauchy_ratio = T(1)/T(2);
unsigned int fail_safe_maximum_cycle_number = 250; //max number of loops before giving up.
};
struct TrackBackConfig
{
unsigned minimum_cycle = 4; //MinCycleTrackback, default = 4
bool junk_removal_test = 1; //JunkRemovalTest, default = 1
unsigned max_depth_LDT = 3; //MaxLDTDepth, default = 3
};
// an empty base class
template <typename T>
struct AlgoTraits;
/**
specialization for PowerSeries, which uses CRTP
*/
template<typename PrecT>
struct AlgoTraits< PowerSeriesEndgame<PrecT>>
{
using NeededConfigs = detail::TypeList<
PowerSeriesConfig,
EndgameConfig,
SecurityConfig
>;
using EmitterType = PowerSeriesEndgame<PrecT>;
};
/**
specialization for Cauchy, which uses CRTP
*/
template<typename PrecT>
struct AlgoTraits< CauchyEndgame<PrecT>>
{
using NeededConfigs = detail::TypeList<
CauchyConfig,
EndgameConfig,
SecurityConfig>;
};
} } // namespaces

View File

@@ -0,0 +1,188 @@
//This file is part of Bertini 2.
//
//events.hpp 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.
//
//events.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with events.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
/**
\file endgames/events.hpp
\brief Contains the endgames/events base types
*/
#pragma once
#include "bertini2/detail/events.hpp"
namespace bertini {
namespace endgame{
/**
\brief Generic event for Endgames
*/
ADD_BERTINI_EVENT_TYPE(EndgameEvent,ConstEvent);
/**
\brief Generic failure event for Endgames
*/
ADD_BERTINI_EVENT_TYPE(EndgameFailure,ConstEvent);
/**
\brief Generic success event for Endgames
*/
ADD_BERTINI_EVENT_TYPE(EndgameSuccess,ConstEvent);
/**
\brief MinTrackTime reached during endgame
*/
ADD_BERTINI_EVENT_TYPE(MinTrackTimeReached,EndgameFailure);
/**
\brief Refining a sample failed for some reason
*/
ADD_BERTINI_EVENT_TYPE(RefiningFailed,EndgameFailure);
/**
\brief Cycle number computed was too high
*/
ADD_BERTINI_EVENT_TYPE(CycleNumTooHigh,EndgameFailure);
/**
\brief Security max norm reached.
*/
ADD_BERTINI_EVENT_TYPE(SecurityMaxNormReached,EndgameFailure);
/**
\brief Started running the endgame
*/
ADD_BERTINI_EVENT_TYPE(Initializing,EndgameEvent);
/**
\brief Time advancing
*/
ADD_BERTINI_EVENT_TYPE(TimeAdvanced,EndgameEvent);
/**
\brief Advanced around the circle around target time
*/
template<class ObservedT>
class CircleAdvanced : public EndgameEvent<ObservedT>
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
using CT = typename ObservedT::BaseComplexType;
/**
\brief The constructor for a CircleAdvanced Event.
\param obs The observable emitting the event.
\param previous The precision before changing.
\param next The precision after changing.
*/
CircleAdvanced(const ObservedT & obs,
Vec<CT> const& new_point,
CT const& new_time) : EndgameEvent<ObservedT>(obs),
new_point_(new_point),
new_time_(new_time)
{}
virtual ~CircleAdvanced() = default;
CircleAdvanced() = delete;
const auto& NewSample() const {return new_point_;}
const auto& NewTime() const {return new_time_;}
private:
const Vec<CT>& new_point_;
const CT& new_time_;
};
/**
\brief Walked a complete loop around the target time.
*/
ADD_BERTINI_EVENT_TYPE(ClosedLoop,EndgameEvent);
/**
\brief Approximated a root at target time.
*/
ADD_BERTINI_EVENT_TYPE(ApproximatedRoot,EndgameEvent);
/**
\brief Converged -- endgame is done!
*/
ADD_BERTINI_EVENT_TYPE(Converged,EndgameSuccess);
/**
\brief Refined a sample
*/
ADD_BERTINI_EVENT_TYPE(SampleRefined,EndgameEvent);
/**
\brief Made it into the EG operating zone, or so we believe
*/
ADD_BERTINI_EVENT_TYPE(InEGOperatingZone,EndgameEvent);
template<class ObservedT>
class PrecisionChanged : public EndgameEvent<ObservedT>
{ BOOST_TYPE_INDEX_REGISTER_CLASS
public:
/**
\brief The constructor for a PrecisionChanged Event.
\param obs The observable emitting the event.
\param previous The precision before changing.
\param next The precision after changing.
*/
PrecisionChanged(const ObservedT & obs,
unsigned previous, unsigned next) : EndgameEvent<ObservedT>(obs),
prev_(previous),
next_(next)
{}
virtual ~PrecisionChanged() = default;
PrecisionChanged() = delete;
/**
\brief Get the previous precision.
*/
auto Previous() const {return prev_;}
/**
\brief Get the next precision, what it changed to.
*/
auto Next() const {return next_;}
private:
const unsigned prev_, next_;
};
}// re: namespace endgames
}// re: namespace bertini

View File

@@ -0,0 +1,119 @@
//This file is part of Bertini 2.
//
//fixed_prec_endgame.hpp 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.
//
//fixed_prec_endgame.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with fixed_prec_endgame.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
// Tim Hodges, Colorado State University
#pragma once
/**
\file fixed_prec_endgame.hpp
\brief Contains the policy for fixed precision endgame types.
*/
#include "bertini2/trackers/fixed_precision_tracker.hpp"
#include "bertini2/trackers/fixed_precision_utilities.hpp"
#include "bertini2/endgames/config.hpp"
#include "bertini2/endgames/prec_base.hpp"
namespace bertini{ namespace endgame {
template<typename TrackerT>
class FixedPrecEndgame : public virtual EndgamePrecPolicyBase<TrackerT>
{
public:
using TrackerType = TrackerT;
using BaseComplexType = typename tracking::TrackerTraits<TrackerType>::BaseComplexType;
using BaseRealType = typename tracking::TrackerTraits<TrackerType>::BaseRealType;
using BCT = BaseComplexType;
using BRT = BaseRealType;
template<typename... T>
static
unsigned EnsureAtUniformPrecision(T& ...args)
{
return bertini::tracking::fixed::EnsureAtUniformPrecision(args...);
}
template<typename T>
static
void EnsureAtPrecision(T const & obj, unsigned prec)
{
using bertini::Precision;
if (Precision(obj)!=prec)
{
std::stringstream err_msg;
err_msg << "ensuring precision of object failed; precision is " << Precision(obj) << " and required precision is " << prec;
throw std::runtime_error(err_msg.str());
}
}
SuccessCode RefineSampleImpl(Vec<BCT> & result, Vec<BCT> const& current_sample, BCT const& current_time, double tol, unsigned max_iterations) const
{
using RT = mpfr_float;
using std::max;
auto& TR = this->GetTracker();
auto refinement_success = this->GetTracker().Refine(result,current_sample,current_time,
tol,
max_iterations);
return SuccessCode::Success;
}
explicit
FixedPrecEndgame(TrackerT const& new_tracker) : EndgamePrecPolicyBase<TrackerT>(new_tracker)
{}
virtual ~FixedPrecEndgame() = default;
}; // re: fixed prec endgame policy
template<>
struct EGPrecSelector<tracking::DoublePrecisionTracker>
{
using type = FixedPrecEndgame<tracking::DoublePrecisionTracker>;
};
template<>
struct EGPrecSelector<tracking::MultiplePrecisionTracker>
{
using type = FixedPrecEndgame<tracking::MultiplePrecisionTracker>;
};
template<class D>
struct EGPrecSelector<tracking::FixedPrecisionTracker<D>>
{
using type = FixedPrecEndgame<tracking::FixedPrecisionTracker<D>>;
};
}} //re: namespaces

View File

@@ -0,0 +1,130 @@
//This file is part of Bertini 2.
//
//interpolation.hpp 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.
//
//interpolation.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with interpolation.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
// Tim Hodges, Colorado State University
/**
\file interpolation.hpp Contains interpolation and extrapolation functions used in the endgames for estimating singular (and nonsingular) roots.
*/
#pragma once
#include "bertini2/common/config.hpp"
namespace bertini{
namespace endgame{
/**
\brief Estimates the root to interpolating polynomial.
Input:
target_time is the time value that we wish to interpolate at.
samples are space values that correspond to the time values in times.
derivatives are the dx_dt or dx_ds values at the (time,sample) values.
Output:
Since we have a target_time the function returns the corrsponding space value at that time.
Details:
We compare our approximations to the tracked value to come up with the cycle number.
Also, we use the Hermite interpolation to interpolate at the origin. Once two interpolants are withing FinalTol we
say we have converged.
\param[out] endgame_tracker_ The tracker used to compute the samples we need to start an endgame.
\param endgame_time The time value at which we start the endgame.
\param x_endgame_start The current space point at endgame_time.
\param times A deque that will hold all the time values of the samples we are going to use to start the endgame.
\param samples a deque that will hold all the samples corresponding to the time values in times.
\tparam CT The complex number type.
*/
template<typename CT>
Vec<CT> HermiteInterpolateAndSolve(CT const& target_time, const unsigned int num_sample_points, const TimeCont<CT> & times, const SampCont<CT> & samples, const SampCont<CT> & derivatives, ContStart shift_from = ContStart::Back)
{
assert((times.size() >= num_sample_points) && "must have sufficient number of sample times");
assert((samples.size() >= num_sample_points) && "must have sufficient number of sample points");
assert((derivatives.size() >= num_sample_points) && "must have sufficient number of derivatives");
unsigned num_t, num_s, num_d;
if (shift_from == ContStart::Back)
{
num_t = times.size()-1;
num_s = samples.size()-1;
num_d = derivatives.size()-1;
}
else
{
num_t = num_s = num_d = num_sample_points-1;
}
Mat< Vec<CT> > space_differences(2*num_sample_points,2*num_sample_points);
Vec<CT> time_differences(2*num_sample_points);
for(unsigned int ii=0; ii<num_sample_points; ++ii)
{
space_differences(2*ii,0) = samples[ num_s-ii]; /* F[2*i][0] = samples[i]; */
space_differences(2*ii+1,0) = samples[ num_s-ii]; /* F[2*i+1][0] = samples[i]; */
space_differences(2*ii+1,1) = derivatives[num_d-ii]; /* F[2*i+1][1] = derivatives[i]; */
time_differences(2*ii) = times[ num_t-ii]; /* z[2*i] = times[i]; */
time_differences(2*ii+1) = times[ num_t-ii]; /* z[2*i+1] = times[i]; */
}
//Add first round of finite differences to fill out rest of matrix.
for(unsigned int ii=1; ii< num_sample_points; ++ii)
{
space_differences(2*ii,1) = (space_differences(2*ii,0) - space_differences(2*ii-1,0)) / (time_differences(2*ii) - time_differences(2*ii-1));
}
//Filling out finite difference matrix to get the diagonal for hermite interpolation polyonomial.
for(unsigned int ii=2; ii < 2*num_sample_points; ++ii)
{
for(unsigned int jj=2; jj <=ii; ++jj)
{
space_differences(ii,jj) =
(space_differences(ii,jj-1) - space_differences(ii-1,jj-1))
/
(time_differences(ii) - time_differences(ii-jj));
}
}
//Start of Result from Hermite polynomial, this is using the diagonal of the
//finite difference matrix.
Vec<CT> Result = space_differences(2*num_sample_points - 1,2*num_sample_points - 1);
//This builds the hermite polynomial from the highest term down.
//As we multiply the previous result we will construct the highest term down to the last term.
for (unsigned ii=num_sample_points-1; ii >= 1; --ii)
{
Result = ((Result*(target_time - time_differences(ii)) + space_differences(2*ii, 2*ii)) * (target_time - time_differences(ii-1)) + space_differences(2*ii-1, 2*ii-1)).eval();
}
// Last term in hermite polynomial.
return (Result * (target_time - time_differences(0)) + space_differences(0,0)).eval();
} //re: HermiteInterpolateAndSolve
}} // re: namespaces

View File

@@ -0,0 +1,113 @@
//This file is part of Bertini 2.
//
//endgames/observers.hpp 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.
//
//endgames/observers.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with endgames/observers.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
/**
\file endgames/observers.hpp
\brief Contains the endgames/observers base types
*/
#pragma once
#include "bertini2/endgames/events.hpp"
#include "bertini2/logging.hpp"
#include "bertini2/detail/observer.hpp"
#include <boost/type_index.hpp>
namespace bertini {
namespace endgame{
/**
\brief Logs the endgame run, with gory detail.
\ingroup loggers observers
*/
template <typename EndgameT>
struct GoryDetailLogger : public Observer<EndgameT>
{BOOST_TYPE_INDEX_REGISTER_CLASS
using EmitterT = EndgameT;
using BCT = typename EndgameT::BaseComplexType;
virtual ~GoryDetailLogger() = default;
virtual void Observe(AnyEvent const& e) override
{
if(auto p = dynamic_cast<const TimeAdvanced<EmitterT>*>(&e))
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "time advanced " << p->Get().LatestTime();
}
else if (auto p = dynamic_cast<const SampleRefined<EmitterT>*>(&e))
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "refined a sample, huzzah";
}
else if (auto p = dynamic_cast<const CircleAdvanced<EmitterT>*>(&e))
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "advanced around the circle, to " << p->NewSample()<< " at time " << p->NewTime();
}
else if (auto p = dynamic_cast<const ClosedLoop<EmitterT>*>(&e))
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "closed a loop, cycle number " << p->Get().CycleNumber();
}
else if (auto p = dynamic_cast<const ApproximatedRoot<EmitterT>*>(&e))
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "approximated the target root. approximation " << p->Get().template FinalApproximation<BCT>() << " with error " << p->Get().ApproximateError();
}
else if (auto p = dynamic_cast<const PrecisionChanged<AMPEndgame>*>(&e))
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "precision changed from " << p->Previous() << " to " << p->Next();
}
else if (auto p = dynamic_cast<const InEGOperatingZone<EmitterT>*>(&e))
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "made it to the endgame operating zone at time " << p->Get().LatestTime();
}
else if(auto p = dynamic_cast<const Converged<EmitterT>*>(&e))
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "converged at time " << p->Get().LatestTime() << " with result " << p->Get().template FinalApproximation<BCT>() << " and residual " << p->Get().ApproximateError();
}
else if (auto p = dynamic_cast<const Initializing<EmitterT>*>(&e))
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "starting running " << boost::typeindex::type_id<EmitterT>().pretty_name();
}
else
{
BOOST_LOG_TRIVIAL(severity_level::debug) << "unprogrammed response for event of type " << boost::typeindex::type_id_runtime(e).pretty_name();
}
}
}; // gory detail
} //re: namespace endgames
}// re: namespace bertini

View File

@@ -0,0 +1,750 @@
//This file is part of Bertini 2.
//
//powerseries_endgame.hpp 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.
//
//powerseries_endgame.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with powerseries_endgame.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
// Tim Hodges, Colorado State University
#pragma once
#include "bertini2/endgames/base_endgame.hpp"
namespace bertini{ namespace endgame{
/**
\class PowerSeriesEndgame
\brief class used to finish tracking paths during Homotopy Continuation
## Explanation
The bertini::PowerSeriesEndgame class enables us to finish tracking on possibly singular paths on an arbitrary square homotopy.
The intended usage is to:
1. Create a system, tracker, and instantiate some settings.
2. Using the tracker created track to the engame boundary, by default this is t = 0.1.
3. Create a PowerSeriesEndgame, associating it to the tracker you wish to use. The tracker knows the system being solved.
4. For each path being tracked send the PowerSeriesEndgame the time value and other variable values that it should use to start the endgame.
5. The PowerSeriesEndgame, if successful, will store the homotopy solutions at t = 0.
## Example Usage
Below we demonstrate a basic usage of the PowerSeriesEndgame class to find the singularity at t = 0.
The pattern is as described above: create an instance of the class, feeding it the system to be used, and the endgame boundary time and other variable values at the endgame boundary.
\code{.cpp}
using namespace bertini::tracking;
using RealT = tracking::TrackerTraits<TrackerType>::BaseRealType; // Real types
using ComplexT = tracking::TrackerTraits<TrackerType>::BaseComplexType; Complex types
// 1. Define the polynomial system that we wish to solve.
System target_sys;
Var x = Variable::Make("x"), t = Variable::Make("t"), y = Variable::Make("y");
VariableGroup vars{x,y};
target_sys.AddVariableGroup(vars);
target_sys.AddFunction((pow(x-1,3));
target_sys.AddFunction((pow(y-1,2));
// 1b. Homogenize and patch the polynomial system to work over projective space.
sys.Homogenize();
sys.AutoPatch();
// 2. Create a start system, for us we will use a total degree start system.
auto TD_start_sys = bertini::start_system::TotalDegree(target_sys);
// 2b. Creating homotopy between the start system and system we wish to solve.
auto my_homotopy = (1-t)*target_sys + t*TD_start_sys*Rational::Rand(); //the random number is our gamma for a random path between t = 1 and t = 0.
my_homotopy.AddPathVariable(t);
//Sets up configuration settings for our particular system.
auto precision_config = PrecisionConfig(my_homotopy);
// 3. Creating a tracker. For us this is an AMPTracker.
AMPTracker tracker(my_homotopy);
//Tracker setup of settings.
SteppingConfig<RealT> stepping_preferences;
stepping_preferences.initial_step_size = RealT(1)/RealT(5);// change a stepping preference
NewtonConfig newton_preferences;
tracker.Setup(TestedPredictor,
RealFromString("1e-6"),
RealFromString("1e5"),
stepping_preferences,
newton_preferences);
tracker.PrecisionSetup(precision_config);
//We start at t = 1, and will stop at t = 0.1 before starting the endgames.
ComplexT t_start(1), t_endgame_boundary(0.1);
//This will hold our solutions at t = 0.1
std::vector<Vec<ComplexT> > my_homotopy_solutions_at_endgame_boundary;
// result holds the value we track to at 0.1, and tracking success will report if we are unsucessful.
Vec<ComplexT> result;
//4. Track all points to 0.1
for (unsigned ii = 0; ii < TD_start_sys.NumStartPoints(); ++ii)
{
DefaultPrecision(ambient_precision);
my_homotopy.precision(ambient_precision); // making sure our precision is all set up
auto start_point = TD_start_sys.StartPoint<ComplexT>(ii);
tracker.TrackPath(result,t_start,t_endgame_boundary,start_point);
my_homotopy_solutions_at_endgame_boundary.push_back(result);
}
//Settings for the endgames.
PowerSeriesConfig power_series_settings;
power_series_settings.max_cycle_number = 4;
// 5. Create a power series endgame, and use them to get the soutions at t = 0.
EndgameSelector<TrackerType>::PSEG my_pseg_endgame(tracker,power_series_settings,tolerances);
std::vector<Vec<ComplexT> > my_homotopy_solutions;
std::vector<Vec<ComplexT> > my_homotopy_divergent_paths;
for(auto s : my_homotopy_solutions_at_endgame_boundary)
{
SuccessCode endgame_success = my_pseg_endgame.Run(t_endgame_boundary,s);
if(endgame_success == SuccessCode::Success)
{
my_homotopy_solutions.push_back(my_homotopy.DehomogenizePoint(my_endgame.FinalApproximation<ComplexT>()));
}
else
{
my_homotopy_divergent_paths.push_back(my_homotopy.DehomogenizePoint(my_endgame.FinalApproximation<ComplexT>()));
}
}
\endcode
If this documentation is insufficient, please contact the authors with suggestions, or get involved! Pull requests welcomed.
## Testing
Test suite driving this class: endgames_test.
File: test/endgames/generic_pseg_test.hpp
File: test/endgames/amp_powerseries_test.cpp
File: test/endgames/fixed_double_powerseries_test.cpp
FIle: test/endgames/fixed_multiple_powerseries_test.cpp
*/
template<typename PrecT>
class PowerSeriesEndgame :
public virtual EndgameBase<PowerSeriesEndgame<PrecT>, PrecT>
{
public:
using BaseEGT = EndgameBase<PowerSeriesEndgame<PrecT>, PrecT>;
using FinalEGT = PowerSeriesEndgame<PrecT>;
using TrackerType = typename BaseEGT::TrackerType;
using BaseComplexType = typename BaseEGT::BaseComplexType;
using BaseRealType = typename BaseEGT::BaseRealType;
using EmitterType = PowerSeriesEndgame<PrecT>;
protected:
using EndgameBase<PowerSeriesEndgame<PrecT>, PrecT>::NotifyObservers;
using TupleOfTimes = typename BaseEGT::TupleOfTimes;
using TupleOfSamps = typename BaseEGT::TupleOfSamps;
using BCT = BaseComplexType;
using BRT = BaseRealType;
using Configs = typename AlgoTraits<FinalEGT>::NeededConfigs;
using ConfigsAsTuple = typename Configs::ToTuple;
/**
\brief State variable representing a computed upper bound on the cycle number.
*/
mutable unsigned upper_bound_on_cycle_number_;
/**
\brief Holds the time values for different space values used in the Power series endgame.
*/
mutable TupleOfTimes times_;
/**
\brief Holds the space values used in the Power series endgame.
*/
mutable TupleOfSamps samples_;
/**
\brief Holds the derivatives at each space point.
*/
mutable TupleOfSamps derivatives_;
/**
\brief Random vector used in computing an upper bound on the cycle number.
*/
mutable Vec<BCT> rand_vector_;
template<typename CT>
void AssertSizesTimeSpace() const
{
const auto num_sample_points = this->EndgameSettings().num_sample_points;
assert(std::get<SampCont<CT> >(samples_).size()==std::get<TimeCont<CT> >(times_).size() && "must have same number of samples in times and spaces");
assert(std::get<SampCont<CT> >(samples_).size()>=num_sample_points && "must have sufficient number of samples");
}
template<typename CT>
void AssertSizesTimeSpaceDeriv() const
{
const auto num_sample_points = this->EndgameSettings().num_sample_points;
assert(std::get<SampCont<CT> >(samples_).size()==std::get<TimeCont<CT> >(times_).size() && "must have same number of samples in times and spaces");
assert(std::get<SampCont<CT> >(samples_).size()==std::get<SampCont<CT> >(derivatives_).size() && "must have same number of samples in derivatives and spaces");
assert(std::get<SampCont<CT> >(samples_).size()>=num_sample_points && "must have sufficient number of samples");
}
public:
auto UpperBoundOnCycleNumber() const { return upper_bound_on_cycle_number_;}
/**
\brief Function that clears all samples and times from data members for the Power Series endgame
*/
template<typename CT>
void ClearTimesAndSamples()
{
std::get<TimeCont<CT> >(times_).clear();
std::get<SampCont<CT> >(samples_).clear();
}
/**
\brief Function to set the times used for the Power Series endgame.
*/
template<typename CT>
void SetTimes(TimeCont<CT> const& times_to_set) { std::get<TimeCont<CT> >(times_) = times_to_set;}
/**
\brief Function to get the times used for the Power Series endgame.
*/
template<typename CT>
const auto& GetTimes() const {return std::get<TimeCont<CT> >(times_);}
const BCT& LatestTimeImpl() const
{
return GetTimes<BCT>().back();
}
/**
\brief Function to set the space values used for the Power Series endgame.
*/
template<typename CT>
void SetSamples(SampCont<CT> const& samples_to_set) { std::get<SampCont<CT> >(samples_) = samples_to_set;}
/**
\brief Function to get the space values used for the Power Series endgame.
*/
template<typename CT>
const auto& GetSamples() const {return std::get<SampCont<CT> >(samples_);}
/**
\brief Function to set the times used for the Power Series endgame.
*/
template<typename CT>
void SetRandVec(int size) {rand_vector_ = Vec<CT>::Random(size);}
explicit PowerSeriesEndgame(TrackerType const& tr,
const ConfigsAsTuple& settings )
: BaseEGT(tr, settings), EndgamePrecPolicyBase<TrackerType>(tr)
{}
template< typename... Ts >
explicit
PowerSeriesEndgame(TrackerType const& tr, const Ts&... ts ) : PowerSeriesEndgame(tr, Configs::Unpermute( ts... ) )
{}
/**
\brief Computes an upper bound on the cycle number. Consult page 53 of \cite bertinibook.
## Input:
None: all data needed are class data members.
## Output:
upper_bound_on_cycle_number_: Used for an exhaustive search for the best cycle number for approimating the path to t = 0.
##Details:
\tparam CT The complex number type.
*/
template<typename CT>
unsigned ComputeBoundOnCycleNumber()
{
using RT = typename Eigen::NumTraits<CT>::Real;
using std::log; using std::abs;
const auto& samples = std::get<SampCont<CT> >(samples_);
AssertSizesTimeSpace<CT>();
auto num_samples = samples.size();
const Vec<CT> & sample0 = samples[num_samples-3];
const Vec<CT> & sample1 = samples[num_samples-2];
const Vec<CT> & sample2 = samples[num_samples-1]; // most recent sample. oldest samples at front of the container
// should this only be if the system is homogenized?
CT rand_sum1 = ((sample1 - sample0).transpose()*rand_vector_).sum();
CT rand_sum2 = ((sample2 - sample1).transpose()*rand_vector_).sum();
if ( abs(rand_sum1)==0 || abs(rand_sum2)==0) // avoid division by 0
{
upper_bound_on_cycle_number_ = 1;
return upper_bound_on_cycle_number_;
}
RT estimate = log(static_cast<RT>(this->EndgameSettings().sample_factor))/log(abs(rand_sum2/rand_sum1));
if (estimate < 1) // would be nan if sample points are same as each other
upper_bound_on_cycle_number_ = 1;
else
{
using std::max;
auto upper_bound = unsigned(round(estimate)*this->template Get<PowerSeriesConfig>().cycle_number_amplification);
upper_bound_on_cycle_number_ = max(upper_bound,this->template Get<PowerSeriesConfig>().max_cycle_number);
}
return upper_bound_on_cycle_number_;
}//end ComputeBoundOnCycleNumber
/**
\brief This function computes the cycle number using an exhaustive search up the upper bound computed by the above function BoundOnCyleNumber.
## Input:
None: all data needed are class data members.
## Output:
cycle_number_: Used to create a hermite interpolation to t = 0.
##Details:
\tparam CT The complex number type.
This is done by an exhaustive search from 1 to upper_bound_on_cycle_number. There is a conversion to the s-space from t-space in this function.
As a by-product the derivatives at each of the samples is returned for further use.
*/
template<typename CT>
unsigned ComputeCycleNumber(CT const& t0)
{
using RT = typename Eigen::NumTraits<CT>::Real;
const auto& samples = std::get<SampCont<CT> >(samples_);
const auto& times = std::get<TimeCont<CT> >(times_);
const auto& derivatives = std::get<SampCont<CT> >(derivatives_);
AssertSizesTimeSpaceDeriv<CT>();
const Vec<CT> &most_recent_sample = samples.back();
const CT& most_recent_time = times.back();
//Compute upper bound for cycle number.
ComputeBoundOnCycleNumber<CT>();
unsigned num_pts;
if (samples.size() > this->EndgameSettings().num_sample_points)
num_pts = this->EndgameSettings().num_sample_points;
else
num_pts = this->EndgameSettings().num_sample_points-1;
auto min_found_difference = Eigen::NumTraits<RT>::highest();
TimeCont<CT> s_times(num_pts);
SampCont<CT> s_derivatives(num_pts);
auto offset = samples.size() - num_pts - 1; // -1 here to shift away from the back of the container
for(unsigned int candidate = 1; candidate <= upper_bound_on_cycle_number_; ++candidate)
{
using std::pow;
std::tie(s_times, s_derivatives) = TransformToSPlane(candidate, t0, num_pts, ContStart::Front);
RT cand_power{1/static_cast<RT>(candidate)};
RT curr_diff = (HermiteInterpolateAndSolve<CT>(
pow((most_recent_time-t0)/(times[0]-t0),cand_power), // the target time
num_pts,s_times,samples,s_derivatives, ContStart::Front) // the input data
-
most_recent_sample).template lpNorm<Eigen::Infinity>();
if (curr_diff < min_found_difference)
{
min_found_difference = curr_diff;
this->cycle_number_ = candidate;
}
}// end cc loop over cycle number possibilities
return this->cycle_number_;
}//end ComputeCycleNumber
/**
\brief Compute a set of derivatives using internal data to the endgame.
## Input:
None: all data needed are class data members.
## Output:
None: Derivatives are members of this class.
##Details:
\tparam CT The complex number type.
*/
template<typename CT>
void ComputeAllDerivatives()
{
auto& samples = std::get<SampCont<CT> >(samples_);
auto& times = std::get<TimeCont<CT> >(times_);
auto& derivatives = std::get<SampCont<CT> >(derivatives_);
assert((samples.size() == times.size()) && "must have same number of times and samples");
if (tracking::TrackerTraits<TrackerType>::IsAdaptivePrec) // known at compile time
{
auto max_precision = this->EnsureAtUniformPrecision(times, samples);
this->GetSystem().precision(max_precision);
}
//Compute dx_dt for each sample.
derivatives.clear(); derivatives.resize(samples.size());
for(unsigned ii = 0; ii < samples.size(); ++ii)
{
derivatives[ii] = -this->GetSystem().Jacobian(samples[ii],times[ii]).lu().solve(this->GetSystem().TimeDerivative(samples[ii],times[ii]));
}
}
/**
\param c The cycle number you want to use
This function transforms the times and derivatives into the S-plane, scaled by the cycle number.
this function also transforms them into the interval [0 1]
*/
template <typename CT>
std::tuple<TimeCont<CT>, SampCont<CT>> TransformToSPlane(int cycle_num, CT const& t0, unsigned num_pts, ContStart shift_from)
{
if (cycle_num==0)
throw std::runtime_error("cannot transform to s plane with cycle number 0");
AssertSizesTimeSpaceDeriv<CT>();
using RT = typename Eigen::NumTraits<CT>::Real;
const auto& times = std::get<TimeCont<CT> >(times_);
const auto& derivatives = std::get<SampCont<CT> >(derivatives_);
RT c = static_cast<RT>(cycle_num);
RT one_over_c = 1/c;
unsigned offset_t, offset_d;
if (shift_from == ContStart::Back)
{
offset_t = times.size()-num_pts;
offset_d = derivatives.size()-num_pts;
}
else
offset_t = offset_d = 0;
TimeCont<CT> s_times(num_pts);
SampCont<CT> s_derivatives(num_pts);
CT time_shift = times[offset_t] - t0;
for(unsigned ii = 0; ii < num_pts; ++ii){
s_times[ii] = pow((times[ii+offset_t]-t0)/time_shift, one_over_c);
s_derivatives[ii] = derivatives[ii+offset_d]*( c*pow(s_times[ii],cycle_num-1))*time_shift;
}
return std::make_tuple(s_times, s_derivatives);
}
/**
\brief This function computes an approximation of the space value at the time time_t0.
## Input:
result: Passed by reference this holds the value of the approximation we compute
t0: This is the time value for which we wish to compute an approximation at.
## Output:
SuccessCode: This reports back if we were successful in making an approximation.
##Details:
\tparam CT The complex number type.
This function handles computing an approximation at the origin.
We compute the cycle number best for the approximation, and convert derivatives and times to the s-plane where s = t^(1/c).
We use the converted times and derivatives along with the samples to do a Hermite interpolation.
*/
template<typename CT>
SuccessCode ComputeApproximationOfXAtT0(Vec<CT>& result, const CT & t0)
{
const auto c = ComputeCycleNumber<CT>(t0);
auto num_pts = this->EndgameSettings().num_sample_points;
TimeCont<CT> s_times;
SampCont<CT> s_derivatives;
std::tie(s_times, s_derivatives) = TransformToSPlane(c, t0, num_pts, ContStart::Back);
// the data was transformed to be on the interval [0 1] so we can hard-code the time-to-solve as 0 here.
Precision(result, Precision(s_derivatives.back()));
result = HermiteInterpolateAndSolve(CT(0), num_pts, s_times, std::get<SampCont<CT> >(samples_), s_derivatives, ContStart::Back);
return SuccessCode::Success;
}//end ComputeApproximationOfXAtT0
/**
\brief The samples used in the power series endgame are collected by advancing time to t = 0, by multiplying the current time by the sample factor.
## Input:
target_time: This is the time we are trying to approximate, default is t = 0.
## Output:
SuccessCode: This reports back if we were successful in advancing time.
##Details:
\tparam CT The complex number type.
This function computes the next time value for the power series endgame. After computing this time value,
it will track to it and compute the derivative at this time value for further appoximations to be made during the
endgame.
*/
template<typename CT>
SuccessCode AdvanceTime(const CT & target_time)
{
using RT = typename Eigen::NumTraits<CT>::Real;
auto& samples = std::get<SampCont<CT> >(samples_);
auto& times = std::get<TimeCont<CT> >(times_);
auto& derivatives = std::get<SampCont<CT> >(derivatives_);
AssertSizesTimeSpaceDeriv<CT>();
Vec<CT> next_sample;
CT next_time = (times.back() + target_time) * static_cast<RT>(this->EndgameSettings().sample_factor); //setting up next time value using the midpoint formula, sample_factor will give us some
if (abs(next_time - target_time) < this->EndgameSettings().min_track_time) // generalized for target_time not equal to 0.
{
NotifyObservers(MinTrackTimeReached<EmitterType>(*this));
return SuccessCode::MinTrackTimeReached;
}
SuccessCode tracking_success = this->GetTracker().TrackPath(next_sample,times.back(),next_time,samples.back());
if (tracking_success != SuccessCode::Success)
return tracking_success;
NotifyObservers(InEGOperatingZone<EmitterType>(*this));
this->EnsureAtPrecision(next_time,Precision(next_sample));
times.push_back(next_time);
samples.push_back(next_sample);
auto refine_success = this->RefineSample(samples.back(), next_sample, times.back(),
this->FinalTolerance() * this->EndgameSettings().sample_point_refinement_factor,
this->EndgameSettings().max_num_newton_iterations);
if (refine_success != SuccessCode::Success)
{
NotifyObservers(RefiningFailed<EmitterType>(*this));
return refine_success;
}
this->EnsureAtPrecision(times.back(),Precision(samples.back()));
NotifyObservers(SampleRefined<EmitterType>(*this));
// we keep one more samplepoint than needed around, for estimating the cycle number
if (times.size() > this->EndgameSettings().num_sample_points+1)
{
times.pop_front();
samples.pop_front();
}
return SuccessCode::Success;
}
/**
\brief Primary function running the Power Series endgame.
## Input:
start_time: This is the time value for which the endgame begins, by default this is t = 0.1
start_point: An approximate solution of the homotopy at t = start_time
target_time: The time value that we are wishing to approximate to. This is default set to t = 0.
## Output:
SuccessCode: This reports back if we were successful in advancing time.
##Details:
\tparam CT The complex number type.
Tracking forward with the number of sample points, this function will make approximations using Hermite interpolation. This process will continue until two consecutive
approximations are withing final tolerance of each other.
*/
template<typename CT>
SuccessCode RunImpl(const CT & start_time, const Vec<CT> & start_point, CT const& target_time)
{
if (start_point.size()!=this->GetSystem().NumVariables())
{
std::stringstream err_msg;
err_msg << "number of variables in start point for PSEG, " << start_point.size() << ", must match the number of variables in the system, " << this->GetSystem().NumVariables();
throw std::runtime_error(err_msg.str());
}
DefaultPrecision(Precision(start_point));
using RT = typename Eigen::NumTraits<CT>::Real;
//Set up for the endgame.
ClearTimesAndSamples<CT>();
// unpack some references for easy use
auto& samples = std::get<SampCont<CT> >(samples_);
auto& times = std::get<TimeCont<CT> >(times_);
auto& derivatives = std::get<SampCont<CT> >(derivatives_);
Vec<CT>& latest_approx = this->final_approximation_;
Vec<CT>& prev_approx = this->previous_approximation_;
// this is for estimating a ... norm?
SetRandVec<CT>(start_point.size());
auto initial_sample_success = this->ComputeInitialSamples(start_time, target_time, start_point, times, samples);
if (initial_sample_success!=SuccessCode::Success)
{
NotifyObservers(EndgameFailure<EmitterType>(*this));
return initial_sample_success;
}
this->template RefineAllSamples<CT>(samples, times);
ComputeAllDerivatives<CT>();
auto extrapolation_code = ComputeApproximationOfXAtT0(prev_approx, target_time);
latest_approx = prev_approx;
if (extrapolation_code != SuccessCode::Success)
return extrapolation_code;
RT norm_of_dehom_of_latest_approx;
RT norm_of_dehom_of_prev_approx;
if (this->SecuritySettings().level <= 0)
norm_of_dehom_of_prev_approx = this->GetSystem().DehomogenizePoint(prev_approx).template lpNorm<Eigen::Infinity>();
NumErrorT& approx_error = this->approximate_error_;
approx_error = 1;
while (approx_error > this->FinalTolerance())
{
auto advance_code = AdvanceTime<CT>(target_time);
if (advance_code!=SuccessCode::Success)
{
NotifyObservers(EndgameFailure<EmitterType>(*this));
return advance_code;
}
// this code is what bertini1 does... it refines all samples, like, all the time.
this->template RefineAllSamples<CT>(samples, times);
ComputeAllDerivatives<CT>();
extrapolation_code = ComputeApproximationOfXAtT0(latest_approx, target_time);
if (extrapolation_code!=SuccessCode::Success)
{
NotifyObservers(EndgameFailure<EmitterType>(*this));
return extrapolation_code;
}
approx_error = static_cast<NumErrorT>((latest_approx - prev_approx).template lpNorm<Eigen::Infinity>());
NotifyObservers(ApproximatedRoot<EmitterType>(*this));
if(this->SecuritySettings().level <= 0)
{
norm_of_dehom_of_latest_approx = this->GetSystem().DehomogenizePoint(latest_approx).template lpNorm<Eigen::Infinity>();
if(norm_of_dehom_of_latest_approx > this->SecuritySettings().max_norm && norm_of_dehom_of_prev_approx > this->SecuritySettings().max_norm)
{
NotifyObservers(SecurityMaxNormReached<EmitterType>(*this));
return SuccessCode::SecurityMaxNormReached;
}
norm_of_dehom_of_prev_approx = norm_of_dehom_of_latest_approx;
}
Precision(prev_approx, Precision(latest_approx));
prev_approx = latest_approx;
} //end while
NotifyObservers(Converged<EmitterType>(*this));
return SuccessCode::Success;
} //end PSEG
virtual ~PowerSeriesEndgame() = default;
}; // end powerseries class
}} // re: namespaces

View File

@@ -0,0 +1,104 @@
//This file is part of Bertini 2.
//
//prec_base.hpp 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.
//
//prec_base.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with prec_base.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin eau claire
// Tim Hodges, Colorado State University
#pragma once
/**
\file include/bertini2/endgames/prec_base.hpp
\brief Contains a parent class, EndgamePrecPolicyBase (an observable), from which the fixed double, fixed multiple, or adaptive precision endgames are derived.
*/
namespace bertini{ namespace endgame {
/**
\brief A common base type for various precision types, fixed and adaptive. The purpose of this is to maintain a uniform interface to the tracker that's being used, across endgame types.
*/
template <typename TrackerT>
class EndgamePrecPolicyBase : public virtual Observable
{
public:
using TrackerType = TrackerT;
explicit
EndgamePrecPolicyBase(TrackerT const& new_tracker) : tracker_(std::ref(new_tracker))
{}
virtual ~EndgamePrecPolicyBase() = default;
/**
Tell the endgame to use the given tracker. Takes a reference.
\note Ensure the tracker you are using doesn not go out of scope!
*/
inline
void SetTracker(TrackerT const& new_tracker)
{
tracker_ = std::ref(new_tracker); // rebind the reference
}
/**
\brief Getter for the tracker used inside an instance of the endgame.
*/
inline
const TrackerT& GetTracker() const
{
return tracker_.get();
}
/**
\brief Get the system being tracked on, which is referred to by the tracker.
*/
inline
const System& GetSystem() const
{ return GetTracker().GetSystem();}
void ChangePrecision(unsigned p)
{
tracker_.ChangePrecision(p);
}
private:
/**
\brief A tracker that must be passed into the endgame through a constructor. This tracker is what will be used to track to all time values during the endgame.
*/
std::reference_wrapper<const TrackerT> tracker_;
}; //EndgamePrecPolicyBase
} } // end namespaces

View File

@@ -0,0 +1,39 @@
//This file is part of Bertini 2.
//
//b2/core/include/forbid_mixed_arithmetic.hpp 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.
//
//b2/core/include/forbid_mixed_arithmetic.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with b2/core/include/forbid_mixed_arithmetic.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2017-2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
#ifndef BERTINI_FORBID_MIXED_ARITHMETIC_HPP
#define BERTINI_FORBID_MIXED_ARITHMETIC_HPP
#pragma once
namespace boost{
namespace multiprecision
{
template <class Backend>
struct is_compatible_arithmetic_type<double, number<Backend> > : public mpl::false_ {};
template <class Backend>
struct is_compatible_arithmetic_type<mpq_rational, number<Backend> > : public mpl::false_ {};
}
}
#endif

View File

@@ -0,0 +1,154 @@
//This file is part of Bertini 2.
//
//function_tree.hpp 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.
//
//function_tree.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with function_tree.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, University of Wisconsin Eau Claire
// jeb collins, west texas a&m
/**
\file function_tree.hpp
\brief Collects the various header files which define the Bertini2 function tree node types.
*/
#ifndef BERTINI_FUNCTION_TREE_HPP
#define BERTINI_FUNCTION_TREE_HPP
#include "bertini2/function_tree/node.hpp"
#include "bertini2/function_tree/operators/operator.hpp"
#include "bertini2/function_tree/operators/arithmetic.hpp"
#include "bertini2/function_tree/operators/trig.hpp"
#include "bertini2/function_tree/symbols/linear_product.hpp"
#include "bertini2/function_tree/symbols/symbol.hpp"
#include "bertini2/function_tree/symbols/variable.hpp"
#include "bertini2/function_tree/symbols/number.hpp"
#include "bertini2/function_tree/symbols/special_number.hpp"
#include "bertini2/function_tree/roots/function.hpp"
#include "bertini2/function_tree/roots/jacobian.hpp"
#include "bertini2/function_tree/simplify.hpp"
BOOST_CLASS_EXPORT_KEY(bertini::node::Node)
BOOST_SERIALIZATION_ASSUME_ABSTRACT(bertini::node::Node)
BOOST_CLASS_EXPORT_KEY(bertini::node::Handle)
BOOST_CLASS_EXPORT_KEY(bertini::node::Symbol)
BOOST_CLASS_EXPORT_KEY(bertini::node::NamedSymbol)
BOOST_CLASS_EXPORT_KEY(bertini::node::Number)
BOOST_SERIALIZATION_ASSUME_ABSTRACT(bertini::node::Symbol)
BOOST_SERIALIZATION_ASSUME_ABSTRACT(bertini::node::NamedSymbol)
BOOST_SERIALIZATION_ASSUME_ABSTRACT(bertini::node::Number)
BOOST_CLASS_EXPORT_KEY(bertini::node::Variable)
BOOST_CLASS_EXPORT_KEY(bertini::node::Differential)
BOOST_CLASS_EXPORT_KEY(bertini::node::Float)
BOOST_CLASS_EXPORT_KEY(bertini::node::Integer)
BOOST_CLASS_EXPORT_KEY(bertini::node::Rational)
BOOST_CLASS_EXPORT_KEY(bertini::node::special_number::Pi)
BOOST_CLASS_EXPORT_KEY(bertini::node::special_number::E)
BOOST_CLASS_EXPORT_KEY(bertini::node::Function)
BOOST_CLASS_EXPORT_KEY(bertini::node::Jacobian)
BOOST_CLASS_EXPORT_KEY(bertini::node::SinOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::ArcSinOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::CosOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::ArcCosOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::TanOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::ArcTanOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::SumOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::NegateOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::MultOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::PowerOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::IntegerPowerOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::SqrtOperator)
BOOST_CLASS_EXPORT_KEY(bertini::node::ExpOperator)
BOOST_CLASS_TRACKING(bertini::node::Node, track_always)
BOOST_CLASS_TRACKING(bertini::node::Symbol, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::NamedSymbol, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::Number, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::Variable, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::Differential, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::Float, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::Integer, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::Rational, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::special_number::Pi, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::special_number::E, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::Function, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::Jacobian, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::SinOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::ArcSinOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::CosOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::ArcCosOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::TanOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::ArcTanOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::SumOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::NegateOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::MultOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::PowerOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::IntegerPowerOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::SqrtOperator, boost::serialization::track_always)
BOOST_CLASS_TRACKING(bertini::node::ExpOperator, boost::serialization::track_always)
#endif

View File

@@ -0,0 +1,128 @@
//This file is part of Bertini 2.
//
//include/bertini2/function_tree/forward_declares.hpp 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.
//
//include/bertini2/function_tree/forward_declares.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with include/bertini2/function_tree/forward_declares.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2016 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
/**
\file include/bertini2/function_tree/forward_declares.hpp
\brief Forward declarations for types in the node:: namespace
*/
#pragma once
namespace bertini {
namespace node{
class Node;
}
namespace node{
class Variable;
class Integer;
class Float;
class Rational;
class Function;
class Jacobian;
class Differential;
}
namespace node{
class Operator;
class UnaryOperator;
class NaryOperator;
class SumOperator;
class MultOperator;
class IntegerPowerOperator;
class PowerOperator;
class ExpOperator;
class LogOperator;
class NegateOperator;
class SqrtOperator;
class LinearProduct;
class DiffLinear;
}
namespace node{
class TrigOperator;
class SinOperator;
class ArcSinOperator;
class CosOperator;
class ArcCosOperator;
class TanOperator;
class ArcTanOperator;
}
namespace node{
namespace special_number{
class Pi;
class E;
}
}
namespace node{
template <typename Archive>
void register_derived_node_types(Archive& ar)
{
ar.template register_type<bertini::node::Variable>();
ar.template register_type<bertini::node::Integer>();
ar.template register_type<bertini::node::Float>();
ar.template register_type<bertini::node::Rational>();
ar.template register_type<bertini::node::Function>();
ar.template register_type<bertini::node::Jacobian>();
ar.template register_type<bertini::node::Differential>();
// ar.template register_type<bertini::node::Operator>(); // abstract type
// ar.template register_type<bertini::node::UnaryOperator>(); // abstract type
// ar.template register_type<bertini::node::NaryOperator>(); // abstract type
ar.template register_type<bertini::node::SumOperator>();
ar.template register_type<bertini::node::MultOperator>();
ar.template register_type<bertini::node::IntegerPowerOperator>();
ar.template register_type<bertini::node::PowerOperator>();
ar.template register_type<bertini::node::ExpOperator>();
ar.template register_type<bertini::node::LogOperator>();
ar.template register_type<bertini::node::NegateOperator>();
ar.template register_type<bertini::node::SqrtOperator>();
ar.template register_type<bertini::node::LinearProduct>();
// ar.template register_type<bertini::node::TrigOperator>(); // abstract type
ar.template register_type<bertini::node::SinOperator>();
ar.template register_type<bertini::node::ArcSinOperator>();
ar.template register_type<bertini::node::CosOperator>();
ar.template register_type<bertini::node::ArcCosOperator>();
ar.template register_type<bertini::node::TanOperator>();
ar.template register_type<bertini::node::ArcTanOperator>();
ar.template register_type<bertini::node::special_number::Pi>();
ar.template register_type<bertini::node::special_number::E>();
}
}
}// namespace bertini

View File

@@ -0,0 +1,451 @@
//This file is part of Bertini 2.
//
//node.hpp 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.
//
//node.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with node.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
//
// silviana amethyst
// University of Wisconsin - Eau Claire
//
// Created by Collins, James B. on 4/30/15.
/**
\file node.hpp
\brief Defines the abstract Node base class.
*/
#ifndef BERTINI_NODE_BASE_HPP
#define BERTINI_NODE_BASE_HPP
#include <iostream>
#include <string>
#include <tuple>
#include <boost/type_index.hpp>
#include "bertini2/num_traits.hpp"
#include "bertini2/detail/visitable.hpp"
#include "bertini2/function_tree/forward_declares.hpp"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/nvp.hpp>
namespace bertini {
namespace node{
class Variable;
}
using VariableGroup = std::vector< std::shared_ptr<node::Variable> >;
enum class VariableGroupType
{
Homogeneous,
Affine,
Ungrouped
};
namespace node{
namespace detail{
template<typename T>
struct FreshEvalSelector
{};
template<>
struct FreshEvalSelector<dbl>
{
template<typename N>
static dbl Run(N const& n, std::shared_ptr<Variable> const& diff_variable)
{
return n.FreshEval_d(diff_variable);
}
template<typename N>
static void RunInPlace(dbl& evaluation_value, N const& n, std::shared_ptr<Variable> const& diff_variable)
{
n.FreshEval_d(evaluation_value, diff_variable);
}
};
template<>
struct FreshEvalSelector<mpfr_complex>
{
template<typename N>
static mpfr_complex Run(N const& n, std::shared_ptr<Variable> const& diff_variable)
{
return n.FreshEval_mp(diff_variable);
}
template<typename N>
static void RunInPlace(mpfr_complex& evaluation_value, N const& n, std::shared_ptr<Variable> const& diff_variable)
{
n.FreshEval_mp(evaluation_value, diff_variable);
}
};
}
/**
An interface for all nodes in a function tree, and for a function object as well. Almost all
methods that will be called on a node must be declared in this class. The main evaluation method is
defined in this class.
Bertini function trees are created using std::shared_ptr's to Node base class, generally.
\brief Abstract base class for the Bertini hybrid-precision (double-multiple) expression tree.
*/
class Node : public virtual VisitableBase<>, public std::enable_shared_from_this<Node>
{
friend detail::FreshEvalSelector<dbl>;
friend detail::FreshEvalSelector<mpfr_complex>;
public:
virtual ~Node() = default;
///////// PUBLIC PURE METHODS /////////////////
/**
Tells code to run a fresh eval on node next time.
*/
virtual void Reset() const = 0;
///////// END PUBLIC PURE METHODS /////////////////
public:
/**
Evaluate the node. If flag false, just return value, if flag true
run the specific FreshEval of the node, then set flag to false.
Template type is type of value you want returned.
\return The value of the node.
\tparam T The number type for return. Must be one of the types stored in the Node class, currently dbl and mpfr_complex.
*/
template<typename T>
T Eval(std::shared_ptr<Variable> const& diff_variable = nullptr) const
{
T result;
EvalInPlace(result, diff_variable);
return result;
}
/**
Evaluate the node in place. If flag false, just return value, if flag true
run the specific FreshEval of the node, then set flag to false.
Template type is type of value you want returned.
\return The value of the node.
\tparam T The number type for return. Must be one of the types stored in the Node class, currently dbl and mpfr_complex.
*/
template<typename T>
void EvalInPlace(T& eval_value, std::shared_ptr<Variable> const& diff_variable = nullptr) const;
///////// PUBLIC PURE METHODS /////////////////
/**
\brief A transform function, which eliminates nodes from the tree
A better implementation of this would use a generic Transform. If you know how to do this, please rewrite the Nodes so they can transform to our whim, and submit a PR.
\return The number of nodes eliminated
\see EliminateZeros
*/
virtual unsigned EliminateOnes() = 0;
/**
\brief A transform function, which eliminates nodes from the tree
A better implementation of this would use a generic Transform. If you know how to do this, please rewrite the Nodes so they can transform to our whim, and submit a PR.
\return The number of nodes eliminated
\see EliminateOnes
*/
virtual unsigned EliminateZeros() = 0;
/**
\brief A mutating function which finds ways to reduce the depth of the tree
\note The default implementation is empty, and does literally nothing.
*/
virtual unsigned ReduceDepth();
/**
Virtual method for printing Nodes to arbitrary output streams.
*/
virtual void print(std::ostream& target) const = 0;
/**
\brief Compute the derivative with respect to a single variable.
Virtual method for differentiating the node. If no variable is passed, produces a Jacobian tree when all is said and done, which is used for evaluating the Jacobian.
\return The result of differentiation. Jacobian or regular Node depending on what you passed in.
*/
virtual std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const = 0;
/**
Compute the degree, optionally with respect to a single variable.
\param v Shared pointer to variable with respect to which you want to compute the degree of the Node.
\return The degree. Will be negative if the Node is non-polynomial.
*/
virtual int Degree(std::shared_ptr<Variable> const& v = nullptr) const = 0;
/**
Compute the multidegree with respect to a variable group. This is for homogenization, and testing for homogeneity.
\return A vector containing the degrees. Negative entries indicate non-polynomiality.
*/
virtual std::vector<int> MultiDegree(VariableGroup const& vars) const = 0;
/**
Compute the overall degree with respect to a variable group.
\param vars A group of variables.
\return The degree. Will be negative if the Node is non-polynomial.
*/
virtual int Degree(VariableGroup const& vars) const = 0;
/**
Homogenize a tree, inputting a variable group holding the non-homogeneous variables, and the new homogenizing variable. The homvar may be an element of the variable group, that's perfectly ok.
\param homvar The homogenizing variable, which is multiplied against terms with degree deficiency with repect to other terms.
\param vars A group of variables, with respect to which you wish to homogenize.
*/
virtual void Homogenize(VariableGroup const& vars, std::shared_ptr<Variable> const& homvar) = 0;
/**
Check for homogeneity, absolutely with respect to all variables, including path variables and all other variable types, or with respect to a single varaible, if passed.
\return True if it is homogeneous, false if not.
*/
virtual bool IsHomogeneous(std::shared_ptr<Variable> const& v = nullptr) const = 0;
/**
Check for homogeneity, with respect to a variable group.
\return True if it is homogeneous, false if not.
*/
virtual bool IsHomogeneous(VariableGroup const& vars) const = 0;
/**
Change the precision of this variable-precision tree node.
\param prec the number of digits to change precision to.
*/
virtual void precision(unsigned int prec) const = 0;
unsigned precision() const;
///////// PUBLIC PURE METHODS /////////////////
/**
Check if a Node is polynomial -- it has degree at least 0. Negative degrees indicate non-polynomial.
\return True if it is polynomial, false if not.
*/
bool IsPolynomial(std::shared_ptr<Variable> const&v = nullptr) const;
/**
Check if a Node is polynomial -- it has degree at least 0. Negative degrees indicate non-polynomial.
\return True if it is polynomial, false if not.
*/
bool IsPolynomial(VariableGroup const&v) const;
protected:
//Stores the current value of the node in all required types
//We must hard code in all types that we want here.
//TODO: Initialize this to some default value, second = false
mutable std::tuple< std::pair<dbl,bool>, std::pair<mpfr_complex,bool> > current_value_;
///////// PRIVATE PURE METHODS /////////////////
/**
Overridden code for specific node types, for how to evaluate themselves. Called from the wrapper Eval<>() call from Node, if so required (by resetting, etc).
If we had the ability to use template virtual functions, we would have. However, this is impossible with current C++ without using experimental libraries, so we have two copies -- because there are two number types for Nodes, dbl and mpfr_complex.
*/
virtual dbl FreshEval_d(std::shared_ptr<Variable> const&) const = 0;
/**
Overridden code for specific node types, for how to evaluate themselves. Called from the wrapper EvalInPlace<>() call from Node, if so required (by resetting, etc).
If we had the ability to use template virtual functions, we would have. However, this is impossible with current C++ without using experimental libraries, so we have two copies -- because there are two number types for Nodes, dbl and mpfr_complex.
*/
virtual void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const&) const = 0;
/**
Overridden code for specific node types, for how to evaluate themselves. Called from the wrapper Eval<>() call from Node, if so required (by resetting, etc).
If we had the ability to use template virtual functions, we would have. However, this is impossible with current C++ without using experimental libraries, so we have two copies -- because there are two number types for Nodes, dbl and mpfr_complex.
*/
virtual mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const&) const = 0;
/**
Overridden code for specific node types, for how to evaluate themselves. Called from the wrapper Eval<>() call from Node, if so required (by resetting, etc).
If we had the ability to use template virtual functions, we would have. However, this is impossible with current C++ without using experimental libraries, so we have two copies -- because there are two number types for Nodes, dbl and mpfr_complex.
*/
virtual void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const&) const = 0;
///////// END PRIVATE PURE METHODS /////////////////
/**
Set the stored values for the Node to indicate a fresh eval on the next pass. This is so that Nodes which are referred to more than once, are only evaluated once. The first evaluation is fresh, and then the indicator for fresh/stored is set to stored. Subsequent evaluation calls simply return the stored number.
*/
void ResetStoredValues() const;
Node();
private:
friend std::ostream& operator<<(std::ostream & out, const Node& N);
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
register_derived_node_types(ar);
}
}; // re: class node
/**
a single layer of indirection, though which to call the overridden virtual print() method which must be defined for each non-abstract Node type.
*/
inline std::ostream& operator<<(std::ostream & out, const Node& N)
{
N.print(out);
return out;
}
inline std::ostream& operator<<(std::ostream & out, const std::shared_ptr<Node>& N)
{
N->print(out);
return out;
}
// inherit from this to get a nice method of producing shared pointers to specific type, solving the diamond problem
//
// T is a derived type
//
// I adapted from:
// https://stackoverflow.com/questions/16082785/use-of-enable-shared-from-this-with-multiple-inheritance
//
template<typename T>
struct EnableSharedFromThisVirtual: public virtual Node
{
public:
std::shared_ptr<T> shared_from_this() {
return std::dynamic_pointer_cast<T>(Node::shared_from_this());
}
std::shared_ptr<const T> shared_from_this() const{
return std::dynamic_pointer_cast<const T>(Node::shared_from_this());
}
template <class ThisT>
std::shared_ptr<ThisT> downcast_shared_from_this(){
return std::dynamic_pointer_cast<ThisT>(Node::shared_from_this());
}
template <class ThisT>
std::shared_ptr<const ThisT> downcast_shared_from_this() const{
return std::dynamic_pointer_cast<const ThisT>(Node::shared_from_this());
}
};
} // re: namespace node
} // re: namespace bertini
#endif
/* defined(BERTINI_NODE_BASE_HPP) */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,228 @@
//This file is part of Bertini 2.
//
//operator.hpp 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.
//
//operator.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with operator.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
// silviana amethyst, university of wisconsin-eau claire
//
// Created by Collins, James B. on 4/30/15.
//
//
// operator.hpp: Declares the class Operator.
/**
\file operator.hpp
\brief Provides the abstract Operator Node type.
*/
#ifndef BERTINI_OPERATOR_HPP
#define BERTINI_OPERATOR_HPP
#include "bertini2/function_tree/node.hpp"
#include <vector>
namespace bertini {
namespace node{
/**
\brief Abstract Node type from which all Operators inherit.
This class is an interface for all operators in the Bertini2 function tree.
*/
class Operator : public virtual Node
{
public:
virtual ~Operator() = default;
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Node>(*this);
}
};
/**
\brief Interface for all unary Operator types.
This class is an interface for all unary operators, such as negation.
The sole child is stored in a shared_ptr.
*/
class UnaryOperator : public virtual Operator
{
public:
UnaryOperator(const std::shared_ptr<Node> & n) : operand_(n)
{}
virtual ~UnaryOperator() = default;
void Reset() const override;
void SetOperand(std::shared_ptr<Node> n);
//Return the only child for the unary operator
std::shared_ptr<Node> Operand() const;
/**
Compute the degree of a node. For trig functions, the degree is 0 if the argument is constant, otherwise it's undefined, and we return nan.
*/
int Degree(std::shared_ptr<Variable> const& v = nullptr) const override;
int Degree(VariableGroup const& vars) const override;
/**
Compute the multidegree with respect to a variable group. This is for homogenization, and testing for homogeneity.
*/
std::vector<int> MultiDegree(VariableGroup const& vars) const override;
void Homogenize(VariableGroup const& vars, std::shared_ptr<Variable> const& homvar) override;
bool IsHomogeneous(std::shared_ptr<Variable> const& v = nullptr) const override;
/**
Check for homogeneity, with respect to a variable group.
*/
bool IsHomogeneous(VariableGroup const& vars) const override;
/**
Change the precision of this variable-precision tree node.
\param prec the number of digits to change precision to.
*/
void precision(unsigned int prec) const override;
protected:
//Stores the single child of the unary operator
std::shared_ptr<Node> operand_;
UnaryOperator(){}
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Operator>(*this);
ar & operand_;
}
};
/**
\brief Abstract interface for n-ary Operator types.
This class is an interface for all n-ary operators, such as summation and multiplication.
Operands of the operator are stored in a vector and methods to add and access operands are available
in this interface.
*/
class NaryOperator : public virtual Operator
{
public:
virtual ~NaryOperator() = default;
void Reset() const override;
// Add an operand onto the container for this operator
virtual void AddOperand(std::shared_ptr<Node> n);
size_t NumOperands() const;
inline auto const& Operands() const{
return operands_;
}
std::shared_ptr<Node> FirstOperand() const;
/**
Change the precision of this variable-precision tree node.
\param prec the number of digits to change precision to.
*/
void precision(unsigned int prec) const override;
protected:
//Stores all children for this operator node.
//This is an NaryOperator and can have any number of children.
std::vector< std::shared_ptr<Node> > operands_;
// constructor is protected to help prevent instantiating empty operators
NaryOperator(){}
private:
virtual void PrecisionChangeSpecific(unsigned prec) const;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Operator>(*this);
ar & operands_;
}
};
} // re: namespace node
} // re: namespace bertini
#endif

View File

@@ -0,0 +1,525 @@
//This file is part of Bertini 2.
//
//trig.hpp 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.
//
//trig.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with trig.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
// silviana amethyst, university of wisconsin-eau claire
//
//
//
// trig.hpp: Declares the trigonometric operator classes.
/**
\file trig.hpp
\brief Provides the abstract TrigOperator, and the concrete types such as SinOperator.
*/
#ifndef BERTINI_TRIGONOMETRIC_OPERATOR_HPP
#define BERTINI_TRIGONOMETRIC_OPERATOR_HPP
#include "bertini2/function_tree/operators/operator.hpp"
#include "bertini2/function_tree/operators/arithmetic.hpp"
namespace bertini {
namespace node{
/**
\brief Abstract class for trigonometric Operator types.
Abstract class for trigonometric Operator types.
*/
class TrigOperator: public virtual UnaryOperator
{
public:
BERTINI_DEFAULT_VISITABLE()
TrigOperator(const std::shared_ptr<Node> & N) : UnaryOperator(N)
{};
virtual ~TrigOperator() = default;
/**
Compute the degree with respect to a single variable.
For transcendental functions, the degree is 0 if the argument is constant, otherwise it's undefined, and we return -1.
*/
int Degree(std::shared_ptr<Variable> const& v = nullptr) const override;
protected:
TrigOperator(){}
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<UnaryOperator>(*this);
}
};
/**
\brief Provides the sine Operator.
This class represents the sine function. FreshEval method
is defined for sine and takes the sine of the child node.
*/
class SinOperator : public virtual TrigOperator, public virtual EnableSharedFromThisVirtual<SinOperator>
{
public:
BERTINI_DEFAULT_VISITABLE()
unsigned EliminateZeros() override;
unsigned EliminateOnes() override;
template<typename... Ts>
static
std::shared_ptr<SinOperator> Make(Ts&& ...ts){
return std::shared_ptr<SinOperator>( new SinOperator(ts...) );
}
private:
SinOperator(const std::shared_ptr<Node> & N) : TrigOperator(N), UnaryOperator(N)
{};
public:
void print(std::ostream & target) const override;
/**
Differentiates the sine function.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
virtual ~SinOperator() = default;
protected:
// Specific implementation of FreshEval for negate.
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
private:
SinOperator() = default;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<TrigOperator>(*this);
}
};
/**
\brief Provides the inverse sine Operator.
This class represents the inverse sine function. FreshEval method
is defined for arcsine and takes the sine of the child node.
*/
class ArcSinOperator : public virtual TrigOperator, public virtual EnableSharedFromThisVirtual<ArcSinOperator>
{
public:
BERTINI_DEFAULT_VISITABLE()
unsigned EliminateZeros() override;
unsigned EliminateOnes() override;
template<typename... Ts>
static
std::shared_ptr<ArcSinOperator> Make(Ts&& ...ts){
return std::shared_ptr<ArcSinOperator>( new ArcSinOperator(ts...) );
}
private:
ArcSinOperator(const std::shared_ptr<Node> & N) : TrigOperator(N), UnaryOperator(N)
{};
public:
void print(std::ostream & target) const override;
/**
Differentiates the sine function.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
virtual ~ArcSinOperator() = default;
protected:
// Specific implementation of FreshEval for negate.
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
private:
ArcSinOperator() = default;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<TrigOperator>(*this);
}
};
/**
\brief Provides the cosine Operator.
This class represents the cosine function. FreshEval method
is defined for cosine and takes the cosine of the child node.
*/
class CosOperator : public virtual TrigOperator, public virtual EnableSharedFromThisVirtual<CosOperator>
{
public:
BERTINI_DEFAULT_VISITABLE()
unsigned EliminateZeros() override;
unsigned EliminateOnes() override;
template<typename... Ts>
static
std::shared_ptr<CosOperator> Make(Ts&& ...ts){
return std::shared_ptr<CosOperator>( new CosOperator(ts...) );
}
private:
CosOperator(const std::shared_ptr<Node> & N) : TrigOperator(N), UnaryOperator(N)
{};
public:
void print(std::ostream & target) const override;
/**
Differentiates the cosine function.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
virtual ~CosOperator() = default;
protected:
// Specific implementation of FreshEval for negate.
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
private:
CosOperator() = default;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<TrigOperator>(*this);
}
};
/**
\brief Provides the arc cosine Operator.
This class represents the inverse cosine function. FreshEval method
is defined for arccosine and takes the arccosine of the child node.
*/
class ArcCosOperator : public virtual TrigOperator, public virtual EnableSharedFromThisVirtual<ArcCosOperator>
{
public:
BERTINI_DEFAULT_VISITABLE()
unsigned EliminateZeros() override;
unsigned EliminateOnes() override;
template<typename... Ts>
static
std::shared_ptr<ArcCosOperator> Make(Ts&& ...ts){
return std::shared_ptr<ArcCosOperator>( new ArcCosOperator(ts...) );
}
private:
ArcCosOperator(const std::shared_ptr<Node> & N) : TrigOperator(N), UnaryOperator(N)
{};
public:
void print(std::ostream & target) const override;
/**
Differentiates the cosine function.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
virtual ~ArcCosOperator() = default;
protected:
// Specific implementation of FreshEval for negate.
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
private:
ArcCosOperator() = default;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<TrigOperator>(*this);
}
};
/**
\brief Provides the tangent Operator.
This class represents the tangent function. FreshEval method
is defined for tangent and takes the tangent of the child node.
*/
class TanOperator : public virtual TrigOperator, public virtual EnableSharedFromThisVirtual<TanOperator>
{
public:
BERTINI_DEFAULT_VISITABLE()
unsigned EliminateZeros() override;
unsigned EliminateOnes() override;
template<typename... Ts>
static
std::shared_ptr<TanOperator> Make(Ts&& ...ts){
return std::shared_ptr<TanOperator>( new TanOperator(ts...) );
}
private:
TanOperator(const std::shared_ptr<Node> & N) : TrigOperator(N), UnaryOperator(N)
{};
public:
void print(std::ostream & target) const override;
/**
Differentiates the tangent function.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
virtual ~TanOperator() = default;
protected:
// Specific implementation of FreshEval for negate.
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
private:
TanOperator() = default;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<TrigOperator>(*this);
}
};
/**
\brief Provides the inverse tangent Operator.
This class represents the inverse tangent function. FreshEval method
is defined for arctangent and takes the arc tangent of the child node.
*/
class ArcTanOperator : public virtual TrigOperator, public virtual EnableSharedFromThisVirtual<ArcTanOperator>
{
public:
BERTINI_DEFAULT_VISITABLE()
unsigned EliminateZeros() override;
unsigned EliminateOnes() override;
template<typename... Ts>
static
std::shared_ptr<ArcTanOperator> Make(Ts&& ...ts){
return std::shared_ptr<ArcTanOperator>( new ArcTanOperator(ts...) );
}
private:
ArcTanOperator(const std::shared_ptr<Node> & N) : TrigOperator(N), UnaryOperator(N)
{};
public:
void print(std::ostream & target) const override;
/**
Differentiates the tangent function.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
virtual ~ArcTanOperator() = default;
protected:
// Specific implementation of FreshEval for arctangent.
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
private:
ArcTanOperator() = default;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<TrigOperator>(*this);
}
};
// begin the overload of operators
inline std::shared_ptr<Node> sin(const std::shared_ptr<Node> & N)
{
return SinOperator::Make(N);
}
inline std::shared_ptr<Node> asin(const std::shared_ptr<Node> & N)
{
return ArcSinOperator::Make(N);
}
inline std::shared_ptr<Node> cos(const std::shared_ptr<Node> & N)
{
return CosOperator::Make(N);
}
inline std::shared_ptr<Node> acos(const std::shared_ptr<Node> & N)
{
return ArcCosOperator::Make(N);
}
inline std::shared_ptr<Node> tan(const std::shared_ptr<Node> & N)
{
return TanOperator::Make(N);
}
inline std::shared_ptr<Node> atan(const std::shared_ptr<Node> & N)
{
return ArcTanOperator::Make(N);
}
} // re: namespace node
} // re: namespace bertini
#endif

View File

@@ -0,0 +1,274 @@
//This file is part of Bertini 2.
//
//bertini2/function_tree/roots/function.hpp 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.
//
//bertini2/function_tree/roots/function.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/function_tree/roots/function.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
// silviana amethyst, university of wisconsin-eau claire
//
// silviana amethyst
// UWEC
// Spring 2018
//
// Created by Collins, James B. on 4/30/15.
//
//
// bertini2/function_tree/roots/function.hpp: Declares the class Function.
/**
\file bertini2/function_tree/roots/function.hpp
\brief Provides the Function Node type, a NamedSymbol.
*/
#ifndef BERTINI_FUNCTION_NODE_HPP
#define BERTINI_FUNCTION_NODE_HPP
#include "bertini2/function_tree/symbols/symbol.hpp"
namespace bertini {
namespace node{
class Handle : public virtual NamedSymbol
{
BERTINI_DEFAULT_VISITABLE()
public:
/**
overridden function for piping the tree to an output stream.
*/
void print(std::ostream & target) const override;
Handle(std::string const& new_name);
/**
Constructor defines entry node at construct time.
*/
Handle(const std::shared_ptr<Node> & entry, std::string const& name = "unnamed_function");
protected:
Handle() = default;
public:
/**
Add a child onto the container for this operator
*/
void SetRoot(std::shared_ptr<Node> const& entry);
/**
throws a runtime error if the root node is nullptr
*/
void EnsureNotEmpty() const;
/**
The function which flips the fresh eval bit back to fresh.
*/
void Reset() const override;
/**
Get the pointer to the entry node for this function.
*/
const std::shared_ptr<Node>& EntryNode() const;
/**
Calls Differentiate on the entry node and returns differentiated entry node.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
/**
Compute the degree of a node. For functions, the degree is the degree of the entry node.
*/
int Degree(std::shared_ptr<Variable> const& v = nullptr) const override;
int Degree(VariableGroup const& vars) const override;
/**
Compute the multidegree with respect to a variable group. This is for homogenization, and testing for homogeneity.
*/
std::vector<int> MultiDegree(VariableGroup const& vars) const override;
void Homogenize(VariableGroup const& vars, std::shared_ptr<Variable> const& homvar) override;
bool IsHomogeneous(std::shared_ptr<Variable> const& v = nullptr) const override;
/**
Check for homogeneity, with respect to a variable group.
*/
bool IsHomogeneous(VariableGroup const& vars) const override;
/**
Change the precision of this variable-precision tree node.
\param prec the number of digits to change precision to.
*/
void precision(unsigned int prec) const override;
protected:
/**
Calls FreshEval on the entry node to the tree.
*/
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
/**
Calls FreshEval in place on the entry node to the tree.
*/
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
/**
Calls FreshEval on the entry node to the tree.
*/
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
/**
Calls FreshEval in place on the entry node to the tree.
*/
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
std::shared_ptr<Node> entry_node_ = nullptr;
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<NamedSymbol>(*this);
ar & entry_node_;
}
}; // class Function
}} // namespaces
namespace bertini {
namespace node{
/**
\brief Formal entry point into an expression tree.
This class defines a function. It stores the entry node for a particular functions tree.
*/
class Function : public virtual Handle, public virtual EnableSharedFromThisVirtual<Function>
{
public:
BERTINI_DEFAULT_VISITABLE()
template<typename... Ts>
static
std::shared_ptr<Function> Make(Ts&& ...ts){
return std::shared_ptr<Function>( new Function(ts...) );
}
template<typename... Ts>
static
std::shared_ptr<Function> MakeInPlace(Function* ptr, Ts&& ...ts){
return std::shared_ptr<Function>( new(ptr) Function(ts...) );
}
private:
Function(std::string const& new_name);
/**
Constructor defines entry node at construct time.
*/
Function(const std::shared_ptr<Node> & entry, std::string const& name = "unnamed_function");
public:
virtual ~Function() = default;
protected:
Function() = default;
private:
friend class boost::serialization::access;
// template<class Archive> friend void boost::serialization::load_construct_data(Archive & ar, Function * t, const unsigned int file_version);
// template<class Archive> friend void boost::serialization::save_construct_data(Archive & ar, const Function * t, const unsigned int file_version);
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Handle>(*this);
}
};
} // re: namespace node
} // re: namespace bertini
#endif

View File

@@ -0,0 +1,131 @@
//This file is part of Bertini 2.
//
//jacobian.hpp 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.
//
//jacobian.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with jacobian.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
// silviana amethyst, university of wisconsin-eau claire
//
// silviana amethyst
// UWEC
// Spring 2018
//
// Created by Collins, James B. on 6/11/15.
//
//
// jacobian.hpp: Declares the class Jacobian.
/**
\file jacobian.hpp
\brief Provides the Jacobian node type.
*/
#ifndef BERTINI_JACOBIAN_NODE_HPP
#define BERTINI_JACOBIAN_NODE_HPP
#include "bertini2/function_tree/node.hpp"
#include "bertini2/function_tree/roots/function.hpp"
#include "bertini2/function_tree/symbols/variable.hpp"
namespace bertini {
namespace node{
/**
\brief Defines the entry point into a Jacobian tree.
This class defines a Jacobian tree. It stores the entry node for a particular functions tree.
*/
class Jacobian : public virtual Handle, public virtual EnableSharedFromThisVirtual<Jacobian>
{
friend detail::FreshEvalSelector<dbl>;
friend detail::FreshEvalSelector<mpfr_complex>;
public:
BERTINI_DEFAULT_VISITABLE()
template<typename... Ts>
static
std::shared_ptr<Jacobian> Make(Ts&& ...ts){
return std::shared_ptr<Jacobian>( new Jacobian(ts...) );
}
private:
/**
*/
Jacobian(const std::shared_ptr<Node> & entry);
public:
/**
Jacobians must be evaluated with EvalJ, so that when current_diff_variable changes
the Jacobian is reevaluated.
*/
template<typename T>
T Eval(std::shared_ptr<Variable> const& diff_variable = nullptr) const = delete;
// Evaluate the node. If flag false, just return value, if flag true
// run the specific FreshEval of the node, then set flag to false.
template<typename T>
T EvalJ(std::shared_ptr<Variable> const& diff_variable) const;
// Evaluate the node. If flag false, just return value, if flag true
// run the specific FreshEval of the node, then set flag to false.
template<typename T>
void EvalJInPlace(T& eval_value, std::shared_ptr<Variable> const& diff_variable) const;
virtual ~Jacobian() = default;
/**
\brief Default construction of a Jacobian node is forbidden
*/
Jacobian() = default;
private:
mutable std::shared_ptr<Variable> current_diff_variable_;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Handle>(*this);
}
};
} // re: namespace node
} // re: namespace bertini
#endif

View File

@@ -0,0 +1,48 @@
//This file is part of Bertini 2.
//
//b2/core/include/bertini2/function_tree/simplify.hpp 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.
//
//b2/core/include/bertini2/function_tree/simplify.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with b2/core/include/bertini2/function_tree/simplify.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2017-2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
/**
\file include/bertini2/function_tree/simplify.hpp
\brief simplification methods for nodal functions
General methods exploting polymorphism, for simplifying a Node, and all subnodes
*/
#ifndef BERTINI_FUNCTION_TREE_SIMPLIFY_HPP
#define BERTINI_FUNCTION_TREE_SIMPLIFY_HPP
#pragma once
#include "bertini2/function_tree/node.hpp"
namespace bertini {
unsigned Simplify(std::shared_ptr<bertini::node::Node> const& n);
} // namespace bertini
#endif //include guards

View File

@@ -0,0 +1,171 @@
//This file is part of Bertini 2.
//
//differential.hpp 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.
//
//differential.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with differential.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
// silviana amethyst, university of wisconsin-eau claire
//
// Created by Collins, James B. on 4/30/15.
//
//
// differential.hpp: Declares the class SpecialNumber.
/**
\file differential.hpp
\brief Provides the differential Node class.
*/
#ifndef BERTINI_NODE_DIFFERENTIAL_HPP
#define BERTINI_NODE_DIFFERENTIAL_HPP
#include <memory>
#include "bertini2/function_tree/node.hpp"
#include "bertini2/function_tree/symbols/symbol.hpp"
#include "bertini2/function_tree/symbols/number.hpp"
namespace bertini {
namespace node{
class Variable;
/**
\brief Provides the differential type for differentiation of expression trees.
This class represents differentials. These are produced in the course of differentiation of a non-constant expression tree.
*/
class Differential : public virtual NamedSymbol, public virtual EnableSharedFromThisVirtual<Differential>
{
public:
BERTINI_DEFAULT_VISITABLE()
template<typename... Ts>
static
std::shared_ptr<Differential> Make(Ts&& ...ts){
return std::shared_ptr<Differential>( new Differential(ts...) );
}
private:
/**
Input shared_ptr to a Variable.
*/
Differential(std::shared_ptr<const Variable> diff_variable, std::string var_name);
public:
void Reset() const override;
const std::shared_ptr<const Variable>& GetVariable() const;
void print(std::ostream & target) const override;
/**
Differentiates a number.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
virtual ~Differential() = default;
/**
Compute the degree with respect to a single variable. For differentials, the degree is 0.
*/
int Degree(std::shared_ptr<Variable> const& v = nullptr) const override;
int Degree(VariableGroup const& vars) const override;
std::vector<int> MultiDegree(VariableGroup const& vars) const override;
void Homogenize(VariableGroup const& vars, std::shared_ptr<Variable> const& homvar) override;
bool IsHomogeneous(std::shared_ptr<Variable> const& v = nullptr) const override;
/**
Check for homogeneity, with respect to a variable group.
*/
bool IsHomogeneous(VariableGroup const& vars) const override;
/**
Change the precision of this variable-precision tree node.
\param prec the number of digits to change precision to.
*/
void precision(unsigned int prec) const override;
protected:
// This should never be called for a Differential. Only for Jacobians.
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
private:
Differential() = default;
std::shared_ptr<const Variable> differential_variable_;
friend class boost::serialization::access;
template<class Archive>
void save(Archive & ar, const unsigned int version) const
{
ar & boost::serialization::base_object<NamedSymbol>(*this);
ar & differential_variable_;
// ar & const_cast<std::shared_ptr<const Variable> >(differential_variable_);
}
template<class Archive>
void load(Archive & ar, const unsigned int version)
{
ar & boost::serialization::base_object<NamedSymbol>(*this);
ar & std::const_pointer_cast<Variable>(differential_variable_);
}
// BOOST_SERIALIZATION_SPLIT_MEMBER()
};
} // re: namespace node
} // re: namespace bertini
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,427 @@
//This file is part of Bertini 2.
//
//number.hpp 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.
//
//number.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with number.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2023 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
//
// silviana amethyst
// University of Wisconsin - Eau Claire
//
// Created by Collins, James B. on 4/30/15.
//
//
// number.hpp: Declares the class Number.
/**
\file number.hpp
\brief Provides the Number Node types, including Rational, Float, and Integer
*/
#ifndef BERTINI_NODE_NUMBER_HPP
#define BERTINI_NODE_NUMBER_HPP
#include "bertini2/function_tree/symbols/symbol.hpp"
namespace bertini {
namespace node{
/**
\brief Abstract Number type from which other Numbers derive.
This class represents constant leaves to a function tree. FreshEval simply returns
the value of the constant.
*/
class Number : public virtual Symbol
{
public:
virtual ~Number() = default;
void Reset() const override;
/**
\brief Get the degree of this node.
The degree of a number is always 0. It's a number.
*/
inline
int Degree(std::shared_ptr<Variable> const& v = nullptr) const override
{
return 0;
}
/**
\brief Get the degree of this node.
The degree of a number is always 0. It's a number.
*/
inline
int Degree(VariableGroup const& vars) const override
{
return 0;
}
/**
\brief Get the multidegree of this node.
The degree of a number is always 0. It's a number.
*/
inline
std::vector<int> MultiDegree(VariableGroup const& vars) const override
{
return std::vector<int>(vars.size(), 0);
}
/**
\brief Homogenize this node.
Homogenization of a number is a trivial operation. Don't do anything.
*/
void Homogenize(VariableGroup const& vars, std::shared_ptr<Variable> const& homvar) override
{
}
/**
\brief Is this node homogeneous?
Numbers are always homogeneous
*/
bool IsHomogeneous(std::shared_ptr<Variable> const& v = nullptr) const override
{
return true;
}
/**
Check for homogeneity, with respect to a variable group.
*/
bool IsHomogeneous(VariableGroup const& vars) const override
{
return true;
}
/**
Change the precision of this variable-precision tree node.
\param prec the number of digits to change precision to.
*/
void precision(unsigned int prec) const override;
/**
\brief Differentiate a number.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
protected:
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Symbol>(*this);
}
};
/**
\brief Signed real Integer storage in an expression tree.
Signed real Integer storage in an expression tree. Consider using a Rational type.
*/
class Integer : public virtual Number, public virtual EnableSharedFromThisVirtual<Integer>
{
public:
BERTINI_DEFAULT_VISITABLE()
Integer(Integer const&) = default;
~Integer() = default;
void print(std::ostream & target) const override;
template<typename... Ts>
static
std::shared_ptr<Integer> Make(Ts&& ...ts){
return std::shared_ptr<Integer>( new Integer(ts...) );
}
private:
// https://stackoverflow.com/questions/33933550/exception-bad-weak-ptr-while-shared-from-this
// struct MakeConstructorPublic;
explicit
Integer(int val) : true_value_(val)
{}
explicit
Integer(mpz_int val) : true_value_(val)
{}
explicit
Integer(std::string const& val) : true_value_(val)
{}
// Return value of constant
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpz_int true_value_;
friend class boost::serialization::access;
Integer() = default;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Number>(*this);
ar & true_value_;
}
};
// struct Integer::MakeConstructorPublic : public Integer {
// template <typename... Args>
// MakeConstructorPublic(Args&& ...args) : Integer(std::forward<Args>(args)...)
// {}
// };
/**
\brief Number type for storing floating point numbers within an expression tree.
Number type for storing floating point numbers within an expression tree. The number passed in at construct time is stored as the true value, and evaluation down or up samples from this 'true value'. Consider using a Rational or Integer if possible.
*/
class Float : public virtual Number, public virtual EnableSharedFromThisVirtual<Float>
{
public:
BERTINI_DEFAULT_VISITABLE()
~Float() = default;
void print(std::ostream & target) const override;
template<typename... Ts>
static
std::shared_ptr<Float> Make(Ts&& ...ts){
return std::shared_ptr<Float>( new Float(ts...) );
}
private:
explicit
Float(mpfr_complex const& val) : highest_precision_value_(val)
{}
explicit
Float(mpfr_float const& rval, mpfr_float const& ival = 0) : highest_precision_value_(rval,ival)
{}
explicit
Float(std::string const& val) : highest_precision_value_(val)
{}
explicit
Float(std::string const& rval, std::string const& ival) : highest_precision_value_(rval,ival)
{}
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex highest_precision_value_;
friend class boost::serialization::access;
Float() = default;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Number>(*this);
ar & const_cast<mpfr_complex &>(highest_precision_value_);
}
};
/**
\brief The Rational number type for Bertini2 expression trees.
The Rational number type for Bertini2 expression trees. The `true value' is stored using two mpq_rational numbers from the Boost.Multiprecision library, and the ratio is converted into a double or a mpfr_complex at evaluate time.
*/
class Rational : public virtual Number, public virtual EnableSharedFromThisVirtual<Rational>
{
public:
BERTINI_DEFAULT_VISITABLE()
using mpq_rational = bertini::mpq_rational;
Rational(int, int) = delete;
~Rational() = default;
/**
\brief Get a random complex rational node. Numerator and denominator will have about 50 digits.
\see RandomRat()
*/
template<unsigned long Digits = 50>
static
Rational Rand()
{
return Rational(RandomRat<Digits>(),RandomRat<Digits>());
}
/**
\brief Get a random real rational node. Numerator and denominator will have about 50 digits.
\see RandomRat()
*/
template<int Digits = 50>
static
Rational RandReal()
{
return Rational(RandomRat<Digits>(),0);
}
void print(std::ostream & target) const override;
template<typename... Ts>
static
std::shared_ptr<Rational> Make(Ts&& ...ts){
return std::shared_ptr<Rational>( new Rational(ts...) );
}
private:
explicit
Rational(int val) : true_value_real_(val), true_value_imag_(0)
{}
explicit
Rational(int val_real_numerator, int val_real_denomenator,
int val_imag_numerator, int val_imag_denomenator)
:
true_value_real_(val_real_numerator,val_real_denomenator), true_value_imag_(val_imag_numerator,val_imag_denomenator)
{}
explicit
Rational(std::string val) : true_value_real_(val), true_value_imag_(0)
{}
explicit
Rational(std::string val_real, std::string val_imag) : true_value_real_(val_real), true_value_imag_(val_imag)
{}
explicit
Rational(mpq_rational const& val_real, mpq_rational const& val_imag = 0) : true_value_real_(val_real), true_value_imag_(val_imag)
{}
// Return value of constant
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpq_rational true_value_real_, true_value_imag_;
Rational() = default;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Number>(*this);
ar & const_cast<mpq_rational &>(true_value_real_);
ar & const_cast<mpq_rational &>(true_value_imag_);
}
};
} // re: namespace node
} // re: namespace bertini
#endif

View File

@@ -0,0 +1,198 @@
//This file is part of Bertini 2.
//
//special_number.hpp 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.
//
//special_number.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with special_number.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2023 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
//
// silviana amethyst
// University of Wisconsin - Eau Claire
//
// Created by Collins, James B. on 4/30/15.
//
//
// special_number.hpp: Declares the class SpecialNumber.
/**
\file special_number.hpp
\brief Provides the special numbers \f$\pi\f$, \f$e\f$, 1, 2, 0, as Nodes
*/
#ifndef BERTINI_FUNCTION_TREE_SPECIAL_NUMBER_HPP
#define BERTINI_FUNCTION_TREE_SPECIAL_NUMBER_HPP
#include "bertini2/function_tree/symbols/number.hpp"
#include <cmath>
namespace bertini {
namespace node{
using ::acos;
using ::exp;
namespace special_number{
/**
\brief The number \f$\pi\f$.
The number \f$\pi\f$. Gets its own class because it is such an important number.
*/
class Pi : public virtual Number, public virtual NamedSymbol, public virtual EnableSharedFromThisVirtual<Pi>
{
public:
BERTINI_DEFAULT_VISITABLE()
virtual ~Pi() = default;
template<typename... Ts>
static
std::shared_ptr<Pi> Make(Ts&& ...ts){
return std::shared_ptr<Pi>( new Pi(ts...) );
}
private:
Pi() : NamedSymbol("pi")
{}
// Return value of constant
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Number>(*this);
ar & boost::serialization::base_object<NamedSymbol>(*this);
}
};
/**
\brief The number \f$e\f$.
The number \f$e\f$. Gets its own class because it is such an important number.
*/
class E : public virtual Number, public virtual NamedSymbol, public virtual EnableSharedFromThisVirtual<E>
{
public:
BERTINI_DEFAULT_VISITABLE()
virtual ~E() = default;
template<typename... Ts>
static
std::shared_ptr<E> Make(Ts&& ...ts){
return std::shared_ptr<E>( new E(ts...) );
}
private:
E() : NamedSymbol("e")
{}
// Return value of constant
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Number>(*this);
ar & boost::serialization::base_object<NamedSymbol>(*this);
}
};
} // re: special_number namespace
/**
Construct a shared pointer to \f$\pi\f$.
*/
std::shared_ptr<Node> Pi();
/**
Construct a shared pointer to \f$e\f$.
*/
std::shared_ptr<Node> E();
/**
Construct a shared pointer to \f$i\f$.
*/
std::shared_ptr<Node> I();
/**
Construct a shared pointer to \f$2\f$.
*/
std::shared_ptr<Node> Two();
/**
Construct a shared pointer to \f$1\f$.
*/
std::shared_ptr<Node> One();
/**
Construct a shared pointer to \f$0\f$.
*/
std::shared_ptr<Node> Zero();
} // re: namespace node
} // re: namespace bertini
#endif

View File

@@ -0,0 +1,133 @@
//This file is part of Bertini 2.
//
//symbol.hpp 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.
//
//symbol.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with symbol.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
// silviana amethyst, university of wisconsin-eau claire
//
// Created by Collins, James B. on 4/30/15.
//
//
// symbol.hpp: Declares the class Symbol.
/**
\file symbol.hpp
\brief Defines the abstract Symbol and NamedSymbol classes,
*/
#ifndef BERTINI_FUNCTION_TREE_SYMBOL_HPP
#define BERTINI_FUNCTION_TREE_SYMBOL_HPP
#include "bertini2/function_tree/node.hpp"
namespace bertini {
namespace node {
/**
\brief Abstract symbol class.
This class is an interface for all non-operators.
*/
class Symbol : public virtual Node
{
public:
virtual ~Symbol() = default;
unsigned EliminateZeros() override;
unsigned EliminateOnes() override;
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Node>(*this);
}
};
/**
\brief Symbols which have names are named symbols.
Symbols which have names are named symbols.
*/
class NamedSymbol : public virtual Symbol
{
public:
/**
Get the name of the named symbol
*/
const std::string & name() const;
/**
Get the name of the named symbol
*/
void name(const std::string & new_name);
/**
Parameterized constructor, sets the name of the symbol
*/
NamedSymbol(const std::string & new_name);
void print(std::ostream& target) const override;
virtual ~NamedSymbol() = default;
protected:
NamedSymbol() = default;
std::string name_;
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<Symbol>(*this);
ar & name_;
}
};
} // re: namespace node
} // re: namespace bertini
#endif

View File

@@ -0,0 +1,176 @@
//This file is part of Bertini 2.
//
//include/bertini2/function_tree/symbols/variable.hpp 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.
//
//include/bertini2/function_tree/symbols/variable.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with include/bertini2/function_tree/symbols/variable.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2023 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// James Collins
// West Texas A&M University
// Spring, Summer 2015
//
// silviana amethyst, university of wisconsin-eau claire
//
// Created by Collins, James B. on 4/30/15.
//
//
// include/bertini2/function_tree/symbols/variable.hpp: Declares the class Variable.
/**
\file include/bertini2/function_tree/symbols/variable.hpp
\brief Provides the Variable Node class.
*/
#ifndef BERTINI_FUNCTION_TREE_VARIABLE_HPP
#define BERTINI_FUNCTION_TREE_VARIABLE_HPP
#include "bertini2/function_tree/symbols/symbol.hpp"
#include "bertini2/function_tree/symbols/differential.hpp"
namespace bertini {
namespace node{
/**
\brief Represents variable leaves in the function tree.
This class represents variable leaves in the function tree. FreshEval returns
the current value of the variable.
When differentiated, produces a differential referring to it.
*/
class Variable : public virtual NamedSymbol, public virtual EnableSharedFromThisVirtual<Variable>
{
public:
BERTINI_DEFAULT_VISITABLE()
template<typename... Ts>
static
std::shared_ptr<Variable> Make(Ts&& ...ts){
return std::shared_ptr<Variable>( new Variable(ts...) );
}
private:
Variable(std::string new_name);
public:
virtual ~Variable() = default;
explicit operator std::string(){return name();}
// This sets the value for the variable
template <typename T>
void set_current_value(T const& val);
/**
\brief Changes the value of the variable to be not-a-number.
*/
template <typename T>
void SetToNan();
/**
\brief Changes the value of the variable to be a random complex number.
*/
template <typename T>
void SetToRand();
/**
\brief Changes the value of the variable to be a random complex number, of magnitude 1.
*/
template <typename T>
void SetToRandUnit();
/**
Differentiates a variable.
*/
std::shared_ptr<Node> Differentiate(std::shared_ptr<Variable> const& v = nullptr) const override;
void Reset() const override;
/**
Compute the degree with respect to a single variable.
If this is the variable, then the degree is 1. Otherwise, 0.
*/
int Degree(std::shared_ptr<Variable> const& v = nullptr) const override;
int Degree(VariableGroup const& vars) const override;
std::vector<int> MultiDegree(VariableGroup const& vars) const override;
void Homogenize(VariableGroup const& vars, std::shared_ptr<Variable> const& homvar) override;
bool IsHomogeneous(std::shared_ptr<Variable> const& v = nullptr) const override;
/**
Check for homogeneity, with respect to a variable group.
*/
bool IsHomogeneous(VariableGroup const& vars) const override;
/**
Change the precision of this variable-precision tree node.
\param prec the number of digits to change precision to.
*/
void precision(unsigned int prec) const override;
protected:
// Return current value of the variable.
dbl FreshEval_d(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_d(dbl& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
mpfr_complex FreshEval_mp(std::shared_ptr<Variable> const& diff_variable) const override;
void FreshEval_mp(mpfr_complex& evaluation_value, std::shared_ptr<Variable> const& diff_variable) const override;
Variable();
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & boost::serialization::base_object<NamedSymbol>(*this);
}
};
} // re: namespace node
} // re: namespace bertini
#endif

View File

@@ -0,0 +1,48 @@
//This file is part of Bertini 2.
//
//have_bertini.hpp 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.
//
//have_bertini.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with have_bertini.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, University of Wisconsin Eau Claire
/**
\file have_bertini.hpp
\brief Declares a function that one can use to test whether Bertini2 exists in library form.
*/
#ifndef BERTINI2_HAVE_BERTINI_HPP
#define BERTINI2_HAVE_BERTINI_HPP
/**
\brief Check for presence of the Bertini 2 library.
This function's sole purpose is for checking for the presence of the Bertini 2 library.
\return The character 'y'.
*/
extern "C"
char HaveBertini2();
#endif

View File

@@ -0,0 +1,100 @@
//This file is part of Bertini 2.
//
//bertini2/io/file_utilities.hpp 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.
//
//bertini2/io/file_utilities.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/io/file_utilities.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
/**
\file bertini2/io/file_utilities.hpp
\brief Provides the file_utilities screens for bertini2.
*/
#pragma once
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
namespace bertini{
namespace fs = boost::filesystem;
using Path = fs::path;
using ifstream = std::ifstream;
/**
\brief Try to open a file, and throw if it doesn't exist, or is a directory.
*/
inline
void OpenInFileThrowIfFail(ifstream & in,
Path const& input_path)
{
using namespace fs;
try{
if (exists(input_path))
{
if (is_directory(input_path))
{
std::stringstream err_msg;
err_msg << "attempting to open file but is a directory, of name '" << input_path.string() << "'";
throw std::runtime_error(err_msg.str());
}
else
{
in.open(input_path.c_str());
if (!in.is_open())
{
std::stringstream err_msg;
err_msg << "file '" << input_path.string() << "' hypothetically exists, but failed to open correctly";
throw std::runtime_error(err_msg.str());
}
}
}
else
{
std::stringstream err_msg;
err_msg << "attempting to open file which doesn't exist, of name '" << input_path.string() << "'";
throw std::runtime_error(err_msg.str());
}
}
catch (const filesystem_error& ex)
{
std::stringstream err_msg;
err_msg << "boost::filesystem throw while attempting to open file '" << input_path.string() << "': '" << ex.what() << "'";
throw std::runtime_error(err_msg.str());
}
}
/**
\brief Read an entire file into a string.
\return The string, now contaning the file.
\param input_path The path to the file.
*/
inline
std::string FileToString(Path const& input_path)
{
ifstream infile;
OpenInFileThrowIfFail(infile, input_path);
return std::string ( std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>() );
}
}

View File

@@ -0,0 +1,232 @@
//This file is part of Bertini 2.
//
//bertini2/io/generators.hpp 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.
//
//bertini2/io/generators.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/io/generators.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
/**
\file bertini2/io/generators.hpp
\brief Provides the generators for bertini2.
*/
#pragma once
#include "bertini2/mpfr_complex.hpp"
#include "bertini2/eigen_extensions.hpp"
#include <boost/math/special_functions/modf.hpp>
BOOST_MATH_STD_USING
#include <boost/fusion/adapted.hpp>
#include <boost/fusion/include/adapted.hpp>
#define BOOST_SPIRIT_USE_PHOENIX_V3 1
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/phoenix/core.hpp>
#include <boost/phoenix/operator.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
// BOOST_FUSION_ADAPT_ADT(
// std::complex<double>,
// (bool, bool, obj.imag() != 0, /**/)
// (double, double, obj.real(), /**/)
// (double, double, obj.imag(), /**/)
// )
// BOOST_FUSION_ADAPT_ADT(
// bertini::mpfr_complex,
// (bool, bool, obj.imag() != 0, /**/)
// (bertini::mpfr_float, bertini::mpfr_float, obj.real(), /**/)
// (bertini::mpfr_float, bertini::mpfr_float, obj.imag(), /**/)
// )
namespace bertini{
namespace generators{
namespace karma = boost::spirit::karma;
template <typename Num>
struct BertiniNumPolicy : public karma::real_policies<Num>
{
// we want the numbers always to be in scientific format
static int floatfield(Num n) { return std::ios_base::scientific; }
static unsigned int precision(Num) {
return std::numeric_limits<Num>::max_digits10;
}
};
template<>
struct BertiniNumPolicy<mpfr_float> : public karma::real_policies<mpfr_float>
{
// we want the numbers always to be in scientific format
static int floatfield(mpfr_float n) { return std::ios_base::scientific; }
static unsigned int precision(mpfr_float const& x) {
return x.precision();
}
};
template<typename Num>
using FullPrec = boost::spirit::karma::real_generator<Num, BertiniNumPolicy<Num> >;
FullPrec<double> const full_prec_d = FullPrec<double>();
FullPrec<mpfr_float> const full_prec_mp = FullPrec<mpfr_float>();
struct Classic{
template <typename OutputIterator>
static bool generate(OutputIterator sink, double const& c)
{
using boost::spirit::karma::omit;
using boost::spirit::karma::generate;
return generate(sink,
// Begin grammar
(
full_prec_d << " " << full_prec_d
),
// End grammar
c, 0 // Data to output
);
}
template <typename OutputIterator>
static bool generate(OutputIterator sink, std::complex<double> const& c)
{
using boost::spirit::karma::omit;
using boost::spirit::karma::generate;
return generate(sink,
// Begin grammar
(
full_prec_d << " " << full_prec_d
),
// End grammar
c.real(), c.imag() // Data to output
);
}
template <typename OutputIterator>
static bool generate(OutputIterator sink, mpfr_float const& c)
{
using boost::spirit::karma::omit;
using boost::spirit::karma::generate;
return generate(sink,
// Begin grammar
(
boost::spirit::karma::string
),
// End grammar
c.str() // Data to output
);
}
template <typename OutputIterator>
static bool generate(OutputIterator sink, mpfr_complex const& c)
{
using boost::spirit::karma::omit;
using boost::spirit::karma::generate;
return generate(sink,
// Begin grammar
(
boost::spirit::karma::string << " " << boost::spirit::karma::string
),
// End grammar
c.real().str(), c.imag().str() // Data to output
);
}
template <typename OutputIterator, typename T>
static bool generate(OutputIterator sink, Vec<T> const& c)
{
auto s = c.size();
for (decltype(s) ii=0; ii<s; ++ii)
{
bool b = generate(sink, c(ii));
if (!b)
return b;
boost::spirit::karma::generate(sink, (boost::spirit::karma::char_), '\n');
}
return true;
}
};
struct CPlusPlus{
template <typename OutputIterator>
static bool generate(OutputIterator sink, std::complex<double> const& c)
{
using boost::spirit::karma::omit;
using boost::spirit::karma::generate;
return generate(sink,
// Begin grammar
(
!full_prec_d(0.0) << '(' << full_prec_d << ", " << full_prec_d << ')'
| omit[full_prec_d] << full_prec_d
),
// End grammar
c.imag(), c.real(), c.imag() // Data to output
);
}
};
}
}

View File

@@ -0,0 +1,38 @@
//This file is part of Bertini 2.
//
//bertini2/io/parsing.hpp 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.
//
//bertini2/io/parsing.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/io/parsing.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2021 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
// individual authors of this file include:
// silviana amethyst, university of wisconsin-eau claire
/**
\file bertini2/io/parsing.hpp
\brief A collective include file for parsing utilities
*/
#pragma once
#include "bertini2/io/parsing/classic_utilities.hpp"
#include "bertini2/io/parsing/function_parsers.hpp"
#include "bertini2/io/parsing/number_parsers.hpp"
#include "bertini2/io/parsing/settings_parsers.hpp"
#include "bertini2/io/parsing/system_parsers.hpp"

View File

@@ -0,0 +1,430 @@
//This file is part of Bertini 2.
//
//bertini2/io/parsers.hpp 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.
//
//bertini2/io/parsing/classic_utilities.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/io/parsing/classic_utilities.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2017 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
/**
\file bertini2/io/parsing/classic_utilities.hpp
\brief Provides utility functions for parsing classic bertini input files.
*/
#pragma once
#include "bertini2/io/parsing/qi_files.hpp"
#include "bertini2/io/file_utilities.hpp"
namespace bertini {
namespace parsing {
namespace classic {
namespace qi = ::boost::spirit::qi;
namespace ascii = ::boost::spirit::ascii;
/**
\class SplitInputFile
\brief Storage class for input file that splits up the config portion from the input portion.
## Use
SplitFileInputConfig parser return an instance of this class. The user can then parse the config and input portions separately using the appropriate parser.
*/
class SplitInputFile
{
public:
std::string Config() const
{
return config_;
}
std::string Input() const
{
return input_;
}
bool Readable() const
{
return readable_;
}
void SetInput(std::string new_input)
{
input_ = new_input;
}
void SetConfig(std::string new_config)
{
config_ = new_config;
}
void SetConfigInput(std::string c, std::string i)
{
config_ = c;
input_ = i;
}
void SetReadable(bool read)
{
readable_ = read;
}
// void StripComments()
// {
// std::string::const_iterator iter = config_.begin();
// std::string::const_iterator end = config_.end();
//
// CommentStripper<std::string::const_iterator> S;
//
// phrase_parse(iter, end, S,boost::spirit::ascii::space, config_);
//
// iter = input_.begin();
// end = input_.end();
//
// phrase_parse(iter, end, S,boost::spirit::ascii::space, input_);
// }
friend std::ostream& operator<<(std::ostream & out, SplitInputFile const& printme)
{
out << "--------config-----------\n\n" << printme.Config() << "\n\n-------input--------\n\n" << printme.Input();
return out;
}
private:
std::string config_;
std::string input_;
bool readable_ = true; //Input file can be split accurately
}; //re: SplitInputFile class
/**
Qi Parser object for parsing text into the SplitInputfile class. This ensures we can provide backwards compatibility with Bertini Classic input files.
To use this parser, construct an object of its type, then use it to parse.
\code
System sys;
std::string str = "variable_group x, y, z; \nfunction f1, f2;\n f1 = x*y*z;\n f2 = x+y+z;\n";
std::string::const_iterator iter = str.begin();
std::string::const_iterator end = str.end();
bertini::SystemParser<std::string::const_iterator> S;
bool s = phrase_parse(iter, end, S,boost::spirit::ascii::space, sys);
\endcode
\brief Qi Parser object for parsing text into the SplitInputFile class.
CON END IN END (1 1 1 1) 15
CON END IN -- (1 1 1 0) 14
CON END -- END (1 1 0 1) 13
CON END -- -- (1 1 0 0) 12
CON -- IN END (1 0 1 1) 11
CON -- IN -- (1 0 1 0) 10
-- -- IN END (0 0 1 1) 3
-- -- IN -- (0 0 1 0) 2
-- -- --END (0 0 0 1) 1
-- -- -- -- (0 0 0 0) 0
*/
template<typename Iterator, typename Skipper = ascii::space_type> //boost::spirit::unused_type
struct SplitInputFileParser : qi::grammar<Iterator, SplitInputFile(), Skipper>
{
SplitInputFileParser() : SplitInputFileParser::base_type(root_rule_, "SplitInputFile")
{
namespace phx = boost::phoenix;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_val;
using qi::eps;
using qi::lit;
using qi::char_;
using qi::omit;
using boost::spirit::lexeme;
using boost::spirit::as_string;
using boost::spirit::ascii::no_case;
root_rule_.name("SplitInputFile_root_rule");
root_rule_ = both_ | unreadable_ |only_input_ ;
// NOTE ON CONVENTIONS CURRENTLY USED:
// the various rules are constructed to obtain the text BEFORE the named marker, so e.g, rule config_ gets all text in the string before 'CONFIG'. similarly for 'END;' and 'INPUT'.
both_.name("have_both_config_and_input");
both_ = (
(omit[config_] >> end_ >> omit[input_] >> end_ >> omit[no_decl_]) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)]// 15
|
(omit[config_] >> end_ >> omit[input_] >> no_decl_) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)] // 14
|
(omit[config_] >> end_ >> end_ >> omit[no_decl_]) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)] // 13
|
(omit[config_] >> input_ >> end_ >> omit[no_decl_]) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)] // 11
|
(omit[config_] >> end_ >> no_decl_) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)] // 12
|
(omit[config_] >> input_ >> no_decl_) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)] // 10
)
;
// the rule for number 11 does not currently correctly parse text which matches it... why???
//this attempt for the both_ rule doesn't work because the ends are optional...
// (omit[config_] >> end_ >> omit[input_] >> end_ >> omit[no_decl_]) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)]
// |
// (omit[config_] >> omit[!end_] >> input_ >> end_ >> omit[no_decl_]) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)]
// |
// (omit[config_] >> end_ >> omit[!input_] >> end_ >> omit[no_decl_]) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)]
// |
// (omit[config_] >> omit[!end_] >> input_ >> no_decl_) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)]
// |
// (omit[config_] >> end_ >> omit[!input_] >> omit[!end_] >> no_decl_) [phx::bind(&SplitInputFile::SetConfigInput, _val, _1, _2)]
// )
only_input_.name("have_only_input");
only_input_ = (
(omit[input_] >> end_ >> omit[no_decl_]) // 3
|
(omit[input_] >> no_decl_) // 2
|
(end_ >> omit[no_decl_]) // 1
|
(no_decl_) // 0
)
[phx::bind(&SplitInputFile::SetInput, _val, _1)];
unreadable_.name("unreadable_input"); //9 and 4 same as 12 and 1 to parser
unreadable_ = (
(omit[config_] >> no_decl_) // 8
|
(end_ >> omit[input_] >> end_ >> omit[no_decl_]) // 7
|
(end_ >> omit[input_] >> omit[no_decl_]) // 6
|
(end_ >> end_ >> omit[no_decl_]) // 5
)
[phx::bind(&SplitInputFile::SetReadable, _val, false)];
config_.name("config_");
config_ = no_case[*(char_ - "CONFIG") >> "CONFIG"];
end_.name("end_");
end_ = no_case[lexeme[*(char_ - "END;")] >> "END;"];
input_.name("input_");
input_ = no_case[lexeme[*(char_ - "INPUT")] >> "INPUT"];
no_decl_.name("no_decl_");
no_decl_ = lexeme[*(char_)];
// debug(root_rule_);
// debug(both_); debug(only_input_);
// debug(config_);
// debug(end_);
// debug(input_);
// debug(no_decl_);
// BOOST_SPIRIT_DEBUG_NODES((root_rule_)
// (both_) (only_input_)
// (config_) (end_) (input_)
// (no_decl_) )
using phx::val;
using phx::construct;
using namespace qi::labels;
qi::on_error<qi::fail>
( root_rule_ ,
std::cout<<
val("config/input split parser could not complete parsing. Expecting ")<<
_4<<
val(" here: ")<<
construct<std::string>(_3,_2)<<
std::endl
);
}
private:
qi::rule<Iterator, SplitInputFile(), ascii::space_type > root_rule_, both_, only_input_, unreadable_;
qi::rule<Iterator, ascii::space_type, std::string()> end_, input_, no_decl_;
qi::rule<Iterator, ascii::space_type> config_;
};
/**
Qi Parser object for removing comments from a line of text and then returns the uncommented line.
To use this parser, construct an object of its type, then use it to parse.
*/
template<typename Iterator, typename Skipper = ascii::space_type> //boost::spirit::unused_type
struct CommentStripper : qi::grammar<Iterator, std::string(), Skipper>
{
CommentStripper() : CommentStripper::base_type(root_rule_, "CommentStripper")
{
namespace phx = boost::phoenix;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_val;
using qi::eol;
using qi::eoi;
using qi::eps;
using qi::lit;
using qi::char_;
using qi::omit;
using boost::spirit::lexeme;
using boost::spirit::as_string;
root_rule_.name("CommentStripper_root_rule");
root_rule_ = eps[_val = ""] >> *line_[_val = _val + _1 + "\n"] >> -last_line_[_val = _val + _1 + "\n"];//+line_ | qi::eoi;
line_.name("line_of_commented_input");
line_ = lexeme[*(char_ - eol - "%") >> omit[-( "%" >> lexeme[*(char_ - eol)] )] >> (eol ) ];
last_line_.name("line_of_commented_input_with_no_eol");
last_line_ = lexeme[*(char_ - "%") >> omit[-( "%" >> lexeme[*(char_ - eol)] )]] ;
// debug(root_rule_);
// debug(line_);
// debug(last_line_);
//
// BOOST_SPIRIT_DEBUG_NODES((root_rule_)
// (line_) (last_line_) )
using phx::val;
using phx::construct;
using namespace qi::labels;
qi::on_error<qi::fail>
( root_rule_ ,
std::cout<<
val("config/input split parser could not complete parsing. Expecting ")<<
_4<<
val(" here: ")<<
construct<std::string>(_3,_2)<<
std::endl
);
}
private:
qi::rule<Iterator, std::string(), ascii::space_type > root_rule_;
qi::rule<Iterator, ascii::space_type, std::string()> line_, last_line_;
};
SplitInputFile ParseInputFile(std::string str_input_file)
{
std::string::const_iterator iter = str_input_file.begin();
std::string::const_iterator end = str_input_file.end();
std::string uncommented_str_input;
CommentStripper<std::string::const_iterator> commentparser;
phrase_parse(iter, end, commentparser,boost::spirit::ascii::space, uncommented_str_input);
iter = uncommented_str_input.begin();
end = uncommented_str_input.end();
SplitInputFileParser<std::string::const_iterator> spliter;
SplitInputFile input_file;
phrase_parse(iter, end, spliter,boost::spirit::ascii::space, input_file);
return input_file;
}
/**
\brief Function for splitting a Bertini Classic style input file into `config` and `input`.
*/
std::tuple<std::string, std::string> SplitIntoConfigAndInput(Path const& input_file)
{
auto file_as_string = FileToString(input_file);
SplitInputFileParser<std::string::const_iterator> parser;
SplitInputFile config_and_input;
std::string::const_iterator iter = file_as_string.begin();
std::string::const_iterator end = file_as_string.end();
phrase_parse(iter, end, parser, boost::spirit::ascii::space, config_and_input);
return std::make_tuple(config_and_input.Config(), config_and_input.Input());
}
/**
\brief Function for splitting a Bertini Classic style input file into `config` and `input`.
*/
void SplitIntoConfigAndInput(std::string & config_section, std::string & input_section, Path const& input_file)
{
std::tie(config_section, input_section) = SplitIntoConfigAndInput(input_file);
}
} // re: namespace classic
}// re: namespace parsing
}// re: namespace bertini

View File

@@ -0,0 +1,70 @@
//This file is part of Bertini 2.
//
//bertini2/io/parsers.hpp 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.
//
//bertini2/io/parsing/function_parsers.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/io/parsing/function_parsers.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2017 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
/**
\file bertini2/io/parsing/function_parsers.hpp
\brief Provides the parsers for functions in bertini2.
*/
#pragma once
#include "bertini2/io/parsing/function_rules.hpp"
namespace bertini {
namespace parsing {
namespace classic {
template <typename Iterator>
bool parse(Iterator first, Iterator last, std::shared_ptr<bertini::node::Node>& func)
{
using boost::spirit::qi::double_;
using boost::spirit::qi::_1;
using boost::spirit::qi::phrase_parse;
using boost::spirit::ascii::space;
using boost::phoenix::ref;
FunctionParser<Iterator> S;
std::shared_ptr<bertini::node::Node> f{};
bool r = phrase_parse(first, last,
S,
space,
f);
if (!r || first != last) // fail if we did not get a full match
return false;
func = f;
return r;
}
} // re: namespace classic
}// re: namespace parsing
}// re: namespace bertini

View File

@@ -0,0 +1,309 @@
//This file is part of Bertini 2.
//
//bertini2/io/parsers.hpp 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.
//
//bertini2/io/parsing/function_rules.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/io/parsing/function_rules.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2017 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
/**
\file bertini2/io/parsing/function_rules.hpp
\brief Provides the parsing rules for functions in bertini2.
*/
#pragma once
#include "bertini2/io/parsing/qi_files.hpp"
#include "bertini2/function_tree/node.hpp"
#include "bertini2/function_tree/roots/function.hpp"
#include "bertini2/function_tree/operators/arithmetic.hpp"
#include "bertini2/function_tree/operators/trig.hpp"
#include "bertini2/function_tree/symbols/number.hpp"
#include "bertini2/function_tree/symbols/variable.hpp"
#include "bertini2/io/parsing/number_rules.hpp"
// see the following link for reading from arbitrary streams without putting the content into a std::string first
//http://boost-spirit.com/home/articles/qi-example/tracking-the-input-position-while-parsing/
namespace {
// this solution for *lazy* make shared comes from the SO forum, asked by polytheme, answered by user sehe.
// https://stackoverflow.com/questions/21516201/how-to-create-boost-phoenix-make-shared
// post found using google search terms `phoenix construct shared_ptr`
// the code has been adapted slightly to fit the naming conventions of this project.
template <typename T>
struct MakeSharedFunctor
{
template <typename... A>
struct result
{
typedef std::shared_ptr<T> type;
};
template <typename... A>
typename result<A...>::type operator()(A&&... a) const
{
return T::Make(std::forward<A>(a)...);
}
};
template <typename T>
using make_shared_ = boost::phoenix::function<MakeSharedFunctor<T> >;
}
//////
//
// the following code adapts the trig functions and other special functions to be phoenix-callable.
//
/////////
// http://www.boost.org/doc/libs/1_58_0/libs/phoenix/doc/html/phoenix/modules/function/adapting_functions.html
//
// form is as follows:
//
//BOOST_PHOENIX_ADAPT_FUNCTION(
// RETURN_TYPE
// , LAZY_FUNCTION
// , FUNCTION
// , FUNCTION_ARITY
// )
BOOST_PHOENIX_ADAPT_FUNCTION(std::shared_ptr<bertini::node::Node>, cos_lazy, cos, 1);
BOOST_PHOENIX_ADAPT_FUNCTION(std::shared_ptr<bertini::node::Node>, sin_lazy, sin, 1);
BOOST_PHOENIX_ADAPT_FUNCTION(std::shared_ptr<bertini::node::Node>, tan_lazy, tan, 1);
BOOST_PHOENIX_ADAPT_FUNCTION(std::shared_ptr<bertini::node::Node>, log_lazy, log, 1);
BOOST_PHOENIX_ADAPT_FUNCTION(std::shared_ptr<bertini::node::Node>, exp_lazy, exp, 1);
BOOST_PHOENIX_ADAPT_FUNCTION(std::shared_ptr<bertini::node::Node>, sqrt_lazy, sqrt, 1);
namespace bertini {
namespace parsing {
namespace classic {
namespace qi = ::boost::spirit::qi;
namespace ascii = ::boost::spirit::ascii;
/**
A Qi grammar parser for parsing text into function trees. Currently called from the SystemParser.
\todo Improve error detection and reporting for the FunctionParser.
\brief A Qi grammar parser for parsing text into function trees.
This parser could not have been written without the generous help of SO user sehe.
*/
template<typename Iterator>
struct FunctionParser : qi::grammar<Iterator, std::shared_ptr<node::Node>(), boost::spirit::ascii::space_type>
{
using Node = node::Node;
using Function = node::Function;
using Float = node::Float;
using Integer = node::Integer;
using Rational = node::Rational;
FunctionParser(qi::symbols<char,std::shared_ptr<Node> > * encountered_symbols) : FunctionParser::base_type(root_rule_,"FunctionParser")
{
namespace phx = boost::phoenix;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_val;
using qi::eps;
using qi::lit;
using std::pow;
using ::pow;
root_rule_.name("function_");
root_rule_ = expression_ [ _val = make_shared_<Function>()(_1)];
///////////////////
expression_.name("expression_");
expression_ =
term_ [_val = _1]
>> *( (lit('+') > term_ [_val += _1])
| (lit('-') > term_ [_val -= _1])
)
;
term_.name("term_");
term_ =
factor_ [_val = _1]
>> *( (lit('*') > factor_ [_val *= _1])
| (lit('/') > factor_ [_val /= _1])
)
;
factor_.name("factor_");
factor_ =
exp_elem_ [_val = _1]
>> *(lit('^') // any number of ^somethings
> exp_elem_ [ phx::bind( []
(std::shared_ptr<Node> & B, std::shared_ptr<Node> P)
{
B = pow(B,P);
},
_val,_1)] )
;
exp_elem_.name("exp_elem_");
exp_elem_ =
(symbol_ >> !qi::alnum) [_val = _1]
| ( '(' > expression_ [_val = _1] > ')' ) // using the > expectation here.
| (lit('-') > expression_ [_val = -_1])
| (lit('+') > expression_ [_val = _1])
| (lit("sin") > '(' > expression_ [_val = sin_lazy(_1)] > ')' )
| (lit("cos") > '(' > expression_ [_val = cos_lazy(_1)] > ')' )
| (lit("tan") > '(' > expression_ [_val = tan_lazy(_1)] > ')' )
| (lit("exp") > '(' > expression_ [_val = exp_lazy(_1)] > ')' )
| (lit("log") > '(' > expression_ [_val = log_lazy(_1)] > ')' )
| (lit("sqrt") > '(' > expression_ [_val = sqrt_lazy(_1)] > ')' )
;
symbol_.name("symbol_");
symbol_ %=
(*encountered_symbols) // the star here is the dereferencing of the encountered_symbols parameter to the constructor.
|
number_
;
number_.name("number_");
number_ =
mpfr_rules_.long_number_string_ [ _val = make_shared_<Float>()(_1) ]
|
mpfr_rules_.integer_string_ [ _val = make_shared_<Integer>()(_1) ];
using qi::on_error;
using boost::phoenix::val;
using boost::phoenix::construct;
on_error<qi::fail>
(
root_rule_
, std::cout
<< val("Function parser error: expecting ")
<< _4
<< val(" here: \"")
<< construct<std::string>(_3, _2)
<< val("\"")
<< std::endl
);
// debug(root_rule_);
// debug(expression_);
// debug(term_);
// debug(factor_);
// debug(exp_elem_);
// debug(number_);
// debug(number_with_no_point_);
// debug(number_with_digits_after_point_);
// debug(number_with_digits_before_point_);
// debug(exponent_notation_);
}
qi::rule<Iterator, std::shared_ptr<Node>(), ascii::space_type > root_rule_;
// the rule for kicking the entire thing off
qi::rule<Iterator, std::shared_ptr<Node>(), ascii::space_type> expression_, term_, factor_, exp_elem_;
// rules for how to turn +-*/^ into operator nodes.
qi::rule<Iterator, std::shared_ptr<Node>(), ascii::space_type > symbol_;
// any of the variables and numbers will be symbols.
qi::rule<Iterator, std::shared_ptr<Node>(), ascii::space_type > variable_; // finds a previously encountered number, and associates the correct variable node with it.
// the number_ rule wants to find strings from the various other number_ rules, and produces a Number node
qi::rule<Iterator, std::shared_ptr<Node>(), ascii::space_type > number_;
parsing::rules::LongNum<Iterator> mpfr_rules_;
};
} // re: namespace classic
} // re: namespace parsing
} // re: namespace bertini

View File

@@ -0,0 +1,284 @@
//This file is part of Bertini 2.
//
//bertini2/io/parsers.hpp 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.
//
//bertini2/io/parsing/number_parsers.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/io/parsing/number_parsers.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2017 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
/**
\file bertini2/io/parsing/number_parsers.hpp
\brief Provides parsers for numbers in bertini.
*/
#pragma once
#include "bertini2/io/parsing/number_rules.hpp"
namespace bertini{
namespace parsing{
namespace classic{
template<typename Iterator, typename Skipper = ascii::space_type>
struct MpfrFloatParser : qi::grammar<Iterator, mpfr_float(), boost::spirit::ascii::space_type>
{
MpfrFloatParser() : MpfrFloatParser::base_type(root_rule_,"MpfrFloatParser")
{
using std::max;
namespace phx = boost::phoenix;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_val;
root_rule_.name("mpfr_float");
root_rule_ = mpfr_rules_.number_string_
[ phx::bind(
[]
(mpfr_float & B, std::string const& P)
{
using std::max;
auto prev_prec = DefaultPrecision();
auto asdf = max(prev_prec,LowestMultiplePrecision());
auto digits = max(P.size(),static_cast<decltype(P.size())>(asdf));
B.precision(digits);
B = mpfr_float(P,digits);
},
_val,_1
)
];
using phx::val;
using phx::construct;
using namespace qi::labels;
qi::on_error<qi::fail>
( root_rule_ ,
std::cout<<
val("mpfr_float parser could not complete parsing. Expecting ")<<
_4<<
val(" here: ")<<
construct<std::string>(_3,_2)<<
std::endl
);
}
qi::rule<Iterator, mpfr_float(), Skipper > root_rule_;
rules::LongNum<Iterator> mpfr_rules_;
};
template<typename Iterator, typename Skipper = ascii::space_type>
struct MpfrComplexParser : qi::grammar<Iterator, mpfr_complex(), boost::spirit::ascii::space_type>
{
MpfrComplexParser() : MpfrComplexParser::base_type(root_rule_,"MpfrComplexParser")
{
using std::max;
namespace phx = boost::phoenix;
using qi::_1;
using qi::_2;
using qi::_val;
root_rule_ =
(mpfr_float_ >> mpfr_float_)
[ phx::bind(
[]
(mpfr_complex & B, mpfr_float const& P, mpfr_float const& Q)
{
auto prev_prec = DefaultPrecision();
auto digits = max(P.precision(),Q.precision());
B.precision(digits);
B.real(P);
B.imag(Q);
},
_val,_1,_2
)
];
}
qi::rule<Iterator, mpfr_complex(), Skipper > root_rule_;
MpfrFloatParser<Iterator> mpfr_float_;
};
template <typename Iterator>
static bool parse(Iterator first, Iterator last, double& c)
{
using boost::spirit::qi::double_;
using boost::spirit::qi::_1;
using boost::spirit::qi::phrase_parse;
using boost::spirit::ascii::space;
using boost::phoenix::ref;
double rN = 0.0;
bool r = phrase_parse(first, last,
(
double_[ref(rN) = _1]
),
space);
if (!r || first != last) // fail if we did not get a full match
return false;
c = rN;
return r;
}
template <typename Iterator>
static bool parse(Iterator first, Iterator last, std::complex<double>& c)
{
using boost::spirit::qi::double_;
using boost::spirit::qi::_1;
using boost::spirit::qi::phrase_parse;
using boost::spirit::ascii::space;
using boost::phoenix::ref;
double rN = 0.0;
double iN = 0.0;
bool r = phrase_parse(first, last,
(
double_[ref(rN) = _1]
>> -(double_[ref(iN) = _1])
| double_[ref(rN) = _1]
),
space);
if (!r || first != last) // fail if we did not get a full match
return false;
c = std::complex<double>(rN, iN);
return r;
}
template <typename Iterator>
static bool parse(Iterator first, Iterator last, mpfr_float& c)
{
using boost::spirit::qi::double_;
using boost::spirit::qi::_1;
using boost::spirit::qi::phrase_parse;
using boost::spirit::ascii::space;
using boost::phoenix::ref;
MpfrFloatParser<Iterator> S;
mpfr_float rN {0};
bool r = phrase_parse(first, last,
S,
space,
rN
);
if (!r || first != last) // fail if we did not get a full match
return false;
c.precision(rN.precision());
c = rN;
return r;
}
template <typename Iterator>
static bool parse(Iterator first, Iterator last, mpfr_complex& c)
{
using boost::spirit::qi::double_;
using boost::spirit::qi::_1;
using boost::spirit::qi::phrase_parse;
using boost::spirit::ascii::space;
using boost::phoenix::ref;
MpfrComplexParser<Iterator> S;
mpfr_complex rN {};
bool r = phrase_parse(first, last,
S,
space,
rN);
if (!r || first != last) // fail if we did not get a full match
return false;
c.precision(rN.precision());
c = rN;
return r;
}
} // re: namespace classic
namespace cplusplus{
template <typename Iterator>
static bool parse(Iterator first, Iterator last, double& c)
{
using boost::spirit::qi::double_;
using boost::spirit::qi::_1;
using boost::spirit::qi::phrase_parse;
using boost::spirit::ascii::space;
using boost::phoenix::ref;
double rN = 0.0;
bool r = phrase_parse(first, last,
(
double_[ref(rN) = _1]
),
space);
if (!r || first != last) // fail if we did not get a full match
return false;
c = rN;
return r;
}
template <typename Iterator>
static bool parse(Iterator first, Iterator last, std::complex<double>& c)
{
using boost::spirit::qi::double_;
using boost::spirit::qi::_1;
using boost::spirit::qi::phrase_parse;
using boost::spirit::ascii::space;
using boost::phoenix::ref;
double rN = 0.0;
double iN = 0.0;
bool r = phrase_parse(first, last,
(
'(' >> double_[ref(rN) = _1]
>> -(',' >> double_[ref(iN) = _1]) >> ')'
| double_[ref(rN) = _1]
),
space);
if (!r || first != last) // fail if we did not get a full match
return false;
c = std::complex<double>(rN, iN);
return r;
}
} // re: namespace cplusplus
} //re: namespace parsing
} //re: namespace bertini

View File

@@ -0,0 +1,182 @@
//This file is part of Bertini 2.
//
//bertini2/io/parsers.hpp 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.
//
//bertini2/io/parsing/number_rules.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/io/parsing/number_rules.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2017 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
/**
\file bertini2/io/parsing/number_rules.hpp
\brief Provides the parsersing rules for numbers in bertini2.
*/
#pragma once
#include "bertini2/io/parsing/qi_files.hpp"
#include "bertini2/mpfr_complex.hpp"
#include "bertini2/num_traits.hpp"
BOOST_FUSION_ADAPT_ADT(
bertini::mpfr_complex,
(obj.real(), obj.real(val))
(obj.imag(), obj.imag(val)))
namespace bertini{
namespace parsing{
namespace qi = ::boost::spirit::qi;
namespace ascii = ::boost::spirit::ascii;
namespace rules{
/**
/brief Struct that holds the rules for parsing mpfr numbers
Use: Include this struct with the rest of your rules.
*/
template<typename Iterator>
struct LongNum
{
LongNum()
{
namespace phx = boost::phoenix;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_val;
using qi::eps;
using qi::lit;
using qi::char_;
using qi::omit;
using boost::spirit::lexeme;
using boost::spirit::as_string;
using boost::spirit::ascii::no_case;
number_string_.name("number_");
number_string_ =
long_number_string_
|
integer_string_;
integer_string_.name("integer_string_");
integer_string_ = eps[_val = std::string()] >>
-(qi::lit('-'))[_val += "-"] >>
number_with_no_point_ [_val += _1]
>> -exponent_notation_ [_val += _1];
long_number_string_.name("long_number_string_");
long_number_string_ = eps[_val = std::string()] >>
-(qi::lit('-'))[_val += "-"] >>
(
// 1. Read possible numbers before decimal, with possible negative
(number_with_digits_after_point_ [_val += _1]
|
number_with_digits_before_point_ [_val += _1] )
>> // reminder -- the - before the exponent_notation here means optional
-exponent_notation_ [_val+=_1]// Possible scientific notation, with possible negative in exponent.
);
number_with_digits_after_point_.name("number_with_digits_after_point_");
number_with_digits_after_point_ = eps[_val = std::string()]
>>
*(qi::char_(L'0',L'9')[_val += _1])
>>
qi::lit('.')[_val += "."] // find a decimal point
>>
+(qi::char_(L'0',L'9')[_val += _1]) // find at least one digit after the point
;
number_with_digits_before_point_.name("number_with_digits_before_point_");
number_with_digits_before_point_ = eps[_val = std::string()]
>>
+(qi::char_(L'0',L'9')[_val += _1])
>>
qi::lit('.')[_val += "."] // find a decimal point
>>
*(qi::char_(L'0',L'9')[_val += _1]) // find any number of digits after the point
;
number_with_no_point_.name("number_with_no_point_");
number_with_no_point_ = eps[_val = std::string()]
>>
(-(qi::lit('-')[_val += "-"]) // then an optional minus sign
>>
+(qi::char_(L'0',L'9'))[_val += _1])
;
exponent_notation_.name("exponent_notation_");
exponent_notation_ = eps[_val = std::string()]
>> ( // start what the rule actually does
(
qi::lit('e')[_val += "e"] // get an opening 'e'
|
qi::lit('E')[_val += "e"] // get an opening 'e'
)
>>
-(qi::lit('-')[_val += "-"]) // then an optional minus sign
>>
+(qi::char_(L'0',L'9')[_val += _1]) // then at least one number
); // finish the rule off
rational.name("long_rational");
rational =
(number_string_
|
(number_string_ >> char_('/') >> number_string_));
}
// these rules all produce strings which are fed into numbers.
qi::rule<Iterator, std::string()> number_string_, integer_string_, long_number_string_, number_with_digits_before_point_,
number_with_digits_after_point_, number_with_no_point_, exponent_notation_, rational;
}; //re: LongNum
} // namespace rules
}
}

View File

@@ -0,0 +1,53 @@
//This file is part of Bertini 2.
//
//bertini2/nag_algorithms/zero_dim_solve.hpp 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.
//
//bertini2/io/parsing/qi_files.hpp is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with bertini2/io/parsing/qi_files.hpp. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright(C) 2015 - 2017 by Bertini2 Development Team
//
// See <http://www.gnu.org/licenses/> for a copy of the license,
// as well as COPYING. Bertini2 is provided with permitted
// additional terms in the b2/licenses/ directory.
/**
\file bertini2/io/parsing/qi_files.hpp
\brief Provides all the include files needed to develop a parsing file that uses boost qi.
*/
#pragma once
#define BOOST_SPIRIT_USE_PHOENIX_V3 1
#include <boost/fusion/adapted.hpp>
#include <boost/fusion/include/adapted.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_core.hpp>
#include <boost/phoenix/core.hpp>
#include <boost/phoenix/operator.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/phoenix/bind/bind_function.hpp>
#include <boost/phoenix/object/construct.hpp>
#include <boost/bind/bind.hpp>
#include <boost/fusion/adapted/adt/adapt_adt.hpp>
#include <boost/fusion/include/adapt_adt.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>

Some files were not shown because too many files have changed in this diff Show More