コンテンツにスキップ

vizspec

Since v8.0.75

vizspecモジュールは、ADVNドキュメントの作成、検証、解析、出力形式の変換を行うJSH APIです。 ADVNはAnalysis Data Visualization Notationの略で、分析結果の可視化用の、レンダラーに依存しないドキュメント形式です。

ADVNを使うと、データの意味とレンダラー固有の出力を分離できます。

ADVNとvizspec

  • ADVNは、意味を表すセマンティックレイヤーです。
  • ADVNはドキュメント形式であり、分析結果の意味を表現します。
  • vizspecモジュールは、ADVNドキュメントを作成・変換するJSH APIです。
  • vizは、ADVNドキュメントを検証・プレビュー・エクスポートするコマンドです。

基本例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const vizspec = require('vizspec');

const spec = new vizspec.Builder()
    .setDomain({
        kind: 'time',
        timeformat: vizspec.Timeformat.ns,
    })
    .setXAxis({ id: 'time', type: 'time', label: 'Time' })
    .addYAxis({ id: 'value', type: 'linear', label: 'Value' })
    .addTimeBucketValueSeries({
        id: 'series-1',
        axis: 'value',
        data: [
            ['1712102400000000000', 10],
            ['1712102460000000000', 12],
        ],
    })
    .build();

定数

このモジュールは、以下の定数グループを提供します。

  • RepresentationKind
  • AnnotationKind
  • Timeformat

アプリケーションのコードでADVNの値を明示的に指定する場合、これらの定数を使うと誤記を減らせます。

RepresentationKind

メンバー説明
RepresentationKind.rawPointraw-point[x, y]形式の生のポイントサンプルです。
RepresentationKind.timeBucketValuetime-bucket-value単一の数値を持つ時間バケットの集計表現です。
RepresentationKind.timeBucketBandtime-bucket-bandmin/max/avgの帯域値を持つ時間バケットの集計表現です。
RepresentationKind.distributionHistogramdistribution-histogramヒストグラム分布のバケット表現です。
RepresentationKind.distributionBoxplotdistribution-boxplot箱ひげ図の分布グループ表現です。
RepresentationKind.eventPointevent-point1つの時刻・値の位置で発生した瞬間的なイベントの表現です。
RepresentationKind.eventRangeevent-rangefrom/toの時間範囲を持つ継続イベントの表現です。

AnnotationKind

メンバー説明
AnnotationKind.pointpoint1つの位置を指すポイント注釈です。
AnnotationKind.linelineしきい値または参照線の注釈です。
AnnotationKind.rangerange範囲を強調する範囲注釈です。

Timeformat

メンバー説明
Timeformat.rfc3339rfc3339RFC3339文字列による時刻表現です。
Timeformat.ssエポック秒です。
Timeformat.msmsエポックミリ秒です。
Timeformat.ususエポックマイクロ秒です。
Timeformat.nsnsエポックナノ秒です。

parse()

ADVNのJSON文字列を解析し、正規化したspecオブジェクトを返します。

構文
parse(text)
パラメーター
名前説明
textstring解析するADVN JSON文字列です。
使用例
1
2
3
const vizspec = require('vizspec');
const spec = vizspec.parse('{"version":1,"series":[]}');
console.println(spec.version);

stringify()

specオブジェクトをADVNのJSON文字列にシリアライズします。

構文
stringify(spec)
パラメーター
名前説明
specobjectシリアライズするADVN specオブジェクトです。
使用例
1
2
3
const vizspec = require('vizspec');
const text = vizspec.stringify(vizspec.createSpec({ version: 1 }));
console.println(typeof text);

validate()

specオブジェクトを検証します。構造やフィールドの組み合わせが不正な場合は、例外を発生させます。

構文
validate(spec)
パラメーター
名前説明
specobject検証するADVN specオブジェクトです。
使用例
1
2
3
const vizspec = require('vizspec');
const ok = vizspec.validate(vizspec.createSpec({ version: 1 }));
console.println(ok);

normalize()

部分的に指定したspecオブジェクトを正規化し、基本構造のフィールドを補完します。

構文
normalize(spec)
パラメーター
名前説明
specobject正規化する部分的なADVN specオブジェクトです。
使用例
1
2
3
const vizspec = require('vizspec');
const spec = vizspec.normalize({});
console.println(spec.version);

createSpec()

初期化オブジェクトからspecオブジェクトを作成し、正規化・検証します。

