F.57. seg

Этот модуль реализует тип данных seg для представления отрезков или интервалов чисел с плавающей точкой. Тип seg может выражать отсутствие уверенности в границах интервала, что позволяет применять его для представления лабораторных измерений.

Данный модуль считается «доверенным», то есть его могут устанавливать обычные пользователи, имеющие право CREATE в текущей базе данных.

F.57.1. Обоснование

Геометрия измерений обычно более сложна, чем точка в числовом континууме. Измерение обычно представляет собой отрезок этого континуума с нечёткими границами. Измеряемые показатели выражаются интервалами вследствие неопределённости и случайности, а также того, что измеряемое значение может отражать некоторое условие, например, диапазон температур стабильности протеина.

Руководствуясь только здравым смыслом, кажется более удобным хранить такие данные в виде интервалов, а не в виде двух отдельных чисел. На практике это оказывается даже эффективнее в большинстве приложений.

Более того, вследствие нечёткости границ использование традиционных числовых типов данных приводит к определённой потере информации. Рассмотрим такой пример: ваш инструмент выдаёт 6.50 и вы вводите это значение в базу данных. Что вы получите, прочитав это значение из базы? Смотрите:

test=> select 6.50 :: float8 as "pH";
 pH
---
6.5
(1 row)

В мире измерений, 6.50 — не то же самое, что 6.5. И разница между этими измерениями иногда бывает критической. Экспериментаторы обычно записывают (и публикуют) цифры, которые заслуживают доверия. Запись 6.50 на самом деле представляет неточный интервал, содержащийся внутри большего и ещё более неточного интервала, 6.5, и единственное, что у них может быть общего, это их центральные точки. Поэтому мы определённо не хотим, чтобы такие разные элементы данных выглядели одинаково.

Вывод? Удобно иметь специальный тип данных, в котором можно сохранить границы интервала с произвольной переменной точностью. В данном случае точность переменная в том смысле, что для каждого элемента данных она может записываться индивидуально.

Проверьте это:

test=> select '6.25 .. 6.50'::seg as "pH";
          pH
------------
6.25 .. 6.50
(1 row)

F.57.2. Синтаксис

Внешнее представление интервала образуется одним или двумя числами с плавающей точкой, соединёнными оператором диапазона (.. или ...). Кроме того, интервал можно задать центральной точкой плюс/минус отклонение. Также этот тип позволяет сохранить дополнительные индикаторы достоверности (<, > или ~). (Однако индикаторы достоверности игнорируются всеми встроенными операторами.) Допустимые представления показаны в Таблице F.35; некоторые примеры приведены в Таблице F.36.

В Таблице F.35 символы x, y и delta обозначают числа с плавающей точкой. Перед значениями x и y, но не delta, может быть добавлен индикатор достоверности.

Таблица F.35. Внешнее представление seg

xОдно значение (интервал нулевой длины)
x .. yИнтервал от x до y
x (+-) deltaИнтервал от x - delta до x + delta
x ..Открытый интервал с нижней границей x
.. xОткрытый интервал с верхней границей x

Таблица F.36. Примеры допустимых вводимых значений seg

5.0Создаёт сегмент нулевой длины (или точку, если хотите)
~5.0Создаёт сегмент нулевой длины и записывает ~ в данные. Знак ~ игнорируется при операциях с seg, но сохраняется как комментарий.
<5.0Создаёт точку с координатой 5.0. Знак < игнорируется, но сохраняется как комментарий.
>5.0Создаёт точку с координатой 5.0. Знак > игнорируется, но сохраняется как комментарий.
5(+-)0.3Создаёт интервал 4.7 .. 5.3. Заметьте, что запись (+-) не сохраняется.
50 ..Всё, что больше или равно 50
.. 0Всё, что меньше или равно 0
1.5e-2 .. 2E-2Создаёт интервал 0.015 .. 0.02
1 ... 2То же, что и 1...2, либо 1 .. 2, либо 1..2 (пробелы вокруг оператора диапазона игнорируются)

Так как оператор ... часто используется в источниках данных, он принимается в качестве альтернативного написания оператора ... К сожалению, это порождает неоднозначность при разборе: неясно, какая верхняя граница имеется в виду в записи 0...2323 или 0.23. Для разрешения этой неоднозначности во входных числах seg перед десятичной точкой всегда должна быть минимум одна цифра.

В качестве меры предосторожности, seg не принимает интервалы с нижней границей, превышающей верхнюю, например: 5 .. 2.

F.57.3. Точность

