GithubHelp home page GithubHelp logo

androsovas / intvalpy Goto Github PK

View Code? Open in Web Editor NEW
9.0 2.0 3.0 6.5 MB

IntvalPy - a Python interval computation library

Home Page: https://intvalpy.readthedocs.io

License: MIT License

Python 100.00%
python linear-systems visualization inequalities library intervals optimal-solution interval-arithmetic

intvalpy's Introduction

Interval library in Python

The Python module implements an algebraically closed interval arithmetic for interval computations, solving interval systems of both linear and nonlinear equations, and visualizing solution sets for interval systems of equations.

For details, see the complete documentation on API.

Installation

Make sure you have all the system-wide dependencies, then install the module itself:

pip install intvalpy

Examples

Visualizing solution sets

For a system of linear inequalities of the form A * x >= b or for an interval system of linear algebraic equations A * x = b, the solution sets are known to be polyhedral sets, convex or non-convex. We can visualize them and display all their vertices:

import intvalpy as ip
ip.precision.extendedPrecisionQ = False
import numpy as np


iplt = ip.IPlot(figsize=(15, 15))
fig, ax = iplt.subplots(nrows=2, ncols=2)


#########################################################################
A, b = ip.Shary(2)
shary_uni = ip.IntLinIncR2(A, b, show=False)
shary_tol = ip.IntLinIncR2(A, b, consistency='tol', show=False)

axindex = (0, 0)
ax[axindex].set_title('United and tolerable solution sets for the Shary interval system')
ax[axindex].title.set_size(15)
iplt.IntLinIncR2(shary_uni, color='gray', alpha=0.5, s=0, axindex=axindex)
iplt.IntLinIncR2(shary_tol, color='blue', alpha=0.3, s=10, axindex=axindex)

#########################################################################
A = ip.Interval([
    [[-1, 1], [-1, 1]],
    [[-1, -1], [-1, 1]]
])
b = ip.Interval([[1, 1], [-2, 2]])
unconstrained_set = ip.IntLinIncR2(A, b, show=False)

axindex = (0, 1)
ax[axindex].set_title('Unbounded set')
ax[axindex].title.set_size(15)
iplt.IntLinIncR2(unconstrained_set, color='darkolivegreen', alpha=0.3, s=10, axindex=axindex)

#########################################################################
A = -np.array([[-3, -1],
              [-2, -2],
              [-1, -3],
              [1, -3],
              [2, -2],
              [3, -1],
              [3, 1],
              [2, 2],
              [1, 3],
              [-1, 3],
              [-2, 2],
              [-3, 1]])
b = -np.array([18,16,18,18,16,18,18,16,18,18,16,18])
duodecagon = ip.lineqs(A, b, show=False)

axindex = (1, 0)
ax[axindex].set_title('Duodecagon')
ax[axindex].title.set_size(15)
iplt.lineqs(duodecagon, color='peru', alpha=0.3, s=10, axindex=axindex)

#########################################################################
x = ip.Interval([[1, 1.2], [1.9, 2.7], [1.7, 1.95], [3.5, 3.5],
                 [4.5, 5.5], [6, 6], [6.5, 7.5], [7, 7.8]])
y = ip.Interval([[4, 4.3], [4.5, 5.3], [4.6, 4.8], [5.1, 6],
                 [6, 6.5], [7, 7], [6.7, 7.4], [6.8, 8]])

axindex = (1, 1)
ax[axindex].set_title('Interval scatterplot')
ax[axindex].title.set_size(15)
iplt.scatter(x, y, color='gray', alpha=0.7, s=10, axindex=axindex)

SolSet

It is also possible to make a three-dimensional (two-dimensional) slice of an N-dimensional figure and see what the set of solutions looks like with fixed N-3 (N-2) parameters. A specific implementation of the algorithm can be found in the examples. As a result, a gif image of the united set of solutions of the system proposed by S.P. Sharym is shown below, during the evolution of the 4th unknown.

Shary4Uni

Recognizing functionals:

Before we start solving a system of equations with interval data it is necessary to understand whether it is solvable or not. To do this we consider the problem of decidability recognition, i.e. non-emptiness of the set of solutions. In the case of an interval linear (m x n)-system of equations, we will need to solve no more than 2\ :sup:n linear inequalities of size 2m+n. This follows from the fact of convexity and polyhedra of the intersection of the sets of solutions interval system of linear algebraic equations (ISLAE) with each of the orthants of R\ :sup:n space. Reducing the number of inequalities is fundamentally impossible, which follows from the fact that the problem is intractable, i.e. its NP-hardness. It is clear that the above described method is applicable only for small dimensionality of the problem, that is why the recognizing functional method was proposed.

After global optimization, if the value of the functional is non-negative, then the system is solvable. If the value is negative, then the set of parameters consistent with the data is empty, but the argument delivering the maximum of the functional minimizes this inconsistency.

As an example, it is proposed to investigate the Bart-Nuding system for the emptiness/non-emptiness of the tolerance set of solutions:

import intvalpy as ip
# transition from extend precision (type mpf) to double precision (type float)
# ip.precision.extendedPrecisionQ = False

A = ip.Interval([
  [[2, 4], [-2, 1]],
  [[-1, 2], [2, 4]]
])
b = ip.Interval([[-2, 2], [-2, 2]])

tol = ip.linear.Tol.maximize(
    A = A, 
    b = b,
    x0 = None,
    weight = None,
    linear_constraint = None
)
print(tol)

External decision evaluation:

To obtain an optimal external estimate of the united set of solutions of an interval system linear of algebraic equations (ISLAE), a hybrid method of splitting PSS solutions is implemented. Since the task is NP-hard, the process can be stopped by the number of iterations completed. PSS methods are consistently guaranteeing, i.e. when the process is interrupted at any number of iterations, an approximate estimate of the solution satisfies the required estimation method.