構文
createSpec(init)
パラメーター
名前説明
initobjectADVN specの初期値オブジェクトです。
使用例
1
2
3
4
5
6
const vizspec = require('vizspec');
const spec = vizspec.createSpec({
    domain: { kind: 'time', timeformat: vizspec.Timeformat.ns },
    series: [],
});
console.println(spec.domain.kind);

listSeries()

spec.seriesの正規化された概要一覧を返します。

構文
listSeries(spec)
パラメーター
名前説明
specobject確認するADVN specオブジェクトです。
返されるフィールド
フィールド説明
indexintegerspec.series内の、0から始まる系列インデックスです。
idstring系列IDです。
namestring指定されている場合の系列名です。
titlestring表示タイトルです。nameがあればname、なければidを使用します。
kindstring表現の種類です。
tuiLinesCompatiblebooleantoTUILines()で描画できる系列かどうかを表します。
使用例
1
2
3
const listed = vizspec.listSeries(spec);
console.println(listed[0].id);
console.println(listed[0].tuiLinesCompatible);

系列ヘルパー

系列ヘルパー関数は、正しい表現の種類と既定のフィールド構成を持つ系列オブジェクトを作成します。

使用できるヘルパー:

  • rawPointSeries(init)
  • timeBucketValueSeries(init)
  • timeBucketBandSeries(init)
  • distributionHistogramSeries(init)
  • distributionBoxplotSeries(init)
  • eventPointSeries(init)
  • eventRangeSeries(init)
構文
timeBucketValueSeries(init)
eventRangeSeries(init)
共通の初期化フィールド
名前説明
idstring系列の識別子です。
namestringアダプターで使用する表示名です。
axisstring数値レンダラーで使用するY軸IDです。
representationobjectフィールドまたは表現メタデータの上書きに使用します。
dataarray系列ペイロードの行配列です。
styleobjectcolor、opacityなど、レンダラーへのヒントとなるスタイル値です。
qualityobjectcoverage、rowCountなどの品質メタデータです。
sourceobject系列の出所を示すメタデータです。
extraobject箱ひげ図の外れ値など、表現固有の追加データです。
使用例
1
2
3
4
5
6
7
const vizspec = require('vizspec');
const series = vizspec.timeBucketValueSeries({
    id: 'cpu',
    axis: 'value',
    data: [['1712102400000000000', 10]],
});
console.println(series.representation.kind);

注釈ヘルパー

注釈ヘルパー関数は、正しい注釈の種類を持つトップレベルの注釈オブジェクトを作成します。

使用できるヘルパー:

  • pointAnnotation(init)
  • lineAnnotation(init)
  • rangeAnnotation(init)
構文
lineAnnotation(init)
rangeAnnotation(init)
共通の初期化フィールド
名前説明
axisstring対象の軸IDです。
labelstringユーザーに表示する注釈ラベルです。
valueany線またはポイントの注釈で使用する値です。
atanyポイント注釈の位置です。
fromany範囲の開始値です。
toany範囲の終了値です。
styleobject省略可能な、レンダラーへのヒントとなるスタイル値です。
使用例
1
2
3
const vizspec = require('vizspec');
const annotation = vizspec.lineAnnotation({ axis: 'value', value: 80, label: 'warning' });
console.println(annotation.kind);

Builder

メソッドチェーンでADVNドキュメントを作成するには、ビルダーを使用します。

構文
new Builder([init])
主なメソッド
メソッド説明
setDomain(definition)spec.domainを設定します。
setXAxis(definition)spec.axes.xを設定します。
addYAxis(definition)Y軸定義を1つ追加します。
addRawPointSeries(definition)raw-point系列を追加します。
addTimeBucketValueSeries(definition)time-bucket-value系列を追加します。
addTimeBucketBandSeries(definition)time-bucket-band系列を追加します。
addDistributionHistogramSeries(definition)ヒストグラム系列を追加します。
addDistributionBoxplotSeries(definition)箱ひげ図系列を追加します。
addEventPointSeries(definition)event-point系列を追加します。
addEventRangeSeries(definition)event-range系列を追加します。
addAnnotation(definition)注釈オブジェクトを追加します。
addLineAnnotation(definition)線の注釈を追加します。
addRangeAnnotation(definition)範囲の注釈を追加します。
setView(definition)spec.viewを設定します。
setMeta(definition)spec.metaを設定します。
build()正規化したspecを返します。
stringify()ビルド結果を文字列にシリアライズします。
listSeries()正規化した系列の概要一覧を返します。
toEChartsOption(options)ビルド結果をEChartsのオプションに変換します。
toTUILines(options)ビルド結果を、ターミナル用のTUIグラフの行配列に変換します。
toTUIBlocks(options)ビルド結果をTUIブロックの配列に変換します。
toSVG(options)ビルド結果をSVG文字列に変換します。
toPNG([svgOptions[, pngOptions]])ビルド結果をPNGバイナリデータに変換します。
使用例
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const vizspec = require('vizspec');