Значения seg хранятся внутри как пары 32-битных чисел с плавающей точкой. Это значит, что числа с более чем 7 значащими цифрами будут усекаться.

Числа, содержащие 7 и меньше значащих цифр, сохраняют изначальную точность. То есть, если запрос возвращает 0.00, вы можете быть уверены, что конечные нули не являются артефактами форматирования: они отражают точность исходных данных. Количество ведущих нулей не влияет на точность: значение 0.0067 будет считаться имеющим только две значащих цифры.

F.57.4. Использование

Модуль seg включает класс операторов индекса GiST для значений seg. Операторы, поддерживаемые этим классом операторов, перечислены в Таблице F.37.

Таблица F.37. Операторы seg для GiST

Оператор

Описание

seg << segboolean

Первый seg полностью находится левее второго? [a, b] << [c, d] — true, если b < c.

seg >> segboolean

Первый seg полностью находится правее второго? [a, b] >> [c, d] — true, если a > d.

seg &< segboolean

Первый seg не простирается правее второго? [a, b] &< [c, d] — true, если b <= d.

seg &> segboolean

Первый seg не простирается левее второго? [a, b] &> [c, d] — true, если a >= c.

seg = segboolean

Два отрезка seg равны?

seg && segboolean

Два отрезка seg пересекаются?

seg @> segboolean

Первый seg содержит второй?

seg <@ segboolean

Первый seg содержится во втором?


Также для типа seg поддерживаются стандартные операторы сравнения, показанные в Таблица 9.1. Эти операторы сначала сравнивают (a) с (c), и если они равны, сравнивают (b) с (d). Результат сравнения позволяет упорядочить значения образом, подходящим для большинства случаев, что полезно, если вы хотите применять ORDER BY с этим типом.

F.57.5. Примечания

Примеры использования можно увидеть в регрессионном тесте sql/seg.sql.

Механизм, преобразующий (+-) в обычные диапазоны, не вполне точно определяет число значащих цифр для границ. Например, он добавляет дополнительную цифру к нижней границе, если результирующий интервал включает степень десяти:

postgres=> select '10(+-)1'::seg as seg;
      seg
---------
9.0 .. 11             -- должно быть: 9 .. 11

Производительность индекса-R-дерева может значительно зависеть от начального порядка вводимых значений. Может быть очень полезно отсортировать входную таблицу по столбцу seg; пример можно найти в скрипте sort-segments.pl.

F.57.6. Благодарности

Первый автор: Джин Селков мл. , Аргоннская национальная лаборатория, Отдел математики и компьютерных наук

