tdfs4ds.plot_periods¶
tdfs4ds.plot_periods
¶
Historian charts per period, and A-vs-B charts of two historian tags (0.3.8.10).
A historian (deep) table holds one row per (ids, timestamp, tag) with the value in a
payload column (see :func:tdfs4ds.plotting.historian_layout). This module adds two
kinds of chart to :mod:tdfs4ds.plotting, both drawn by TD_PLOT through the same
:func:~tdfs4ds.plotting.panel / :func:~tdfs4ds.plotting.plot_panels machinery:
- Tag A versus tag B (:func:
plot_historian_xy): the two tags averaged per (ids, time bucket) inside a window, one point per bucket, one series per id. The bucket is chosen so a series stays neartdfs4ds.PLOT_XY_POINTS_PER_SERIESpoints. - Per period (:func:
period_rows, :func:plot_historian_by_periods): a table or view of PERIODS (one row per item: an id, the key columns that match the historian's id columns - a line, a machine -, a start and an end) gives one series per row. The historian is read only on that row's key values and between its start and end: oneUNION ALLbranch per row with literal bounds (:func:tdfs4ds.plotting.aligned_source_sql). Rows can be kept by conditions on the dataset's columns (:func:dataset_condition_sql: operator whitelist, typed literals, units from the column documentation) and on an aggregate of a tag over each row's own period (:func:filter_periods_by_tag).
Nothing from a request is pasted into SQL as is: names are checked against the real
columns, values become typed literals (sql_literal, quote_ident).
UNITS
module-attribute
¶
UNITS = {'nm': ('length', 1e-09), 'um': ('length', 1e-06), 'µm': ('length', 1e-06), 'mm': ('length', 0.001), 'cm': ('length', 0.01), 'dm': ('length', 0.1), 'm': ('length', 1.0), 'km': ('length', 1000.0), 'mg': ('mass', 1e-06), 'g': ('mass', 0.001), 'kg': ('mass', 1.0), 't': ('mass', 1000.0), 'mW': ('power', 0.001), 'W': ('power', 1.0), 'kW': ('power', 1000.0), 'MW': ('power', 1000000.0), 'Wh': ('energy', 1.0), 'kWh': ('energy', 1000.0), 'MWh': ('energy', 1000000.0), 'ms': ('time', 0.001), 's': ('time', 1.0), 'min': ('time', 60.0), 'h': ('time', 3600.0), 'mbar': ('pressure', 100.0), 'bar': ('pressure', 100000.0), 'Pa': ('pressure', 1.0), 'kPa': ('pressure', 1000.0), '%': ('ratio', 1.0), '°C': ('celsius', 1.0), 'rpm': ('rotation', 1.0)}
_UNIT_WORDS
module-attribute
¶
_UNIT_WORDS = {'nanometer': 'nm', 'nanometre': 'nm', 'micrometer': 'um', 'micrometre': 'um', 'micron': 'um', 'millimeter': 'mm', 'millimetre': 'mm', 'millimètre': 'mm', 'centimeter': 'cm', 'centimetre': 'cm', 'centimètre': 'cm', 'meter': 'm', 'metre': 'm', 'mètre': 'm', 'kilometer': 'km', 'kilometre': 'km', 'kilomètre': 'km', 'gram': 'g', 'gramme': 'g', 'kilogram': 'kg', 'kilogramme': 'kg', 'ton': 't', 'tonne': 't', 'watt': 'W', 'kilowatt': 'kW', 'megawatt': 'MW', 'mégawatt': 'MW', 'second': 's', 'seconde': 's', 'minute': 'min', 'hour': 'h', 'heure': 'h', 'percent': '%', 'pourcent': '%', 'degree celsius': '°C', 'degré celsius': '°C', 'celsius': '°C'}
_UNIT_IN_DESC_RE
module-attribute
¶
_UNIT_IN_DESC_RE = re.compile('\\b(?:in|en|unit[ée]?s?\\s*[:=]?|unit\\s*[:=]|expressed\\s+in|exprim[ée]e?s?\\s+en)\\s+(?:the\\s+|les\\s+|des\\s+)?([A-Za-zµ°%][\\wµ°%]*(?:\\s+celsius)?)', re.IGNORECASE)
_UNIT_IN_BRACKETS_RE
module-attribute
¶
_NICE_BUCKETS
module-attribute
¶
_NICE_BUCKETS = (1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400, 172800, 604800)
ConditionError
¶
Bases: ValueError
A condition that cannot be applied as given. kind: unknown_column, bad_operator,
bad_value, unit_unknown (the column documents no unit), unit_mismatch,
unknown_value (a category value the column does not hold: values lists the stored ones).
quote_ident
¶
:func:quote_ident for a column read from a user's table, which may also be a
reserved word (a historian payload named value made the plot SQL fail, Error 3706).
A name that is neither reserved nor in need of quotes is returned untouched, so every SQL statement that worked before is unchanged; only SQL that was refused changes. Not used for the package's own objects (see Reserved words above).
qualified
¶
Build db.obj with each part quoted only as needed.
qualified('TDB', 'FS_X') == 'TDB.FS_X' (unchanged for ordinary names);
qualified('SVC@CORP', 'FS_X') == '"SVC@CORP".FS_X'. An empty/None
database yields the bare object name, so unqualified callers keep working.
force=True quotes both parts unconditionally — only for the sites that
have always emitted quotes and whose exact text is already persisted (dataset
view DDL, returned volatile-table names).
split_qualified
¶
Split db.obj into (database, object), both de-quoted.
Quote-aware, so a dot inside a quoted part does not split the name:
split_qualified('"DEINF.CARLOSN"."FS_X"') == ('DEINF.CARLOSN', 'FS_X').
The naive rsplit('.', 1) this replaces returns ('"DEINF.CARLOSN"',
'"FS_X"') only by luck and ('"DEINF', 'CARLOSN"."FS_X"') in the
split('.') variant.
An unqualified name returns ('', name).
sql_literal
¶
Escape value for use inside a single-quoted SQL string literal.
For the DBC probes and catalog predicates that compare a name as data
(WHERE DatabaseName = '…'). The caller supplies the surrounding quotes.
normalise_unit
¶
The symbol of a unit written as a symbol or a word ("km", "kilometres", "kW"), else None. Pure.
column_unit
¶
The unit a column's (or a tag's) documentation states: in brackets in its name or description ("Length (m)"), "unit: km", "in metres", "en mètres". None when it states none (the caller then asks; a unit is never guessed). Pure.
convert
¶
value in from_unit expressed in to_unit; ValueError across dimensions. Pure.
dataset_condition_sql
¶
dataset_condition_sql(columns: Dict[str, str], conditions, *, descriptions: Optional[Dict[str, str]] = None, stored_values: Optional[Callable] = None)
(predicate, notes): the conditions joined by AND, every part checked. Raises
:class:ConditionError.
conditions: [{"column", "op", "value", "unit"}] or (column, op, value[, unit])
tuples. columns: {name: HELP COLUMN type code}. Operators: :data:CONDITION_OPS
(BETWEEN takes (low, high), IN a list).
- number column: a number; with a unit, converted to the unit the column's documentation
states (descriptions:
{column: text}, :func:column_unit); no documented unit = aunit_unknownerror, never a guess. Without a unit the value is used as is. - date / timestamp column: a date or timestamp, compared as a typed literal.
- text column (a category):
=,<>orIN; each value is matched against the column's stored values by stored_values(column, values) -> (matched, existing) (case-insensitive, the stored spelling is kept); an unknown value =unknown_valuecarrying the existing values. Without stored_values the values are used as given.
describe_condition
¶
A condition as text for an answer or a rephrased question ("LEVEL_M > 1000"). Pure.
stored_values_reader
¶
A stored_values callable for :func:dataset_condition_sql over source: the given
values matched case-insensitively against the column (stored spelling), and up to limit
existing values of the column (asked when a value is unknown).
period_rows
¶
period_rows(dataset: str, *, key_col: str, start_col: str, end_col: str, id_map: Dict[str, str], where=None, limit: Optional[int] = None, starting_in=None, descriptions=None, stored_values: Optional[Callable] = None) -> dict
The rows of a dataset of periods, most recent first: one period per row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
str
|
|
required |
key_col
|
str
|
the column that names each row (the item). |
required |
start_col, end_col
|
the start and end of each row's period (date/time columns). |
required | |
id_map
|
Dict[str, str]
|
|
required |
where
|
conditions, as for :func: |
None
|
|
limit
|
Optional[int]
|
at most this many rows (default |
None
|
starting_in
|
|
None
|
Returns {"periods": [{"label", "start", "end", "ids"}], "n_total", "n_left_out",
"where", "notes"}; n_total counts every row the conditions keep.
tag_condition_sql
¶
tag_condition_sql(source: str, layout: dict, tag: str, periods, agg: str, op: str, value, *, id_types=None) -> str
The periods whose agg of tag over their own window satisfies op value: SELECT
period_, <agg> AS a ... GROUP BY period_ HAVING ..., one literal-bounded branch per period
(:func:tdfs4ds.plotting.aligned_source_sql). Pure.
filter_periods_by_tag
¶
filter_periods_by_tag(table: str, periods: list, tag: str, agg: str, op: str, value, *, id_types=None)
(kept periods, {label: aggregate}): the periods whose agg (MAX / MIN / AVG) of tag
over their own window satisfies the condition. One statement.
auto_bucket_seconds
¶
The smallest round bucket (1 s, 5 s, ..., 1 day, 1 week) keeping span_seconds at or
below target buckets (default tdfs4ds.PLOT_XY_POINTS_PER_SERIES). Pure.
parse_bucket
¶
Seconds of a bucket given as a number of seconds or as text ("30 s", "5 min", "1 h", "1 day"). Pure.
xy_bucket_sql
¶
Two tags of inner (rows tag_, t_off in seconds, v) averaged per (group_cols,
bucket of bucket_seconds): xv / yv, buckets holding both tags only. Pure.
historian_xy_sql
¶
historian_xy_sql(source: str, layout: dict, x_tag: str, y_tag: str, window, bucket_seconds: int, id_values=None) -> str
The rows of :func:plot_historian_xy: both tags averaged per (ids, bucket) inside window
(literal bounds; tags and ids compared on the bare columns). Pure.
default_window
¶
(now - days, now) as text, now the database's (default PLOT_HISTORIAN_DEFAULT_DAYS);
None when the setting is 0 or the time is not readable.
_closed_window
¶
A window with both ends, an open end closed at now / the default length.
_stored_tags
¶
The stored spelling of wanted tags (case-insensitive), read inside window only.
historian_xy_panels
¶
historian_xy_panels(table: str, x_tag: str, y_tag: str, *, id_values=None, xlim=None, bucket=None, title: Optional[str] = None, max_series: Optional[int] = None, exact_tags: bool = False)
The panel :func:plot_historian_xy draws, and what it reads.
plot_historian_xy
¶
plot_historian_xy(table: str, x_tag: str, y_tag: str, *, id_values=None, xlim=None, bucket=None, title: Optional[str] = None, max_series: Optional[int] = None, exact_tags: bool = False, **kwargs) -> dict
Tag y_tag against tag x_tag of a historian table, drawn in the database (scatter).
Both tags are averaged per (ids, time bucket) inside the window; a point is a bucket where both have a value, one series per id. Rows are read between literal bounds (the window), the tags and ids compared on the bare columns, so a PTI or a time-partitioned historian reads a time range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
str
|
the historian (its documented layout gives the columns). |
required |
x_tag, y_tag
|
the two tags (matched case-insensitively inside the window; |
required | |
id_values
|
keep these ids. |
None
|
|
xlim
|
the time window |
None
|
|
bucket
|
seconds or text ("5 min"); default: the smallest round bucket keeping each series near
|
None
|
historian_by_periods_panels
¶
historian_by_periods_panels(table: str, tags, periods: list, *, xy: bool = False, clock_time: bool = False, bucket=None, title: Optional[str] = None, noun: Optional[str] = None, exact_tags: bool = False)
The panels :func:plot_historian_by_periods draws, and what they read.
plot_historian_by_periods
¶
plot_historian_by_periods(table: str, tags, periods: list, *, xy: bool = False, clock_time: bool = False, bucket=None, title: Optional[str] = None, noun: Optional[str] = None, exact_tags: bool = False, layout=None, **kwargs) -> dict
One series per period: each period read on its own ids, between its own start and end.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
str
|
the historian table. |
required |
tags
|
the tag(s) drawn over time (one panel per tag), or |
required | |
periods
|
list
|
|
required |
xy
|
bool
|
a scatter of the two tags, averaged per bucket of each period (bucket, default automatic). |
False
|
clock_time
|
bool
|
x = the timestamp; default x = the time since the period's start (minutes, hours or days, from the longest period), so periods far apart overlay. |
False
|
noun
|
Optional[str]
|
the business word for one period in titles ("batch", "run"); default "period". |
None
|