const spec = new vizspec.Builder()
    .setDomain({ kind: 'time', timeformat: vizspec.Timeformat.ns })
    .setXAxis({ id: 'time', type: 'time', label: 'Time' })
    .addYAxis({ id: 'value', type: 'linear', label: 'Temperature' })
    .addTimeBucketBandSeries({
        id: 'sensor-1',
        axis: 'value',
        data: [
            ['1712102400000000000', 18, 24, 21],
            ['1712102460000000000', 17, 23, 20],
        ],
    })
    .build();

出力アダプター

toEChartsOption()

specをEChartsのオプションオブジェクトに変換します。

構文
toEChartsOption(spec[, options])
パラメーター
名前説明
specobject描画するADVN specオブジェクトです。
optionsobject省略可能な出力側の時刻設定です。
オプションフィールド
オプション既定値説明
timeformatstringrfc3339ECharts用に時刻値をエンコードする際の、出力時刻の表現です。
tzstringローカルタイムゾーンRFC3339の時刻値を出力する際に適用するタイムゾーンです。
使用例
1
2
3
4
5
const option = vizspec.toEChartsOption(spec, {
    timeformat: vizspec.Timeformat.rfc3339,
    tz: 'Asia/Seoul',
});
console.println(JSON.stringify(option));

toTUILines()

スパークライン対応の最初の系列を、ターミナル用のスパークライン行配列に変換します。

構文
toTUILines(spec[, options])
パラメーター
名前説明
specobject描画するADVN specオブジェクトです。
optionsobject省略可能なスパークラインの描画設定です。
オプションフィールド
オプション既定値説明
heightinteger3raw-pointとtime-bucket-valueの行出力に使用するグラフの高さです。
widthinteger40値をサンプリングし、スパークライン本体を描画する際の幅です。
seriesIdstring最初の対応系列series[].idで、描画する系列を選択します。
timeformatstringrfc3339スパークラインのX軸ラベルに使用する出力時刻形式です。
tzstringローカルタイムゾーンスパークラインのX軸ラベルに適用するタイムゾーンです。

注意:

  • seriesIdを省略すると、toTUILines()はスパークライン対応の最初の系列を返します。
  • seriesIdを指定すると、series[].idが一致する系列を描画します。
  • 選択できる系列IDを確認するには、listSeries()を使用します。
  • 指定したseriesIdが存在しない場合や、スパークライン非対応の系列を指す場合は、エラーが発生します。
  • 戻り値は、複数行のTUIグラフを構成するターミナル用の行配列です。
  • toTUIBlocks()と異なり、軸ラベルを含む展開された複数行グラフ形式を維持します。
  • heightは、raw-pointtime-bucket-valueの出力だけに適用します。time-bucket-bandは、既存のmax/avg/min形式を維持します。
  • 現在のtoTUILines()は、rowscompactオプションを受け取っても使用しません。
使用例
1
2
const lines = vizspec.toTUILines(spec, { width: 32, height: 5, seriesId: 'series-1' });
console.println(lines.join('\n'));

CLI 例:

viz lines --height 5 --series series-1 sample.json
ソースコード全体:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const vizspec = require('vizspec');
const { Client } = require('machcli');

const dbConf = {
    host: '127.0.0.1', port: 5656,
    user: 'sys', password: 'manager',
};

var db, conn, rows;
var data = [];
try {
    db = new Client(dbConf);
    conn = db.connect();
    rows = conn.query(`SELECT TIME, VALUE FROM EXAMPLE
        WHERE NAME = ? AND TIME > now - 2h`, 'machbase:ps:cpu_percent');
    for (const row of rows) {
        data.push([row.TIME, row.VALUE]);
    }
} catch( e ) {
    console.println("ERROR", e.message);
} finally {
    rows && rows.close();
    conn && conn.close();
    db && db.close();
}