Я очень благодарен в первую очередь профессору Джо Геллерштейну (https://dsf.berkeley.edu/jmh/) за пояснение сути GiST (http://gist.cs.berkeley.edu/). Я также признателен всем разработчикам Postgres в настоящем и прошлом за возможность создать свой собственный мир и спокойно жить в нём. Ещё я хотел бы выразить признательность Аргоннской лаборатории и Министерству энергетики США за годы постоянной поддержки моих исследований в области баз данных.

F.57. seg

This module implements a data type seg for representing line segments, or floating point intervals. seg can represent uncertainty in the interval endpoints, making it especially useful for representing laboratory measurements.

This module is considered trusted, that is, it can be installed by non-superusers who have CREATE privilege on the current database.

F.57.1. Rationale

The geometry of measurements is usually more complex than that of a point in a numeric continuum. A measurement is usually a segment of that continuum with somewhat fuzzy limits. The measurements come out as intervals because of uncertainty and randomness, as well as because the value being measured may naturally be an interval indicating some condition, such as the temperature range of stability of a protein.

Using just common sense, it appears more convenient to store such data as intervals, rather than pairs of numbers. In practice, it even turns out more efficient in most applications.

Further along the line of common sense, the fuzziness of the limits suggests that the use of traditional numeric data types leads to a certain loss of information. Consider this: your instrument reads 6.50, and you input this reading into the database. What do you get when you fetch it? Watch:

test=> select 6.50 :: float8 as "pH";
 pH
---
6.5
(1 row)

In the world of measurements, 6.50 is not the same as 6.5. It may sometimes be critically different. The experimenters usually write down (and publish) the digits they trust. 6.50 is actually a fuzzy interval contained within a bigger and even fuzzier interval, 6.5, with their center points being (probably) the only common feature they share. We definitely do not want such different data items to appear the same.

Conclusion? It is nice to have a special data type that can record the limits of an interval with arbitrarily variable precision. Variable in the sense that each data element records its own precision.

Check this out:

test=> select '6.25 .. 6.50'::seg as "pH";
          pH
------------
6.25 .. 6.50
(1 row)

F.57.2. Syntax

The external representation of an interval is formed using one or two floating-point numbers joined by the range operator (.. or ...). Alternatively, it can be specified as a center point plus or minus a deviation. Optional certainty indicators (<, > or ~) can be stored as well. (Certainty indicators are ignored by all the built-in operators, however.) Table F.35 gives an overview of allowed representations; Table F.36 shows some examples.

In Table F.35, x, y, and delta denote floating-point numbers. x and y, but not delta, can be preceded by a certainty indicator.

Table F.35. seg External Representations

xSingle value (zero-length interval)
x .. yInterval from x to y
x (+-) deltaInterval from x - delta to x + delta
x ..Open interval with lower bound x
.. xOpen interval with upper bound x

Table F.36. Examples of Valid seg Input

5.0 Creates a zero-length segment (a point, if you will)
~5.0 Creates a zero-length segment and records ~ in the data. ~ is ignored by seg operations, but is preserved as a comment.
<5.0 Creates a point at 5.0. < is ignored but is preserved as a comment.
>5.0 Creates a point at 5.0. > is ignored but is preserved as a comment.
5(+-)0.3 Creates an interval 4.7 .. 5.3. Note that the (+-) notation isn't preserved.
50 .. Everything that is greater than or equal to 50
.. 0Everything that is less than or equal to 0
1.5e-2 .. 2E-2 Creates an interval 0.015 .. 0.02
1 ... 2 The same as 1...2, or 1 .. 2, or 1..2 (spaces around the range operator are ignored)

Because the ... operator is widely used in data sources, it is allowed as an alternative spelling of the .. operator. Unfortunately, this creates a parsing ambiguity: it is not clear whether the upper bound in 0...23 is meant to be 23 or 0.23. This is resolved by requiring at least one digit before the decimal point in all numbers in seg input.

As a sanity check, seg rejects intervals with the lower bound greater than the upper, for example 5 .. 2.

F.57.3. Precision

seg values are stored internally as pairs of 32-bit floating point numbers. This means that numbers with more than 7 significant digits will be truncated.

Numbers with 7 or fewer significant digits retain their original precision. That is, if your query returns 0.00, you will be sure that the trailing zeroes are not the artifacts of formatting: they reflect the precision of the original data. The number of leading zeroes does not affect precision: the value 0.0067 is considered to have just 2 significant digits.

F.57.4. Usage

The seg module includes a GiST index operator class for seg values. The operators supported by the GiST operator class are shown in Table F.37.

Table F.37. Seg GiST Operators

Operator

Description

seg << segboolean

Is the first seg entirely to the left of the second? [a, b] << [c, d] is true if b < c.

seg >> segboolean

Is the first seg entirely to the right of the second? [a, b] >> [c, d] is true if a > d.

seg &< segboolean

Does the first seg not extend to the right of the second? [a, b] &< [c, d] is true if b <= d.

seg &> segboolean

Does the first seg not extend to the left of the second? [a, b] &> [c, d] is true if a >= c.

seg = segboolean

Are the two segs equal?

seg && segboolean

Do the two segs overlap?

seg @> segboolean

Does the first seg contain the second?

seg <@ segboolean

Is the first seg contained in the second?


In addition to the above operators, the usual comparison operators shown in Table 9.1 are available for type seg. These operators first compare (a) to (c), and if these are equal, compare (b) to (d). That results in reasonably good sorting in most cases, which is useful if you want to use ORDER BY with this type.

F.57.5. Notes

For examples of usage, see the regression test sql/seg.sql.

The mechanism that converts (+-) to regular ranges isn't completely accurate in determining the number of significant digits for the boundaries. For example, it adds an extra digit to the lower boundary if the resulting interval includes a power of ten:

postgres=> select '10(+-)1'::seg as seg;
      seg
---------
9.0 .. 11             -- should be: 9 .. 11

The performance of an R-tree index can largely depend on the initial order of input values. It may be very helpful to sort the input table on the seg column; see the script sort-segments.pl for an example.

F.57.6. Credits

Original author: Gene Selkov, Jr. , Mathematics and Computer Science Division, Argonne National Laboratory.

My thanks are primarily to Prof. Joe Hellerstein (https://dsf.berkeley.edu/jmh/) for elucidating the gist of the GiST (http://gist.cs.berkeley.edu/). I am also grateful to all Postgres developers, present and past, for enabling myself to create my own world and live undisturbed in it. And I would like to acknowledge my gratitude to Argonne Lab and to the U.S. Department of Energy for the years of faithful support of my database research.