diff --git a/doc/manual/manual/functions/differentialinclusions/differentialinclusions.rst b/doc/manual/manual/functions/differentialinclusions/differentialinclusions.rst new file mode 100644 index 000000000..9ca764db6 --- /dev/null +++ b/doc/manual/manual/functions/differentialinclusions/differentialinclusions.rst @@ -0,0 +1,116 @@ +.. _sec-functions-differential-inclusions: + +Differential Inclusions +======================= + + Main author: `Damien Massé `_ + +The content of this page is limited to C++. Python bindings are missing for now. + +Differential inclusions +----------------------- + +Differential inclusions are equations of the form :math:`\dot{\mathbf{x}} \in \big\{ \mathbf{f}\big(t,\mathbf{x},\mathbf{u}\big) \big\}` where :math:`\mathbf{u}` are unknown (possibly non-continuous) functions varying +on a domain :math:`U`. + +Codac enables to define differential inclusions and to integrate differential +inclusions. The variables for :math:`\mathbf{x}` and :math:`\mathbf{u}` can +be indifferently ``ScalarVar``, ``VectorVar`` or ``MatrixVar``. The +function :math:`\mathbf{f}` can be any function (linear or not). + +For now, two integration schemes are implemented: + +- ``RS_box``: a 0-order scheme using boxes (``IntervalVector``), very imprecise +- ``RS_zonotope``: a 1-order scheme using zonotopes, more precise. This scheme requires :math:`\mathbf{f}` to be differentiable (for all its variables). + +Examples +-------- + +Direct integration +~~~~~~~~~~~~~~~~~~ + +We consider :math:`\mathbf{f}:\mathbb{R}^2 \times \mathbb{R} \to\mathbb{R}^2`: + +.. math:: + \mathbf{f}((x_1,x_2),u)= (-x_2+u, x_1-0.1 x_2) + +We consider :math:`\mathbf{u}` varying in the interval :math:`[-0.03,0.03]`. +The following code performs a guaranteed integration (which constant +time steps) from +:math:`t=0` to :math:`t=10` using ``RS_box``, starting from a small box +:math:`[1,1.01]\times[0,0.01]` and draws the result. + +.. tabs:: + + .. group-tab:: C++ + + .. literalinclude:: src1.cpp + :language: c++ + :start-after: [1-beg] + :end-before: [1-end] + :dedent: 4 + +The next code performs the same integration using ``RS_zonotope``: + +.. tabs:: + + .. group-tab:: C++ + + .. literalinclude:: src1.cpp + :language: c++ + :start-after: [2-beg] + :end-before: [2-end] + :dedent: 4 + +And this code integrate starting from a large square (the maximum +order of zonotopes is deliberately set to a low value, which means +that the integration is done on parallelepipeds): + +.. tabs:: + + .. group-tab:: C++ + + .. literalinclude:: src1.cpp + :language: c++ + :start-after: [3-beg] + :end-before: [3-end] + :dedent: 4 + +The results are given below. A black line describes the computation result +when :math:`\mathbf{u}` is 0 (hence the equation is an ODE). The inclusion +of the final set of reachables sets from the large square (in black) +inside the initial set (in blue) proves the stability of the differential +inclusion. + +.. image:: img/diff_inclusion_first.png + :alt: 2D-differential inclusion integration + :align: center + :width: 400px + +Tube integration +~~~~~~~~~~~~~~~~ + +Codac enables to generate a tube :class:``~codac.SlicedTube`` from a set +of initial (or final) states, following a temporal domain +:class:`~codac.TDomain`. The contraction of an existing tube is also provided. +However, since the domain of zonotopes does not admit useful intersection +operators, the contraction is not very efficient for now. An example is +given below: + +.. tabs:: + + .. group-tab:: C++ + + .. literalinclude:: src2.cpp + :language: c++ + :start-after: [1-beg] + :end-before: [1-end] + :dedent: 4 + +The resulting plot is shown below. + +.. image:: img/diff_inclusion_tube.png + :alt: tubes for differential inclusion + :align: center + :width: 400px + diff --git a/doc/manual/manual/functions/differentialinclusions/img/diff_inclusion_first.png b/doc/manual/manual/functions/differentialinclusions/img/diff_inclusion_first.png new file mode 100644 index 000000000..a54eaaf8f Binary files /dev/null and b/doc/manual/manual/functions/differentialinclusions/img/diff_inclusion_first.png differ diff --git a/doc/manual/manual/functions/differentialinclusions/img/diff_inclusion_tube.png b/doc/manual/manual/functions/differentialinclusions/img/diff_inclusion_tube.png new file mode 100644 index 000000000..70b745c3e Binary files /dev/null and b/doc/manual/manual/functions/differentialinclusions/img/diff_inclusion_tube.png differ diff --git a/doc/manual/manual/functions/differentialinclusions/src1.cpp b/doc/manual/manual/functions/differentialinclusions/src1.cpp new file mode 100644 index 000000000..e518a1ba6 --- /dev/null +++ b/doc/manual/manual/functions/differentialinclusions/src1.cpp @@ -0,0 +1,93 @@ +#include + +using namespace std; +using namespace codac2; + +int main() +{ + { + // [1-beg] + VectorVar x(2); + ScalarVar u; + AnalyticFunction f({x,u}, {-x[1]+u, x[0]-0.1*x[1]}); + DiffInclusion di(f); + + int q=0; + DI_Integration, + RS_box> integration0(di); + IntervalVector state {{1.0,1.01},{0.0,0.01}}; + for (double t=0;t<2.0;t+=0.01) { + IntervalVector s1 = IntervalVector::constant(2,Interval()); + IntervalVector s2 = IntervalVector::constant(2,Interval()); + integration0.contract_one_step(Interval(t,t+0.01), + state, + s1,s2, Interval(-0.03,0.03),true); + state=s2; + if ((++q)%10==0) + DefaultFigure::draw_box(state,Color::purple()); + else + DefaultFigure::draw_box(state,Color::purple(0.1)); + } + // [1-end] + + + // [2-beg] + state = {{1.0,1.01},{0.0,0.01}}; + Zonotope zstate(state); + DI_Integration, + RS_zonotope> integration1(di); + q=0; + /* high limit the number of zonotope generators */ + integration1.get_reachabilitystep()->set_max_zonotope_order(200.0); + for (double t=0;t<10.0;t+=0.02) { + IntervalVector s1 = IntervalVector::constant(2,Interval()); + Zonotope z2; + integration1.contract_one_step(Interval(t,t+0.02), + zstate, + s1,z2, Interval(-0.03,0.03),true); + zstate=z2; + if ((++q)%10==0) { + DefaultFigure::draw_zonotope(zstate,Color::red()); + } else + DefaultFigure::draw_zonotope(zstate,Color::red(0.1)); + } + // [2-end] + + + state = {{1.0,1.01},{0.0,0.01}}; + zstate = Zonotope(state); + for (double t=0;t<10.0;t+=0.02) { + IntervalVector s1 = IntervalVector::constant(2,Interval()); + Zonotope z2; + integration1.contract_one_step(Interval(t,t+0.02), + zstate, + s1,z2, Interval(-0.00,0.00),true); + zstate=z2; + if ((++q)%10==0) { + DefaultFigure::draw_zonotope(zstate,Color::black()); + } else + DefaultFigure::draw_zonotope(zstate,Color::black(0.1)); + } + + + // [3-beg] + /* low limit the number of zonotope generators */ + integration1.get_reachabilitystep()->set_max_zonotope_order(2.0); + state = {{-2.0,2.0},{-2.0,2.0}}; + zstate = Zonotope(state); + DefaultFigure::draw_zonotope(zstate,Color::blue()); + q=0; + for (double t=0;t<11.0;t+=0.01) { + IntervalVector s1 = IntervalVector::constant(2,Interval()); + Zonotope z2; + integration1.contract_one_step(Interval(t,t+0.01), + zstate, + s1,z2, Interval(-0.03,0.03),true); + zstate=z2; + if ((++q)%30==0) DefaultFigure::draw_zonotope(zstate,Color::red(0.2)); + } + DefaultFigure::draw_zonotope(zstate,Color::black()); + // [3-end] + + } +} diff --git a/doc/manual/manual/functions/differentialinclusions/src2.cpp b/doc/manual/manual/functions/differentialinclusions/src2.cpp new file mode 100644 index 000000000..219578954 --- /dev/null +++ b/doc/manual/manual/functions/differentialinclusions/src2.cpp @@ -0,0 +1,34 @@ +#include + +using namespace std; +using namespace codac2; + +int main() +{ + { + // [1-beg] + VectorVar x(2); + ScalarVar u; + AnalyticFunction f({x,u}, {-x[1]+u, x[0]-0.1*x[1]}); + DiffInclusion di(f); + + IntervalVector init = {{-0.3,0.3},{0.8,1.0}}; + DI_Integration, + RS_zonotope> integration1(di); + auto tube = integration1.create_sliced_tube + (create_tdomain(Interval(0,10),0.03), + init, IntervalVector({{-10,10},{-10,10}}), + Interval(-0.03,0.03),true); + + DefaultFigure::plot_tube(tube[0],Color::red(0.1)); + DefaultFigure::plot_tube(tube[1],Color::blue(0.1)); + + tube.set(IntervalVector({{0.85,0.9},{0.15,0.2}}),Interval(5.0)); + integration1.contract_sliced_tube + (tube,Interval(-0.03,0.03),TimePropag::FWD_BWD); + + DefaultFigure::plot_tube(tube[0],Color::red(1.0)); + DefaultFigure::plot_tube(tube[1],Color::blue(1.0)); + // [1-end] + } +} diff --git a/doc/manual/manual/functions/index.rst b/doc/manual/manual/functions/index.rst index 35d7a8bd0..bb4fded60 100644 --- a/doc/manual/manual/functions/index.rst +++ b/doc/manual/manual/functions/index.rst @@ -9,4 +9,5 @@ Inclusion functions analytic/analytic_functions.rst analytic/analytic_operators.rst parallelepiped/parallelepiped_eval.rst - peibos/peibos.rst \ No newline at end of file + peibos/peibos.rst + differentialinclusions/differentialinclusions.rst diff --git a/examples/17_diffinclusions/CMakeLists.txt b/examples/17_diffinclusions/CMakeLists.txt new file mode 100644 index 000000000..a92852494 --- /dev/null +++ b/examples/17_diffinclusions/CMakeLists.txt @@ -0,0 +1,39 @@ +# ================================================================== +# codac / basics example - cmake configuration file +# ================================================================== + + cmake_minimum_required(VERSION 3.10) + project(codac_example LANGUAGES CXX) + + set(CMAKE_CXX_STANDARD 20) + set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Adding Codac + + # In case you installed Codac in a local directory, you need + # to specify its path with the CMAKE_PREFIX_PATH option. + # set(CMAKE_PREFIX_PATH "~/codac/build_install") + + find_package(CODAC REQUIRED) + message(STATUS "Found Codac version ${CODAC_VERSION}") + +# Initializating Ibex + + ibex_init_common() + +# Compilation + + if(FAST_RELEASE) + add_compile_definitions(FAST_RELEASE) + message(STATUS "You are running Codac in fast release mode. (option -DCMAKE_BUILD_TYPE=Release is required)") + endif() + + add_executable(${PROJECT_NAME} main.cpp) + target_compile_options(${PROJECT_NAME} PUBLIC ${CODAC_CXX_FLAGS}) + target_include_directories(${PROJECT_NAME} SYSTEM PUBLIC ${CODAC_INCLUDE_DIRS}) + target_link_libraries(${PROJECT_NAME} PUBLIC ${CODAC_LIBRARIES}) + + add_executable(diff_inclusion_tube main_tube.cpp) + target_compile_options(diff_inclusion_tube PUBLIC ${CODAC_CXX_FLAGS}) + target_include_directories(diff_inclusion_tube SYSTEM PUBLIC ${CODAC_INCLUDE_DIRS}) + target_link_libraries(diff_inclusion_tube PUBLIC ${CODAC_LIBRARIES}) diff --git a/examples/17_diffinclusions/main.cpp b/examples/17_diffinclusions/main.cpp new file mode 100644 index 000000000..306724bb8 --- /dev/null +++ b/examples/17_diffinclusions/main.cpp @@ -0,0 +1,81 @@ +#include + +using namespace std; +using namespace codac2; + +int main() +{ + { + VectorVar x(2); + ScalarVar u; + AnalyticFunction f({x,u}, {-x[1]+u, x[0]-0.1*x[1]}); + DiffInclusion di(f); + + int q=0; + DI_Integration, + RS_box> integration0(di); + IntervalVector state {{1.0,1.01},{0.0,0.01}}; + for (double t=0;t<2.0;t+=0.01) { + IntervalVector s1 = IntervalVector::constant(2,Interval()); + IntervalVector s2 = IntervalVector::constant(2,Interval()); + integration0.contract_one_step(Interval(t,t+0.01), + state, + s1,s2, Interval(-0.03,0.03),true); + state=s2; + if ((++q)%10==0) + DefaultFigure::draw_box(state,Color::purple()); + else + DefaultFigure::draw_box(state,Color::purple(0.1)); + } + state = {{1.0,1.01},{0.0,0.01}}; + Zonotope zstate(state); + DI_Integration, + RS_zonotope> integration1(di); + q=0; + /* high limit the number of zonotope generators */ + integration1.get_reachabilitystep()->set_max_zonotope_order(200.0); + for (double t=0;t<10.0;t+=0.02) { + IntervalVector s1 = IntervalVector::constant(2,Interval()); + Zonotope z2; + integration1.contract_one_step(Interval(t,t+0.02), + zstate, + s1,z2, Interval(-0.03,0.03),true); + zstate=z2; + if ((++q)%10==0) { + DefaultFigure::draw_zonotope(zstate,Color::red()); + } else + DefaultFigure::draw_zonotope(zstate,Color::red(0.1)); + } + state = {{1.0,1.01},{0.0,0.01}}; + zstate = Zonotope(state); + for (double t=0;t<10.0;t+=0.02) { + IntervalVector s1 = IntervalVector::constant(2,Interval()); + Zonotope z2; + integration1.contract_one_step(Interval(t,t+0.02), + zstate, + s1,z2, Interval(-0.00,0.00),true); + zstate=z2; + if ((++q)%10==0) { + DefaultFigure::draw_zonotope(zstate,Color::black()); + } else + DefaultFigure::draw_zonotope(zstate,Color::black(0.1)); + } + /* low limit the number of zonotope generators */ + integration1.get_reachabilitystep()->set_max_zonotope_order(2.0); + state = {{-2.0,2.0},{-2.0,2.0}}; + zstate = Zonotope(state); + DefaultFigure::draw_zonotope(zstate,Color::blue()); + q=0; + for (double t=0;t<11.0;t+=0.01) { + IntervalVector s1 = IntervalVector::constant(2,Interval()); + Zonotope z2; + integration1.contract_one_step(Interval(t,t+0.01), + zstate, + s1,z2, Interval(-0.03,0.03),true); + zstate=z2; + if ((++q)%30==0) DefaultFigure::draw_zonotope(zstate,Color::red(0.2)); + } + DefaultFigure::draw_zonotope(zstate,Color::black()); + + } +} diff --git a/examples/17_diffinclusions/main_tube.cpp b/examples/17_diffinclusions/main_tube.cpp new file mode 100644 index 000000000..15cdbd071 --- /dev/null +++ b/examples/17_diffinclusions/main_tube.cpp @@ -0,0 +1,32 @@ +#include + +using namespace std; +using namespace codac2; + +int main() +{ + { + VectorVar x(2); + ScalarVar u; + AnalyticFunction f({x,u}, {-x[1]+u, x[0]-0.1*x[1]}); + DiffInclusion di(f); + + IntervalVector init = {{-0.3,0.3},{0.8,1.0}}; + DI_Integration, + RS_zonotope> integration1(di); + auto tube = integration1.create_sliced_tube + (create_tdomain(Interval(0,10),0.03), + init, IntervalVector({{-10,10},{-10,10}}), + Interval(-0.03,0.03),true); + + DefaultFigure::plot_tube(tube[0],Color::red(0.1)); + DefaultFigure::plot_tube(tube[1],Color::blue(0.1)); + + tube.set(IntervalVector({{0.85,0.9},{0.15,0.2}}),Interval(5.0,5.00)); + integration1.contract_sliced_tube + (tube,Interval(-0.03,0.03),TimePropag::FWD_BWD); + + DefaultFigure::plot_tube(tube[0],Color::red(1.0)); + DefaultFigure::plot_tube(tube[1],Color::blue(1.0)); + } +} diff --git a/python/src/core/CMakeLists.txt b/python/src/core/CMakeLists.txt index 6adb86409..ca35e1b36 100644 --- a/python/src/core/CMakeLists.txt +++ b/python/src/core/CMakeLists.txt @@ -69,7 +69,10 @@ functions/analytic/codac2_py_analytic_variables.cpp functions/analytic/codac2_py_AnalyticFunction.h functions/analytic/codac2_py_AnalyticExprWrapper.h - + + functions/diffinclusions/codac2_py_DiffInclusion.h + functions/diffinclusions/codac2_py_DI_Integration.h + geometry/codac2_py_ConvexPolygon.cpp geometry/codac2_py_geometry.cpp geometry/codac2_py_Polygon.cpp @@ -150,6 +153,7 @@ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/extensions/sympy/ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/functions/ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/functions/analytic/ + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/functions/diffinclusions/ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/graphics/ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/matrices/ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/paver/ diff --git a/python/src/core/codac2_py_core.cpp b/python/src/core/codac2_py_core.cpp index 2e862e79e..9d06ee0e1 100644 --- a/python/src/core/codac2_py_core.cpp +++ b/python/src/core/codac2_py_core.cpp @@ -16,12 +16,16 @@ #include #include #include +#include +#include #include "codac2_py_Sep.h" #include "codac2_py_AnalyticFunction.h" #include "codac2_py_CtcInverse.h" #include "codac2_py_MatrixBlock.h" #include "codac2_py_Slice.h" #include "codac2_py_SlicedTube.h" +#include "codac2_py_DI_Integration.h" +#include "codac2_py_DiffInclusion.h" using namespace codac2; namespace py = pybind11; @@ -133,6 +137,9 @@ void export_pave(py::module& m); // peibos void export_peibos(py::module& m); +// diffinclusions +void export_DiffInclusion(py::module& m, const std::string& name); + // proj void export_qinter(py::module& m); @@ -324,6 +331,14 @@ PYBIND11_MODULE(_core, m) // peibos export_peibos(m); + // diffinclusions + export_DiffInclusion(m, "DiffInclusion"); + export_DI_Integration,RS_box> + (m, "Integration_Box"); + export_DI_Integration,RS_zonotope> + (m, "Integration_Zonotope"); + + // proj export_qinter(m); diff --git a/python/src/core/functions/diffinclusions/codac2_py_DI_Integration.h b/python/src/core/functions/diffinclusions/codac2_py_DI_Integration.h new file mode 100644 index 000000000..1ce1abaf4 --- /dev/null +++ b/python/src/core/functions/diffinclusions/codac2_py_DI_Integration.h @@ -0,0 +1,95 @@ +/** + * Codac binding (diffinclusion) + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "codac2_py_DI_Integration_docs.h" + +using namespace codac2; +namespace py = pybind11; +using namespace pybind11::literals; + +/* we limit ourselves to VectorVar */ + +template +void export_DI_Integration(py::module& m, const std::string& name) +{ + + using X = DI::X; + using U = DI::U; + using DomA = IS::DomainA; + using DomB = IS::DomainB; + + + py::class_> + exported_di_integration(m, name.c_str(), + DI_INTEGRATION_MAIN); + + exported_di_integration + .def(py::init(), + DI_INTEGRATION_DIIS_DI_INTEGRATION_CONST_DI_REF_INT_INT, + "di"_a, "widen_attempts"_a=3, "narrow_attempts"_a=3) + + .def("contract_one_step", + [](DI_Integration& s, const Interval &time_step, + const DomA& init, DomB& in_domain, DomA& out_gate, + const U& u, bool forward) { + return s.contract_one_step(time_step,init,in_domain,out_gate,u, + forward); + }, + BOOL_DI_INTEGRATION_DIIS_CONTRACT_ONE_STEP_CONST_INTERVAL_REF_CONST_DOMA_REF_DOMB_REF_DOMA_REF_CONST_U_REF_BOOL, + "time_step"_a, "init"_a, "in_domain"_a, "out_gate"_a, "u"_a, + "forward"_a=true) + + .def("integrate_to_time_indom", + [](DI_Integration& s, const Interval &time_step, + const DomA& init, const DomB& in_domain, + const U& u, double t_steps) { + return s.integrate_to_time_indom(time_step,init,in_domain,u,t_steps); + }, + PAIR_BOOLDOMA_DI_INTEGRATION_DIIS_INTEGRATE_TO_TIME_INDOM_CONST_INTERVAL_REF_CONST_DOMA_REF_CONST_DOMB_REF_CONST_U_REF_DOUBLE, + "time_step"_a, "init"_a, "in_domain"_a, "u"_a, "t_steps"_a) + + .def("integrate_to_time", + [](DI_Integration& s, const Interval &time_step, + const X& init, const X& in_domain, + const U& u, double t_steps) { + return s.integrate_to_time(time_step,init,in_domain,u,t_steps); + }, + PAIR_BOOLX_DI_INTEGRATION_DIIS_INTEGRATE_TO_TIME_CONST_INTERVAL_REF_CONST_X_REF_CONST_X_REF_CONST_U_REF_DOUBLE, + "time_step"_a, "init"_a, "in_domain"_a, "u"_a, "t_steps"_a) + + .def("create_sliced_tube", + [](DI_Integration& s, const std::shared_ptr& tdomain, + const X&init, const X& in_domain, + const U& u, bool forward) { + return s.create_sliced_tube(tdomain,init,in_domain,u,forward); + }, + SLICEDTUBE_X_DI_INTEGRATION_DIIS_CREATE_SLICED_TUBE_CONST_SHARED_PTR_TDOMAIN_REF_CONST_X_REF_CONST_X_REF_CONST_U_REF_BOOL, + "tdomain"_a, "init"_a, "in_domain"_a, "u"_a, "forward"_a) + + .def("contract_sliced_tube", + [](DI_Integration& s, SlicedTube& tube, const U& u, TimePropag dir) { + s.contract_sliced_tube(tube,u,dir); + }, + "tube"_a, "u"_a, "dir"_a) + ; +} diff --git a/python/src/core/functions/diffinclusions/codac2_py_DiffInclusion.h b/python/src/core/functions/diffinclusions/codac2_py_DiffInclusion.h new file mode 100644 index 000000000..ba5cb00e6 --- /dev/null +++ b/python/src/core/functions/diffinclusions/codac2_py_DiffInclusion.h @@ -0,0 +1,39 @@ +/** + * Codac binding (diffinclusion) + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include "codac2_py_DiffInclusion_docs.h" + +using namespace codac2; +namespace py = pybind11; +using namespace pybind11::literals; + +/* we limit ourselves to VectorVar */ + +void export_DiffInclusion(py::module& m, const std::string& name) +{ + py::class_> + exported_diffinclusion(m, name.c_str(), + DIFFINCLUSION_MAIN); + + exported_diffinclusion + + .def(py::init&, bool>(), + DIFFINCLUSION_XVARUVAR_DIFFINCLUSION_CONST_ANALYTICFUNCTION_XTYPE_REF_BOOL, + "f"_a, "time_dependant"_a = false) + ; +} diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 7c3752756..6cb4d799d 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -126,6 +126,15 @@ ${CMAKE_CURRENT_SOURCE_DIR}/functions/set/codac2_SetFunction.h ${CMAKE_CURRENT_SOURCE_DIR}/functions/set/codac2_set_constants.h + ${CMAKE_CURRENT_SOURCE_DIR}/diffinclusions/codac2_DiffInclusion.h + ${CMAKE_CURRENT_SOURCE_DIR}/diffinclusions/codac2_DiffInclusion.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/diffinclusions/codac2_ReachabilityStep.h + ${CMAKE_CURRENT_SOURCE_DIR}/diffinclusions/codac2_RS_box.h + ${CMAKE_CURRENT_SOURCE_DIR}/diffinclusions/codac2_RS_zonotope.h + ${CMAKE_CURRENT_SOURCE_DIR}/diffinclusions/codac2_RS_box.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/diffinclusions/codac2_RS_zonotope.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/diffinclusions/codac2_DI_Integration.h + ${CMAKE_CURRENT_SOURCE_DIR}/geometry/codac2_ConvexPolygon.cpp ${CMAKE_CURRENT_SOURCE_DIR}/geometry/codac2_ConvexPolygon.h ${CMAKE_CURRENT_SOURCE_DIR}/geometry/codac2_geometry.cpp diff --git a/src/core/diffinclusions/codac2_DI_Integration.h b/src/core/diffinclusions/codac2_DI_Integration.h new file mode 100644 index 000000000..a8bc17817 --- /dev/null +++ b/src/core/diffinclusions/codac2_DI_Integration.h @@ -0,0 +1,238 @@ +/** + * \file codac2_DI_Integration.h + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + + +#pragma once + +#include "codac2_AnalyticFunction.h" +#include "codac2_DiffInclusion.h" +#include "codac2_ReachabilityStep.h" +#include "codac2_SlicedTube.h" +#include "codac2_TimePropag.h" +#include + +namespace codac2 +{ + template + class DI_Integration { + public: + using XType = DI::XType; + /* X,U : e.g. IntervalVector */ + using X = DI::X; + using U = DI::U; + + using DomA = IS::DomainA; + using DomB = IS::DomainB; + + DI_Integration(const DI& di, int widen_attempts=3, + int narrow_attempts=3) : + _di(std::make_unique(di)), + _is(std::make_unique(&(*_di))), + _widen_attempts(widen_attempts), + _narrow_attempts(narrow_attempts) { } + + + std::unique_ptr &get_differentialinclusion() { + return _is; + } + std::unique_ptr &get_reachabilitystep() { + return _is; + } + + std::pair integration_step(DomA& approx, + DomB& in_domain) const { + int nb_tries=0; + DomB inside_in; + bool success=false; + while (nb_tries<_widen_attempts) { /* inflation steps */ + _is->inflate(approx); + DomB inside = _is->intersect(in_domain,approx); + std::tie(approx,std::ignore) = _is->enclose(inside); + DomB new_inside = _is->intersect(in_domain,approx); + if (new_inside.is_subset(inside)) { + in_domain = new_inside; + success=true; + break; + } + nb_tries++; + } + /* success = true : approx and in_domain are guaranteed; gate + * is not computed. + * success = false : approx is not sufficient, + in_domain has not changed */ + if (in_domain.is_unbounded()) return { false,approx }; + nb_tries=0; + DomA gate; + while (nb_tries<_narrow_attempts) { /* reduction steps */ + DomB inside = in_domain; + std::tie(approx,gate)= _is->enclose(inside); + in_domain = _is->intersect(inside,approx); + if (inside.is_subset(in_domain)) break; + success=true; + nb_tries++; + } + return { success, gate }; + } + + bool contract_one_step(const Interval &time_step, + const DomA& init, DomB& in_domain, DomA& out_gate, + const U& u, bool forward=true) { + IntervalVector u_ = _di->from_U(u); + _is->update_time(time_step, forward ? IS::FWD : IS::BWD); + _is->update_init(init); + _is->update_u(u_); + DomA z1 = _is->approx(); + bool result; + DomA out_gate2; + std::tie(result,out_gate2) = + this->integration_step(z1,in_domain); + if (result) + out_gate = (out_gate2 & in_domain); /* FIXME : intersection? */ + return result; + } + + std::pair integrate_to_time_indom(const Interval &time_step, + const DomA& init, const DomB& in_domain, + const U& u, double t_steps) { + assert_release(t_steps!=0.0); + bool forward=(t_steps>0); + double cur_time = (forward ? time_step.lb() : -time_step.ub()); + double end_time = (forward ? time_step.ub() : -time_step.lb()); + if (!forward) t_steps = -t_steps; + DomA current(init); + while (cur_timeend_time) nxt_time=end_time; + Interval small_step(cur_time,nxt_time); + DomB in_domain2(in_domain); + DomA out_gate2; + bool result = this->contract_one_step( + (forward ? small_step : -small_step), + current, in_domain2, out_gate2, u, forward); + if (!result) return { false, current }; + /* FIXME : use smaller steps ? */ + current = out_gate2; + if (_is->intersect(in_domain,current).is_empty()) { + current.set_empty(); + return { true, current }; + } + cur_time=nxt_time; + } + return { true, current }; + } + + std::pair integrate_to_time(const Interval &time_step, + const X& init, const X& in_domain, + const U& u, double t_steps) { + DomA ninit(_di->from_X(init)); + DomB indomain(_di->from_X(in_domain)); + auto res = this->integrate_to_time_indom(time_step, + ninit, indomain, u, t_steps); + return { res.first, _di->to_X(IS::intVect_from_DomainA(res.second)) }; + } + + SlicedTube create_sliced_tube + (const std::shared_ptr& tdomain, + const X&init, const X& in_domain, + const U& u, bool forward=true) { + DomB indomain(_di->from_X(in_domain)); + SlicedTube built(tdomain, in_domain); + DomA current(_di->from_X(init)); + bool empty = init.is_empty(); + auto sl = (forward ? built.first_slice() : built.last_slice()); + while (sl!=nullptr) { + if (empty) { + sl->codomain().set_empty(); + } else + if (sl->is_gate()) { + sl->codomain() &= + _di->to_X(IS::intVect_from_DomainA(current)); + } else { + DomB indomain2(indomain); + DomA out_gate2; + bool result = this->contract_one_step( + sl->t0_tf(), + current, indomain2, out_gate2, u, forward); + if (result) { + sl->codomain() &= + _di->to_X(IS::intVect_from_DomainB(indomain2)); + current = out_gate2; + if (sl->codomain().is_empty() || + current.is_empty()) empty=true; + } else { + current = DomA(_di->from_X(in_domain)); + } + } + sl = (forward ? sl->next_slice() : sl->prev_slice()); + } + return built; + } + + void contract_sliced_tube + (SlicedTube& tube, + const U& u, bool forward=true) { + Interval global_time=tube.t0_tf(); + auto sl = (forward ? tube.first_slice() : tube.last_slice()); + DomA current(_di->from_X(sl->codomain())); + bool empty = sl->codomain().is_empty(); + while (sl!=nullptr) { + if (empty) { + sl->codomain().set_empty(); + } else + if (sl->is_gate()) { + sl->codomain() &= + _di->to_X(IS::intVect_from_DomainA(current)); + if (sl->codomain().is_empty()) empty=true; + current &= _di->from_X(sl->codomain()); + if (current.is_empty()) empty=true; + } else { + DomB indomain2(_di->from_X(sl->codomain())); + DomA out_gate2; + current &= indomain2; + bool result = this->contract_one_step( + sl->t0_tf(), + current, indomain2, out_gate2, u, forward); + if (result) { + sl->codomain() &= + _di->to_X(IS::intVect_from_DomainB(indomain2)); + current = out_gate2; + if (sl->codomain().is_empty() || + current.is_empty()) empty=true; + } else { + current = DomA(_di->from_X(sl->codomain())); + } + } + sl = (forward ? sl->next_slice() : sl->prev_slice()); + } + } + + void contract_sliced_tube + (SlicedTube& tube, + const U& u, TimePropag dir) { + if (dir == TimePropag::FWD) { + this->contract_sliced_tube(tube,u,true); + } else if (dir == TimePropag::BWD) { + this->contract_sliced_tube(tube,u,false); + } else { + for (int i=0;i<2;i++) { + this->contract_sliced_tube(tube,u,true); + this->contract_sliced_tube(tube,u,false); + } /* TODO : check the changes ? */ + } + } + + private: + std::unique_ptr _di; + std::unique_ptr _is; + int _widen_attempts; + int _narrow_attempts; + }; + +} + diff --git a/src/core/diffinclusions/codac2_DiffInclusion.cpp b/src/core/diffinclusions/codac2_DiffInclusion.cpp new file mode 100644 index 000000000..cdd538cc9 --- /dev/null +++ b/src/core/diffinclusions/codac2_DiffInclusion.cpp @@ -0,0 +1,40 @@ +/** + * \file codac2_DiffInclusion.cpp + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + +#include +#include +#include "codac2_Matrix.h" +#include "codac2_Interval.h" +#include "codac2_IntervalMatrix.h" +#include "codac2_IntervalVector.h" +#include "codac2_DiffInclusion.h" +#include "codac2_ReachabilityStep.h" + +namespace codac2 { + + IntervalVector + DiffInclusionBase::approx_RK4_base(const Interval &time_step, + const IntervalVector& init, const IntervalVector& u, + bool forward, bool end_gate) const { + double start_time = (forward ? time_step.lb() : time_step.ub()); + double step_size = (forward ? time_step.diam() : -time_step.diam()); + IntervalVector k1 = f_eval(EvalMode::NATURAL,start_time,init,u); + IntervalVector k2 = f_eval(EvalMode::NATURAL,start_time+0.5*step_size, + init+0.5*step_size*k1, u); + IntervalVector k3 = f_eval(EvalMode::NATURAL,start_time+0.5*step_size, + init+0.5*step_size*k2, u); + IntervalVector k4 = f_eval(EvalMode::NATURAL,start_time+step_size, + init+k3, u); + IntervalVector ret = init + (step_size/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4); + if (end_gate) return ret; + IntervalVector inter = init + Interval(0,0.25)*step_size*(k1+k2); + return (inter | ret); + } + +} diff --git a/src/core/diffinclusions/codac2_DiffInclusion.h b/src/core/diffinclusions/codac2_DiffInclusion.h new file mode 100644 index 000000000..8c64e28a7 --- /dev/null +++ b/src/core/diffinclusions/codac2_DiffInclusion.h @@ -0,0 +1,247 @@ +/** + * \file codac2_DiffInclusion.h + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + +#pragma once + +#include "codac2_AnalyticFunction.h" +#include "codac2_SlicedTube.h" + +namespace codac2 +{ + /* class to handle reachability steps on a specific domain, + has two methods : inflate (on DomA) and enclose (on DomA and DomB) + see codac2_ReachabilityStep.h */ + template + class ReachabilityStep; + + /* DiffInclusionBase is an abstract class which considers only + * functions (IntervalVector,IntervalVector) -> IntervalVector. + * Below DiffInclusion extends DiffInclusionBase to handle other + * functions */ + class DiffInclusionBase + { + public: + virtual IntervalVector f_eval(const EvalMode& m, const Interval &t, + const IntervalVector& x, + const IntervalVector& u) const =0; + + virtual VectorType f_eval_diff(const Interval &t, + const IntervalVector& x, + const IntervalVector& u) const =0; + + std::tuple + split_diff_matrix(const IntervalMatrix &da) const { + if (_time_dependant) { + return { + da.col(0), + da.middleCols(1,_x_shape.first*_x_shape.second), + da.rightCols(_u_shape.first*_u_shape.second) + }; + } else { + return { + IntervalVector::Zero(_x_shape.first*_x_shape.second), + da.leftCols(_x_shape.first*_x_shape.second), + da.rightCols(_u_shape.first*_u_shape.second) + }; + } + } + + protected: + DiffInclusionBase(bool td) : _time_dependant(td) { } + + IntervalVector approx_RK4_base(const Interval &time_step, + const IntervalVector& init, const IntervalVector& u, + bool forward, bool end_gate) const; + + const bool _time_dependant = false; + std::pair _x_shape; + std::pair _u_shape; + + private: + /* general templated single-step fixpoint-based integration scheme, + * starts with an initial set and an approximation of the reachable set + * 1) Increasing chain loop to get a post-fixpoint (widening process) + * a) intersect with current out => B + * b) compute guaranteed enclosing set A (function 2) + * c) check inclusion A <= B + * d) if inclusion false, enlarge and loop + * e) stops if inclusion is true or nb attempts too large (failure) + * 2) If 3) failed and unbounded out, returns false + * 3) Decreasing chain loop (narrowing process) + * a) starts with previous results if increasing succeeds, or + * with current out => B + * b) compute guaranteed enclosing set A (and gate) (function 2) + * c) check inclusion B <= A + * d) if inclusion true or nb attempts limited, stops + * e) otherwise, B=A and loop + * 4) returns true if 2 succeeded or one step of 4 succeeded, + * otherwise false + */ + /* moved to codac2_DI_Integration */ + }; + + + + + /** diffential inclusion x' = f(x,u) or f(t,x,u). + * x and u can be scalar, interval or matrix. + * For practical reasons (on the interface), we consider + * exactly one u. (TODO: lift this restriction ?) */ + template + class DiffInclusion : public DiffInclusionBase + { + public: + + /* Type : e.g. VectorType (for AnalyticFunction) */ + using XType = typename ExprType::Type; + /* X,U : e.g. IntervalVector */ + using X = XType::Domain; + using U = typename ExprType::Type::Domain; + + + DiffInclusion(const AnalyticFunction& f, + bool time_dependant=false) : + DiffInclusionBase(time_dependant), _f(f) + { + size_t x_arg=(time_dependant ? 1 : 0); + assert_release(f.args().size() == x_arg+2 && + "DiffInclusion: wrong args size"); + /* NdD : I don't understand why output_shape is not + a virtual method of VarBase but maybe some variable types + cannot have any "shape"... */ + _u_shape = dynamic_cast(*(f.args()[x_arg+1])). + output_shape(); + if (time_dependant) { + assert_release((f.args()[0]->size() == 1) + && "DiffInclusion: wrong time size"); + } + _x_shape = dynamic_cast(*(f.args()[x_arg])). + output_shape(); + assert_release(_x_shape == f.output_shape() + && "DiffInclusion: wrong output size"); + } + + /** \brief approximation of IVP on a step using RK4. + * Does not return a guaranteed result, used for + * approximate enclosing + * \param time_step time stem (backward or forward) + * \param init initial values + * \param u uncertainties + */ + template + X approx_RK4(const Interval &time_step, const X& init, const U& u) { + return + to_X(approx_RK4_base(time_step, + from_X(init),from_U(u),forward,end_gate)); + } + + + /** \brief basic enclosing step + * \param time_step time stem (backward or forward) + * \param init_domain initial values + * \param in_domain inside values (may be contracted) + * \param out_gate final values (may be contracted) + * \param u uncertainties + * \param inflation_ratio inflation ratio (default 0.1) + * \param inflation_base inflation base (default 1e-2) + * \param attempts max number of attempts (default 3) + * \return false if no improvement was found */ + /* moved to codac2_DI_Integration.h */ + + inline IntervalVector f_eval(const EvalMode& m, const Interval &t, + const IntervalVector& x, + const IntervalVector& u) const override { + if constexpr(std::is_same_v + && std::is_same_v) { + if (_time_dependant) + return _f.eval(m,t,x,u); + else + return _f.eval(m,x,u); + } else { + if (_time_dependant) + return from_X(_f.eval(m,t,to_X(x),to_U(u))); + else + return from_X(_f.eval(m,to_X(x),to_U(u))); + } + } + + inline VectorType f_eval_diff(const Interval &t, + const IntervalVector& x, + const IntervalVector& u) const override { + if constexpr(std::is_same_v + && std::is_same_v) { + if (_time_dependant) + return _f.eval_and_diff(t,x,u); + else + return _f.eval_and_diff(x,u); + } else { + if (_time_dependant) { + XType ret = _f.eval_and_diff(t,to_X(x),to_U(u)); + return { from_X(ret.m), + from_X(ret.a), + ret.da, + ret.def_domain }; + } + else { + XType ret = _f.eval_and_diff(to_X(x),to_U(u)); + return { from_X(ret.m), + from_X(ret.a), + ret.da, + ret.def_domain }; + } + } + } + + inline IntervalVector from_X(const X& x) const { + if constexpr(std::is_same_v) { + return { x }; + } else { + return x.template reshaped(); + } + } + inline Vector from_X(const XType::Scalar& x) const { + if constexpr(std::is_same_v) { + return { x }; + } else { + return x.template reshaped(); + } + } + inline X to_X(const IntervalVector& x) const { + if constexpr(std::is_same_v) { + return x[0]; + } else { + return x.template reshaped + (_x_shape.first,_x_shape.second); + } + } + + inline IntervalVector from_U(const U& u) const { + if constexpr(std::is_same_v) { + return { u }; + } else { + return u.template reshaped(); + } + } + inline U to_U(const IntervalVector& u) const { + if constexpr(std::is_same_v) { + return u[0]; + } else { + return u.template reshaped + (_u_shape.first,_u_shape.second); + } + } + + protected: + const AnalyticFunction _f; + + + }; +} + + diff --git a/src/core/diffinclusions/codac2_RS_box.cpp b/src/core/diffinclusions/codac2_RS_box.cpp new file mode 100644 index 000000000..18cd4a527 --- /dev/null +++ b/src/core/diffinclusions/codac2_RS_box.cpp @@ -0,0 +1,31 @@ +/** + * \file codac2_RS_box.cpp + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + +#include "codac2_AnalyticFunction.h" +#include "codac2_DiffInclusion.h" +#include "codac2_ReachabilityStep.h" +#include "codac2_RS_box.h" + +namespace codac2 +{ + void RS_box::inflate(IntervalVector &a) const { + IntervalVector a_ins = a - a.mid(); + a += _inflation_ratio*a_ins; + a.inflate(_inflation_base); + } + + std::pair + RS_box::enclose(const IntervalVector &b) const { + IntervalVector evolution = + _diffinclusion->f_eval(EvalMode::DEFAULT,_time_step,b,_u); + return { _init+_time_interval*evolution, + _init+_time_bound*evolution }; + } + +} diff --git a/src/core/diffinclusions/codac2_RS_box.h b/src/core/diffinclusions/codac2_RS_box.h new file mode 100644 index 000000000..4473037bc --- /dev/null +++ b/src/core/diffinclusions/codac2_RS_box.h @@ -0,0 +1,63 @@ +/** + * \file codac2_RS_box.h + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + +#pragma once + +#include "codac2_AnalyticFunction.h" +#include "codac2_DiffInclusion.h" +#include "codac2_ReachabilityStep.h" + +namespace codac2 +{ + /* IntervalVector, 0-order reachability step */ + class RS_box : public + ReachabilityStep + { + public: + RS_box(const DiffInclusionBase *diffinclusion, + double inflation_ratio=1.1, double inflation_base=1e-2) : + ReachabilityStep(diffinclusion), + _inflation_ratio(inflation_ratio), + _inflation_base(inflation_base) { + } + + std::pair get_inflation_options() const { + return { _inflation_ratio, _inflation_base }; + } + void set_inflation_options(std::pair options) { + std::tie(_inflation_ratio,_inflation_base) = + options; + } + + IntervalVector approx() const { return approx_base(_init); } + void inflate(IntervalVector &a) const override; + std::pair enclose + (const IntervalVector &b) const override; + IntervalVector intersect(const IntervalVector &b, + const IntervalVector &a) + const { + return (b & a); + } + static const IntervalVector & + intVect_from_DomainA(const IntervalVector &a) { + return a; + } + static const IntervalVector & + intVect_from_DomainB(const IntervalVector &b) { + return b; + } + + + private: + double _inflation_ratio; + double _inflation_base; + }; + + +} diff --git a/src/core/diffinclusions/codac2_RS_zonotope.cpp b/src/core/diffinclusions/codac2_RS_zonotope.cpp new file mode 100644 index 000000000..d4babe934 --- /dev/null +++ b/src/core/diffinclusions/codac2_RS_zonotope.cpp @@ -0,0 +1,83 @@ +/** + * \file codac2_RS_zonotope.cpp + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + +#include +#include "codac2_AnalyticFunction.h" +#include "codac2_DiffInclusion.h" +#include "codac2_ReachabilityStep.h" +#include "codac2_RS_zonotope.h" + +namespace codac2 +{ + void RS_zonotope::inflate(Zonotope &a) const { + a.A *= (1.0+_inflation_ratio); + IntervalVector bx = IntervalVector::Constant + (a.c.size(),Interval(-_inflation_base,_inflation_base)); + a += bx; + } + + std::pair + RS_zonotope::enclose(const IntervalVector &b) const { + /* evaluation on whole set */ + VectorType retWhole = + _diffinclusion->f_eval_diff(_time_step,_init.box(),_u); + if (!retWhole.def_domain) { /* we can't differentiate ! */ + /* create a zonotope enclosing _time_interval * retWhole.a + */ + Matrix Min { _time_interval.rad()*retWhole.a.mid() }; + Zonotope Zin(_time_interval.mid()*retWhole.a.mid(), Min); + Zin += (_time_interval-_time_interval.mid())*retWhole.a.rad(); + IntervalVector nxtGate = _time_bound * retWhole.a; + Zonotope gate(_init); + gate += nxtGate; + return { + _init + Zin, + gate + }; + } + + auto splitmat = _diffinclusion->split_diff_matrix(retWhole.da); + IntervalVector lincorr_u = std::get<2>(splitmat)*(_u-_u.mid()); + IntervalVector quadcorr_x + = std::get<1>(splitmat)*retWhole.a + + std::get<0>(splitmat); + + /* evaluation on initial states, u_mid */ + VectorType retInit = + _diffinclusion->f_eval_diff(_start_time,_init.box(),_u.mid()); + assert_release(retInit.def_domain); + splitmat = _diffinclusion->split_diff_matrix(retInit.da); + + /* creation of the reachable block */ + IntervalMatrix m1 = IntervalMatrix::Identity(b.size(),b.size()) + + _time_interval*std::get<1>(splitmat); + Zonotope zinside = _init.transform(m1); + zinside += (_time_interval*(retInit.m+lincorr_u) + + 0.5*sqr(_time_interval)*retInit.m); + /* FIXME : make a zonotope ? */ + + /* creation of the reachable gate */ + m1 = IntervalMatrix::Identity(b.size(),b.size()) + + _time_bound*std::get<1>(splitmat); + Zonotope zgate = _init.transform(m1); + zgate += (_time_bound*(retInit.m+lincorr_u) + + 0.5*sqr(_time_bound)*quadcorr_x); + if (this->_max_zonotope_order>=2.0 && + zgate.A.rows()*this->_max_zonotope_order + { + public: + RS_zonotope(const DiffInclusionBase *diffinclusion, + double max_zonotope_order=50.0, + std::pair inflation_options={1.1,1e-2}) : + ReachabilityStep(diffinclusion), + _inflation_ratio(inflation_options.first), + _inflation_base(inflation_options.second), + _max_zonotope_order(max_zonotope_order) { + } + + std::pair get_inflation_options() const { + return { _inflation_ratio, _inflation_base }; + } + void set_inflation_options(std::pair options) { + std::tie(_inflation_ratio,_inflation_base) = + options; + } + + double get_max_zonotope_order() const { + return _max_zonotope_order; + } + void set_max_zonotope_order(double value) { + _max_zonotope_order=value; + } + + static const IntervalVector + intVect_from_DomainA(const Zonotope &a) { + return a.box(); + } + static const IntervalVector & + intVect_from_DomainB(const IntervalVector &b) { + return b; + } + + Zonotope approx() const { return Zonotope(approx_base(_init.box())); } + void inflate(Zonotope &a) const override; + std::pair enclose + (const IntervalVector &b) const override; + IntervalVector intersect(const IntervalVector &b, const Zonotope &a) + const override; + + private: + double _inflation_ratio; + double _inflation_base; + double _max_zonotope_order; + }; + +} diff --git a/src/core/diffinclusions/codac2_ReachabilityStep.h b/src/core/diffinclusions/codac2_ReachabilityStep.h new file mode 100644 index 000000000..de23bcc6d --- /dev/null +++ b/src/core/diffinclusions/codac2_ReachabilityStep.h @@ -0,0 +1,183 @@ +/** + * \file codac2_ReachabilityStep.h + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + +#pragma once + +#include "codac2_AnalyticFunction.h" +#include "codac2_DiffInclusion.h" + +namespace codac2 +{ + /* class to handle reachability steps on a specific domain, + has two methods : inflate (on DomA) and enclose (on DomA and DomB) + DomA can be inflated, temporaly propagated but maybe not compared or + intersected (IntervalVector, Zonotope, Polytope) + DomB can be (partially) intersected with DomA, intersected with DomB, + and inclusion can be tested (IntervalVector, maybe Polytope) + Reachability step includes the underlying differential equation, + initial step, temporal interval, direction, + value of the uncertainties (maybe), and maybe other elements(?) + */ + template + class ReachabilityStep { + public: + using DomainA = DomA; + using DomainB = DomB; + enum StepDirection { FWD, BWD }; + + /* approximation step on interval vectors , to be used + * as approx if needed */ + IntervalVector approx_base(const IntervalVector &init) const { + IntervalVector k1 = _diffinclusion->f_eval(EvalMode::NATURAL, + _start_time,init,_u); + IntervalVector k2 = _diffinclusion->f_eval(EvalMode::NATURAL, + _start_time+0.5*_time_bound, init+0.5*_time_bound*k1, _u); + IntervalVector k3 = _diffinclusion->f_eval(EvalMode::NATURAL, + _start_time+0.5*_time_bound, init+0.5*_time_bound*k2, _u); + IntervalVector k4 = _diffinclusion->f_eval(EvalMode::NATURAL, + _start_time+_time_bound, init+k3, _u); + IntervalVector ret = init + + (_time_bound/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4); + IntervalVector inter = init + Interval(0,0.25)*_time_bound*(k1+k2); + return (inter | ret); + } + + virtual DomA approx() const = 0; + virtual void inflate(DomA &a) const =0; + virtual std::pair enclose(const DomB &b) const =0; + virtual DomB intersect(const DomB &b, const DomA &a) const = 0; + + void update_time(const Interval &time_step, StepDirection dir) { + _dir = dir; + _time_step = time_step; + _start_time = (dir==FWD ? _time_step.lb() : _time_step.ub()); + _time_interval = time_step-_start_time; + _time_bound = + (dir==FWD ? time_step.ub()-Interval(_start_time) : + time_step.lb()-Interval(_start_time)); + } + + void update_init(const DomA &init) { + _init = init; + } + + void update_u(const IntervalVector &u) { + _u=u; + } + + protected: + ReachabilityStep(const DiffInclusionBase *diffinclusion) : + _diffinclusion(diffinclusion) { } + + const DiffInclusionBase *_diffinclusion; + StepDirection _dir; + double _start_time; + Interval _time_step; /* time value in the integration */ + Interval _time_interval; /* interval (0, end_time) or (-end_time,0) */ + Interval _time_bound; /* (end_time) or (-end_time) */ + DomA _init; + IntervalVector _u; + }; + + /* IntervalVector, 0-order reachability step */ + class ReachabilityStep0 : public + ReachabilityStep + { + public: + ReachabilityStep0(const DiffInclusionBase *diffinclusion, + double inflation_ratio=1.1, double inflation_base=1e-2) : + ReachabilityStep(diffinclusion), + _inflation_ratio(inflation_ratio), + _inflation_base(inflation_base) { + } + + std::pair get_inflation_options() const { + return { _inflation_ratio, _inflation_base }; + } + void set_inflation_options(std::pair options) { + std::tie(_inflation_ratio,_inflation_base) = + options; + } + + IntervalVector approx() const { return approx_base(_init); } + void inflate(IntervalVector &a) const override; + std::pair enclose + (const IntervalVector &b) const override; + IntervalVector intersect(const IntervalVector &b, + const IntervalVector &a) + const { + return (b & a); + } + static const IntervalVector & + intVect_from_DomainA(const IntervalVector &a) { + return a; + } + static const IntervalVector & + intVect_from_DomainB(const IntervalVector &b) { + return b; + } + + + private: + double _inflation_ratio; + double _inflation_base; + }; + + /* Zonotope, 1-order reachability step */ + class ReachabilityStep1 : public + ReachabilityStep + { + public: + ReachabilityStep1(const DiffInclusionBase *diffinclusion, + double max_zonotope_order=50.0, + std::pair inflation_options={1.1,1e-2}) : + ReachabilityStep(diffinclusion), + _inflation_ratio(inflation_options.first), + _inflation_base(inflation_options.second), + _max_zonotope_order(max_zonotope_order) { + } + + std::pair get_inflation_options() const { + return { _inflation_ratio, _inflation_base }; + } + void set_inflation_options(std::pair options) { + std::tie(_inflation_ratio,_inflation_base) = + options; + } + + double get_max_zonotope_order() const { + return _max_zonotope_order; + } + void set_max_zonotope_order(double value) { + _max_zonotope_order=value; + } + + static const IntervalVector + intVect_from_DomainA(const Zonotope &a) { + return a.box(); + } + static const IntervalVector & + intVect_from_DomainB(const IntervalVector &b) { + return b; + } + + Zonotope approx() const { return Zonotope(approx_base(_init.box())); } + void inflate(Zonotope &a) const override; + std::pair enclose + (const IntervalVector &b) const override; + IntervalVector intersect(const IntervalVector &b, const Zonotope &a) + const override; + + private: + double _inflation_ratio; + double _inflation_base; + double _max_zonotope_order; + }; + +} diff --git a/src/core/domains/zonotope/codac2_Zonotope.cpp b/src/core/domains/zonotope/codac2_Zonotope.cpp index 53f7d02f1..fbddc4f5c 100644 --- a/src/core/domains/zonotope/codac2_Zonotope.cpp +++ b/src/core/domains/zonotope/codac2_Zonotope.cpp @@ -9,9 +9,21 @@ #include "codac2_Zonotope.h" #include "codac2_inversion.h" +#include "codac2_arith_mul.h" namespace codac2 { + Zonotope::Zonotope(const IntervalVector& box) + : c(box.mid()) + { + A = Matrix::Identity(box.size(),box.size()); + if (box.is_empty()) { + empty_flag = true; + return; + } + for (Index i=0;iis_empty() && "Invalid operation on empty zonotope"); + + Vector c_sum = c + box.mid(); + IntervalVector box2 = (box - c_sum) + c; /* (c_sum - c) may be rounded */ + c = c_sum; + Index nbtoadd=0; + for (Index i=0;i0.0) nbtoadd++; + } + if (nbtoadd==0) return (*this); + for (Index i=A.cols()-1;i>=0;i--) { + /* decreasing because axis generators may have been added at the end */ + int nbnotzero=0; + Index idnotzero=-1; + for (Index j=0;j1) break; + idnotzero=j; + } + } + if (nbnotzero==1 && box2[idnotzero].mag()>0.0) { + A(idnotzero,i) += box2[idnotzero].mag(); /* rounded up ? */ + box2[idnotzero]=0.0; + nbtoadd--; + if (nbtoadd==0) return (*this); + } + } + Index col = A.cols(); + A.conservativeResize(Eigen::NoChange, A.cols()+nbtoadd); + for (Index i=0;i0.0) { + A.col(col)= Vector::Zero(A.rows()); + A(i,col) = box2[i].mag(); + col++; + } + } + return (*this); + } + + Zonotope Zonotope::transform(const IntervalMatrix &mat) const { + assert_release(!this->is_empty() && "Invalid operation on empty zonotope"); + Matrix matmid = mat.mid(); + Matrix newA = matmid*this->A; + IntervalVector boxadd = ((mat-matmid)*this->A.template cast())* + IntervalVector::constant(A.cols(),{-1,1}); + Zonotope Z(this->c,newA); + return (Z += boxadd); + } + + Zonotope &Zonotope::operator&=(const IntervalVector &box) { + if (this->is_empty()) return (*this); + if (box.is_empty()) { this->set_empty(); return (*this); } + if (this->box().is_subset(box)) return (*this); + IntervalVector rhs = IntervalVector::constant(A.cols(),{-1,1}); + IntervalMatrix cpA = this->A; + MulOp::bwd(box-this->c,cpA,rhs); + if (rhs.is_empty()) { this->set_empty(); return (*this); } + Vector delta = this->A*rhs.mid(); + this->c += delta; + for (Index i=0;iA.cols();i++) { + this->A.col(i) *= rhs[i].rad(); + } + return (*this); + } + + Zonotope Zonotope::operator& (const IntervalVector &box) const { + Zonotope ret(*this); + ret &= box; + return ret; + } + + Zonotope Zonotope::reduction(double o, bool invert) const { assert_release(o>=1.0 && "Zonotope reduction must give an order >= 1."); - if (empty_flag) return (*this); + if (this->is_empty()) return (*this); Index dim = A.rows(); if (A.cols() <= dim*o && !invert) return (*this); Index newcols = dim*o; diff --git a/src/core/domains/zonotope/codac2_Zonotope.h b/src/core/domains/zonotope/codac2_Zonotope.h index e778707ab..1fb561d72 100644 --- a/src/core/domains/zonotope/codac2_Zonotope.h +++ b/src/core/domains/zonotope/codac2_Zonotope.h @@ -1,9 +1,9 @@ /** * \file codac2_Zonotope.h * ---------------------------------------------------------------------------- - * \date 2025 - * \author Maël Godard - * \copyright Copyright 2024 Codac Team + * \date 2026 + * \author Maël Godard, Damien Massé + * \copyright Copyright 2026 Codac Team * \license GNU Lesser General Public License (LGPL) */ @@ -13,6 +13,7 @@ #include "codac2_Vector.h" #include "codac2_Matrix.h" #include "codac2_IntervalVector.h" +#include "codac2_IntervalMatrix.h" namespace codac2 { @@ -28,6 +29,17 @@ namespace codac2 { public: + /** + * \brief Constructs an invalid zonotope, for future assignment + */ + Zonotope() { }; + + /** + * \brief Constructs a zonotope from a box + * \param box The box + */ + Zonotope(const IntervalVector &box); + /** * \brief Constructs a n-zonotope object with a given center and shape matrix * @@ -90,6 +102,26 @@ namespace codac2 */ Zonotope operator+(const Zonotope& zonotope) const; + /** + * \brief Add an IntervalVector to the current zonotope. Create + * a new generator only if needed. + * + * \param box The other Zonotope to add to this one + * + * \return *(this) + */ + Zonotope& operator+=(const IntervalVector& box); + + /** + * \brief apply a transformation on A (keeping c) with an IntervalMatrix + * i.e. enclose { c, MA }. + * + * \param mat The matrix of interval vectors + * + * \return a new Zonotope + */ + Zonotope transform(const IntervalMatrix &mat) const; + /** * \brief Create a new zonotope englobing (*this) with at most * \f$n\times o\f$ columns (with \f$n\f$ the dimension of the zonotope. @@ -107,6 +139,25 @@ namespace codac2 */ Zonotope reduction(double o, bool invert=false) const; + /** + * \brief In-place intersection of a zonotope and a box. + * Not very precise but may be useful in some case. + * + * \param box the box to be intersected + * \return (*this) + */ + Zonotope &operator&=(const IntervalVector &box); + + /** + * \brief Intersection of a zonotope and a box. Not very precise + * but may be useful in some case. + * + * \param box the box to be intersected + * \return a new zonotope + */ + Zonotope operator&(const IntervalVector &box) const; + + /** * \brief Center of the zonotope */ @@ -121,6 +172,7 @@ namespace codac2 * \brief Flag indicating whether the zonotope is empty */ bool empty_flag = false; + }; /** @@ -131,4 +183,5 @@ namespace codac2 * \return The output stream with the zonotope information. */ std::ostream& operator<<(std::ostream& str, const Zonotope& z); + } diff --git a/src/core/functions/analytic/codac2_AnalyticFunction.h b/src/core/functions/analytic/codac2_AnalyticFunction.h index 7d569e124..0ed9fd6a2 100644 --- a/src/core/functions/analytic/codac2_AnalyticFunction.h +++ b/src/core/functions/analytic/codac2_AnalyticFunction.h @@ -93,6 +93,13 @@ namespace codac2 return eval(x...).mid(); } + + template + T eval_and_diff(const Args&... x) const + { + return eval_(x...); + } + template typename T::Domain eval(const EvalMode& m, const Args&... x) const { @@ -378,4 +385,4 @@ namespace codac2 AnalyticFunction(const FunctionArgsList&, const T&) -> AnalyticFunction::Type>; -} \ No newline at end of file +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d933ab001..da51780ce 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -91,6 +91,8 @@ list(APPEND SRC_TESTS # listing files without extension core/operators/codac2_tests_operators + core/diffinclusions/codac2_tests_DiffInclusion + core/peibos/codac2_tests_peibos core/separators/codac2_tests_SepCartProd diff --git a/tests/core/diffinclusions/codac2_tests_DiffInclusion.cpp b/tests/core/diffinclusions/codac2_tests_DiffInclusion.cpp new file mode 100644 index 000000000..bf86079be --- /dev/null +++ b/tests/core/diffinclusions/codac2_tests_DiffInclusion.cpp @@ -0,0 +1,85 @@ +/** + * Codac tests + * ---------------------------------------------------------------------------- + * \date 2026 + * \author Damien Massé + * \copyright Copyright 2026 Codac Team + * \license GNU Lesser General Public License (LGPL) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace codac2; + +TEST_CASE("AnalyticFunction") +{ + { + ScalarVar x; + ScalarVar u; + AnalyticFunction f({x,u}, -x+u); + DiffInclusion di(f); + /* with x(0)=1 and u=u_m + [-eps,eps], + x \in u_m(1-e^-t) + e^-t + [-1,1] eps | e^t - 1 | */ + + DI_Integration, + RS_box> integration(di); + { + IntervalVector i1({{-5.0,5.0}}), i2({{-5.0,5.0}}); + + + auto r = integration.contract_one_step(Interval(0.0,0.1), + IntervalVector({1.0}), i1,i2, Interval(0.0,0.2)); + // "exact" gate : [0.9048, 0.9239] + // "exact" inside : [0.9048, 1] + // result obtained : [0.8999, 0.9301] + CHECK(r); + CHECK(i1[0].is_superset(Interval(0.9048,1))); + CHECK(i2[0].is_superset(Interval(0.9048,0.9239))); + } + { + IntervalVector i1({{-5.0,5.0}}), i2({{-5.0,5.0}}); + bool r = integration.contract_one_step(Interval(-0.1,0.0), + IntervalVector({1.0}), i1,i2, Interval(0.0,0.2),false); + // "exact" : [1.0841, 1.1052] + // "exact" : [1.0000, 1.1052] + // result obtained : [1.0799, 1.1112] + CHECK(r); + CHECK(i1[0].is_superset(Interval(1,1.1052))); + CHECK(i2[0].is_superset(Interval(1.0841,1.1052))); + } + } + { + VectorVar x(2); + ScalarVar u; + AnalyticFunction f({x,u}, {-x[1]+u, x[0]}); + DiffInclusion di(f); + /* with x(0)=(1,0) and u=[0], + x = (cos(t),sin(t)) */ + DI_Integration, + RS_box> integration(di); + + { + IntervalVector i1 {{-5.0,5.0},{-5.0,5.0}}; + IntervalVector i2 {{-5.0,5.0},{-5.0,5.0}}; + bool r = integration.contract_one_step(Interval(0.0,0.1), + IntervalVector({1.0,0.0}), + i1,i2, Interval(0.0,0.0),true); + /* "exact" gate : [0.9950,0.9951],[0.0998,0.0999] */ + /* obtained : [0.9899,1], [0.09899,0.1000] */ + CHECK(r); + CHECK(i1.contains(Vector({cos(0.1),sin(0.1)}))); + } + } +} diff --git a/tests/core/diffinclusions/codac2_tests_DiffInclusion.py b/tests/core/diffinclusions/codac2_tests_DiffInclusion.py new file mode 100644 index 000000000..a1659ee90 --- /dev/null +++ b/tests/core/diffinclusions/codac2_tests_DiffInclusion.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +# Codac tests +# ---------------------------------------------------------------------------- +# \date 2026 +# \author Simon Rohou +# \copyright Copyright 2026 Codac Team +# \license GNU Lesser General Public License (LGPL) + +import unittest +from codac import * + + +class TestDiffInclusion(unittest.TestCase): + + def test_DiffInclusion(self): + + x = VectorVar(1) + u = VectorVar(1) + f = AnalyticFunction([x,u],-x+u) + + di = DiffInclusion(f) + + integration = Integration_Box(di) + + i1 = IntervalVector([[-5,5]]) + i2 = IntervalVector([[-5,5]]) + r = integration.contract_one_step(Interval(0.0,0.1), + IntervalVector([[1.0]]), i1, i2, IntervalVector([[0.0,0.2]])) + + self.assertTrue(r) + self.assertTrue(i1[0].is_superset(Interval(0.9048,1))) + self.assertTrue(i2[0].is_superset(Interval(0.9048,0.9239))) + +if __name__ == '__main__': + unittest.main()