const spec = new vizspec.Builder()
    .setDomain({ kind: 'time', timeformat: vizspec.Timeformat.rfc3339 })
    .setXAxis({ id: 'time', type: 'time', label: 'Time' })
    .addYAxis({ id: 'value', type: 'linear', label: 'Value' })
    .addTimeBucketValueSeries({ id: 'series-1', axis: 'value', data: data })
    .build();

console.println(vizspec.toTUILines(spec, { width: 80 }).join('\n'));

出力例:

toTUIBlocks()

specを、ターミナルで確認するためのTUIブロックオブジェクト配列に変換します。

構文
toTUIBlocks(spec[, options])
パラメーター
名前説明
specobject描画するADVN specオブジェクトです。
optionsobject省略可能なTUI描画設定です。
オプションフィールド
オプション既定値説明
widthinteger40スパークライン、ヒストグラム、タイムラインの描画幅です。
rowsinteger8table、histogram、eventブロックに表示する詳細行の最大数です。
compactbooleanfalse系列の概要と生データの表ブロックを非表示にします。
timeformatstringrfc3339出力時刻の形式です。rfc3339smsusnsを使用できます。
tzstringローカルタイムゾーン出力時刻値に適用するタイムゾーンです。
戻り値

戻り値はブロックオブジェクトの配列です。各ブロックは、以下の共通フィールドを持つ場合があります。

フィールド説明
typestringブロックの種類です。例:summaryseries-summarysparklinebandlinebarsbox-summaryevent-listtimelinetableannotations
titlestringブロックのタイトルです。
statsarray概要系ブロックで使用する{ label, value }オブジェクトの配列です。
linesarraysparkline、timeline、histogramなどの行形式のブロックで使用する文字列配列です。現在のsparklineブロックは、コンパクトなスパークラインを1行返します。
columnsarraytableブロックの列名の配列です。
rowsarraytableブロックの行配列です。各行は、列順に並ぶ値の配列です。
metaobjectブロック固有の付加情報です。例:representationaxistotalRowstruncated

実際に設定されるフィールドはtypeによって異なります。たとえば、sparklineブロックは主にlinesを使用し、tableブロックはcolumnsrowsmetaを使用します。

注意:

  • toTUIBlocks()sparklineブロックは、従来のコンパクトなスパークライン表現を返します。
  • 軸ラベルと複数のグラフ行を含む展開形式が必要な場合は、toTUILines()を使用します。
使用例
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const blocks = vizspec.toTUIBlocks(spec, {
    width: 80,
    rows: 5,
    timeformat: vizspec.Timeformat.rfc3339,
    tz: 'Asia/Seoul',
});
console.println(blocks[0].type);           // summary
console.println(blocks[0].stats[0].label); // series
console.println(blocks[2].type);           // sparkline
console.println(blocks[2].lines[0]);       // ▁▃▅▇█▆▄▂

toSVG()

specをSVG文字列に変換します。

構文
toSVG(spec[, options])
パラメーター
名前説明
specobject描画するADVN specオブジェクトです。
optionsobject省略可能なSVG描画設定です。
オプションフィールド
オプション既定値説明
widthinteger960SVGキャンバスの幅(ピクセル)です。
heightinteger420SVGキャンバスの高さ(ピクセル)です。
paddinginteger48グラフの外側の余白(ピクセル)です。
backgroundstringwhiteSVGの背景色です。
fontFamilystringsans-serif既定のフォントファミリーです。
fontSizeinteger12既定のフォントサイズ(ピクセル)です。
showLegendbooleantrue凡例を描画するかどうかを制御します。
titlestring省略可能なグラフのタイトルです。
timeformatstringrfc3339軸ラベルと出力時刻値に使用する時刻形式です。
tzstringローカルタイムゾーンRFC3339時刻の出力に適用するタイムゾーンです。
使用例
1
2
3
4
5
6
7
const svg = vizspec.toSVG(spec, {
    title: 'Sensor Overview',
    width: 960,
    height: 420,
    timeformat: vizspec.Timeformat.rfc3339,
    tz: 'Asia/Seoul',
});

toPNG()

specをPNGバイナリデータに変換します。戻り値はArrayBufferで、必要に応じてnew Uint8Array(png)で読み取れます。

構文
toPNG(spec[, options])
パラメーター
名前説明
specobject描画するADVN specオブジェクトです。
optionsobject省略可能な、グラフレイアウト・テキスト・出力時刻・ラスタライズの統合設定です。
オプションフィールド