import intvalpy as ip
# transition from extend precision (type mpf) to double precision (type float)
# ip.precision.extendedPrecisionQ = False

A, b = ip.Shary(12, N=12, alpha=0.23, beta=0.35)
pss = ip.linear.PSS(A, b)
print('pss: ', pss)

Interval system of nonlinear equations:

For nonlinear systems, the simplest multidimensional interval methods of Krawczyk and Hansen-Sengupta are implemented for solving nonlinear systems:

import intvalpy as ip
# transition from extend precision (type mpf) to double precision (type float)
# ip.precision.extendedPrecisionQ = False

epsilon = 0.1
def f(x):
    return ip.asinterval([x[0]**2 + x[1]**2 - 1 - ip.Interval(-epsilon, epsilon),
                          x[0] - x[1]**2])

def J(x):    
    result = [[2*x[0], 2*x[1]],
              [1, -2*x[1]]]
    return ip.asinterval(result)

ip.nonlinear.HansenSengupta(f, J, ip.Interval([0.5,0.5],[1,1]))

The library also provides the simplest interval global optimization:

import intvalpy as ip
# transition from extend precision (type mpf) to double precision (type float)
# ip.precision.extendedPrecisionQ = False

def levy(x):
    z = 1 + (x - 1) / 4
    t1 = np.sin( np.pi * z[0] )**2
    t2 = sum(((x - 1) ** 2 * (1 + 10 * np.sin(np.pi * x + 1) ** 2))[:-1])
    t3 = (z[-1] - 1) ** 2 * (1 + np.sin(2*np.pi * z[-1]) ** 2)
    return t1 + t2 + t3

N = 2
x = ip.Interval([-5]*N, [5]*N)
ip.nonlinear.globopt(levy, x, tol=1e-14)

Links

intvalpy's People

Contributors

androsovas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

intvalpy's Issues

not able to plot polytope

Dear Developer
I try to plot a polytope via intvalpy. i face the following error message

IndexError Traceback (most recent call last)
Input In [50], in <cell line: 1>()
----> 1 v=plot_poly3dnew(s2n[0], ax, color ='C1')

Input In [42], in plot_poly3dnew(poly, ax, alpha, color)
35 dim=poly.dim
37 if dim == 3:
---> 38 v = ip.lineqs3D(-poly.A, -poly.b, size=(3,3), show=False)
39 for i in v:
40 x, y, z = i[:,0], i[:,1], i[:,2]

File ~\AppData\Local\Programs\Python\Python39\lib\site-packages\intvalpy\visualization.py:607, in lineqs3D(A, b, show, color, alpha, s, size, bounds)
605 #print("St = BoundaryIntervals(At, bt) ", St)
606 if len(St) > 0:
--> 607 Pt = Intervals2Path(St)
608 P = []
609 for l in range(len(Pt)):

File ~\AppData\Local\Programs\Python\Python39\lib\site-packages\intvalpy\visualization.py:160, in Intervals2Path(S)
158 index = k
159 break
--> 160 es = S[index, 2:4]
162 if np.max(np.abs(bs-es)) > 1e-8:
163 P.append(es)

IndexError: index 3 is out of bounds for axis 0 with size 3

I checked the dimension of polytope and it is 3D polyhedron. I do not know why the BoundaryIntervals failes to creae the facet.
your suggestion will be more helpful to figure out the causes for this problem

any comments is highly appreciated

Thank you

Best regards
Muthu
Researcher
TU freiberg, Germany

Повышенная точность

При вычислении функций sin, cos, exp и т.п., не сохраняется повышенная точность.
Необходимо использовать библиотеку mpmath, а не math.

Лишние np.array при __setitem__

При срабатывания setitem, если присваивается одиночный интервал, создаются лишние np.array

Example:
import intvalpy as ip

test = ip.zeros(2)
test[0] = ip.Interval(2, 3)
test.a

ФР: array([array(mpf('2.0'), dtype=object), mpf('0.0')], dtype=object)
ОР: array([mpf('2.0'), mpf('0.0')], dtype=object)

Работа с неопределённостями

Необходимо добавить отдельную функцию infinity для работы с бесконечностью, а также решить проблему возникающую при умножение 0 * inf

Обозначение повышенной точности

В текущий момент используется термин increased precision. Однако существует определение extended precision, которое соответсвует стандарту IEEE 754-2008.

Создание интервалов

Добавить возможность создавать интервалы через середину и радиус, или через задание одного массива.

Tol() takes no arguments

I took code from the example here https://pypi.org/project/intvalpy/ .
Example:

import intvalpy as ip
A = ip.Interval([
[[2, 4], [-2, 1]],
[[-1, 2], [2, 4]]
])
b = ip.Interval([[-2, 2], [-2, 2]])
tol = ip.linear.Tol(A, b, maxQ=True)
print(tol)

When I try to run it I get an error: "TypeError: Tol() takes no arguments"
Can anyone tell me what is wrong and how to fix it?
Thanks

Направленные округления

Необходимо реализовать направленные округления, которые при желании можно отключать (для ускорения работы алгоритмов).

dtype для интервала

Было бы удобно иметь в пакете dtype который можно использовать при конструкции numpy массивов и для других пакетов поддерживающих dtype типизацию.
В моем случае я хотел создать разреженную матрицу в scipy для хранения интервалов. Но тот же scipy не поддерживает стандартный python объект как dtype (так как разреженные матрицы могут быть очень большими у них применяются различные техники для сжатия данных, реализация таких техник в контексте ванильного питон объекта невозможна)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.