レイアウトとテキストのフィールド:

オプション既定値説明
widthinteger960ラスター拡大前の出力幅(ピクセル)です。
heightinteger420ラスター拡大前の出力高さ(ピクセル)です。
paddinginteger48グラフの外側の余白(ピクセル)です。
backgroundstringwhiteSVGレイアウトとPNGラスター出力に共通で適用する背景色です。
fontFamilystringsans-serif既定のフォントファミリーです。
fontSizeinteger12既定のフォントサイズ(ピクセル)です。
showLegendbooleantrue凡例を描画するかどうかを制御します。
titlestring省略可能なグラフのタイトルです。
timeformatstringrfc3339軸ラベルと出力時刻値に使用する時刻形式です。
tzstringローカルタイムゾーンRFC3339時刻の出力に適用するタイムゾーンです。

ラスタライズのフィールド:

オプション既定値説明
scalenumber1SVGベースのレイアウトを倍率に従って拡大し、ラスタライズします。
dpiinteger未設定scaleがない場合に使用する目標DPIです。内部でdpi / 96の倍率として適用します。
themestringmrtgPNGテーマ名です。現在はmrtgだけに対応しています。

注意:

  • scaledpiを両方指定すると、scaleが優先されます。
  • 現在のPNGレンダラーは、MRTG形式の出力を生成します。
  • JavaScript APIは、単一のoptionsオブジェクトを受け取り、内部でレイアウトとラスタライズのフィールドに分割します。
  • 後方互換性のため、従来のtoPNG(spec, svgOptions, pngOptions)の呼び出し形式にも対応しています。
使用例
1
2
3
4
5
6
7
8
9
const png = vizspec.toPNG(spec, {
    title: 'Sensor Overview',
    width: 640,
    height: 240,
    scale: 2,
    theme: 'mrtg'
});
const bytes = new Uint8Array(png);
console.println(bytes[0].toString(16));

時刻の処理

エポックタイムスタンプをsmsusns形式で使用すると、値自体がUTCに基づく絶対時刻を表すため、 入力データにタイムゾーンを明示する必要はありません。タイムゾーンは、元のタイムスタンプに付ける情報ではなく、 そのタイムスタンプを読みやすい文字列として出力する際のオプションです。

特にnsは桁数が大きく、JavaScriptのnumberで表すと精度が失われる場合があります。 たとえば、1712102400000000000などの値は、IEEE 754倍精度浮動小数点数の安全な整数範囲を超えるため、 ナノ秒のエポック時刻は、文字列で渡すことを推奨します。

Machbase Neoのタイムスタンプデータには、次の組み合わせを推奨します。

  • timeformat: vizspec.Timeformat.ns
  • JavaScriptのnumberではなく、文字列のタイムスタンプを使用

例:

const spec = vizspec.createSpec({
    domain: {
        kind: 'time',
        timeformat: vizspec.Timeformat.ns,
    },
    series: [vizspec.eventRangeSeries({
        id: 'maintenance',
        data: [['1712102400000000000', '1712102460000000000', 'maintenance']],
    })],
});

時刻の表示

データソースの時刻エンコーディングと出力時の時刻表現は、別々に扱います。

  • domain.timeformatは、ADVNドキュメント内のタイムスタンプのエンコーディングを表します。
  • アダプターオプションのtimeformattzは、そのタイムスタンプを表示する形式とタイムゾーンを表します。

アダプターオプションを省略すると、vizspecアダプターは既定でrfc3339とローカルタイムゾーンを使用します。

例:

const svg = vizspec.toSVG(spec, {
    title: 'CPU Usage',
    width: 960,
    height: 420,
    timeformat: vizspec.Timeformat.rfc3339,
    tz: 'Asia/Seoul',
});

同じ規則は、toTUIBlocks()toEChartsOption()にも適用されます。

vizコマンドの使用

作成した仕様を検証するには、次のように実行します。

/work > viz validate cpu-usage.json
VALID version=1 series=1 annotations=1

ターミナルで確認するには、次のように実行します。

/work > viz view cpu-usage.json

SVGに出力するには、次のように実行します。

/work > viz export --title "CPU Usage" --output cpu-usage.svg cpu-usage.json

出力時刻形式とタイムゾーンを明示するには、次のように実行します。

/work > viz view --timeformat rfc3339 --tz Asia/Seoul cpu-usage.json
最終更新日