Writing Performant Formulas

作者 gopigment6fec49f4ce9d無授權條款22 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 天前更新

Execution skill. Use when reviewing or finalizing Pigment formulas before delivery. Provides the mandatory pre-delivery checklist, sparsity preservation rules, scope-first patterns, and anti-patterns to avoid.

僅含說明Data & Analytics
AI 產生的概覽

交付前撰寫稀疏、高效能 Pigment 公式的檢查清單與規則。

功能
此技能為 Pigment 公式提供交付前審查流程,核心是一份 14 項檢查清單,涵蓋識別碼、維度對齊、稀疏性、存在性檢查、作用域、聚合順序、日期範圍、分配與存取權限。它說明 Pigment 的稀疏多維引擎只儲存已定義的儲存格,並提供規則,例如將 BLANK 視為缺失而非零或假、優先使用 ISDEFINED 而非 ISBLANK、依先限定作用域再聚合的結構撰寫公式,以及用 PRORATA 處理日期範圍。它還包含一張反模式表,將常見的稠密或冗長寫法對應到更利於稀疏的改寫方式。其產出是指導與改寫後的公式模式,而非產生的檔案。
適用情境
在交付前審查或定稿 Pigment 公式時使用,尤其是公式可能使稀疏模型變稠密或影響效能的情況。它也適合用來改寫已知反模式,例如用 ISBLANK 做存在性檢查、用 ADD 做分配,或對日期範圍加 IF 判斷。
執行需求
無需指令碼或工具,僅為說明性內容。它假定使用者熟悉 Pigment 公式語法,並引用相關技能以處理以分析器為基礎的疑難排解、迭代計算與公式函式例外情況。

Writing Performant Pigment Formulas

Apply this skill to every formula before delivery. Pigment is a sparse multidimensional engine: only defined cells are stored. Performance depends on keeping formulas sparse and scoped.

Simple same-dimension arithmetic (e.g. 'A' + 'B') needs no special performance wrapping. Always review the checklist; deep rewrite when any item fails. For profiler-based troubleshooting after delivery, see skill:diagnosing-performance-issues.

Pre-Delivery Checklist

Before delivering any formula, verify each item. Rewrite until all pass.

  1. Identifiers: Correctly quoted — single quotes for names ('Revenue'), double quotes for items and text literals.
  2. Dimension alignment: No unintended ADD or dimension mismatch.
  3. Sparsity: No unnecessary 0, FALSE, or TRUE where BLANK suffices.
  4. Existence checks: Prefer ISDEFINED / IFDEFINED / IFBLANK over ISBLANK / ISNOTBLANK (see skill:using-formula-functions for rare valid exceptions).
  5. Scope-first: FILTER, EXCLUDE, or IFDEFINED appear before calculations, not after.
  6. Aggregations last: REMOVE, BY, and other aggregations come after the core calculation.
  7. Prior periods: Use SELECT with offset — not PREVIOUS unless true iteration is required (see skill:iterating-with-previous-and-cycles).
  8. Allocation: Use BY with a mapping when one exists — not ADD.
  9. Date ranges: Use PRORATA — not IF(Date >= Start AND Date <= End, ...).
  10. BY guards: No IF / ISBLANK wrappers on BY when the source is dimension-typed.
  11. Negation: Prefer EXCLUDE: condition over FILTER: NOT(condition).
  12. Access rights: Wrap in IFDEFINED('Users roles', ...). Optionally add IFDEFINED(User, ...) as an additional performance trim.
  13. Conditional output: Use IF(condition, value) (sparse) — not IF(condition, value, 0) or IF(condition, TRUE, FALSE).
  14. Subsetting: Use FILTER: CurrentValue — not IF(expr, expr, BLANK).

Treat BLANK as Absence, Not Zero or False

StateStored?Meaning
BLANK / undefinedNoCell does not exist
0YesExplicit numeric zero
FALSE / TRUEYesExplicit boolean

Example: 1000 Products x 12 Months = 12,000 possible cells. If only 500 have values, sparse metric stores 500 cells (~4%). Densifying to 12,000 multiplies storage and computation.

Rule: Represent "no value" with BLANK. Never substitute 0 for empty numbers or FALSE for empty booleans unless downstream logic explicitly requires stored values.

Meaningful zero exception: Explicit 0 IS correct when zero is a business value (zero variance, zero balance, zero growth rate, inactive line item contributing 0 to a total). In these cases BLANK would incorrectly omit the line from aggregations.

Prefer ISDEFINED Over ISBLANK

ISBLANK(A) returns TRUE or FALSE for every cell (dense). ISDEFINED(A) returns TRUE only where a value exists, BLANK elsewhere (sparse). Reserve ISBLANK / ISNOTBLANK only when every cell must hold an explicit boolean — see skill:using-formula-functions for the rare-valid-exception allow-list.

pigment
// WRONG — densifiesIF(ISBLANK('Revenue'), 'Default', 'Revenue')
// CORRECT — sparseIFBLANK('Revenue', 'Default')IFDEFINED('Revenue', 'Revenue')

Structure Formulas Scope-First, Aggregations Last

Put narrowing modifiers and guards before calculations; aggregations after.

pigment
// WRONG — computes on all cells, then filters('Revenue' * 'Rate')[FILTER: 'Region' = SET_Selected_Region]
// CORRECT — scope first, then calculate, then aggregate'Revenue'  [FILTER: 'Region' = SET_Selected_Region]  * 'Rate'  [REMOVE: Product]

Pattern: Source [scope modifiers] → calculation → [REMOVE / BY aggregation].

Model Date Ranges with PRORATA

PRORATA(TimeDimension, StartDate, EndDate) returns the fraction of each period within [StartDate, EndDate). Start date is included; end date is excluded; add 1 for inclusive end.

pigment
// WRONG — verbose, error-prone, poor sparsityIF('Date' >= 'Start Date' AND 'Date' <= 'End Date', 1, BLANK)
// CORRECT — sparse presence factorPRORATA(Month, 'Start Date', 'End Date' + 1)

Derive presence booleans with ISDEFINED(PRORATA(...)), not ISBLANK(PRORATA(...)).

Prior Period Lookups

Use SELECT with offset for simple lags — not PREVIOUS (iterative, expensive).

PREVIOUS(Month) is correct only for true iterative calculations within a single metric (e.g. cumulative balance, cash roll-forward, inventory carry-forward). For multi-metric iteration (opening/closing inventory across metrics), use PREVIOUSOF(...) with a cycle. See skill:iterating-with-previous-and-cycles for patterns.

Allocation: BY Over ADD

BY follows a mapping (sparse); ADD creates all combinations (dense).

  • Use BY CONSTANT with a mapping for value replication instead of ADD CONSTANT (dense).
  • Do not wrap BY with IF(ISBLANK(...)) guards on dimension-typed metrics.
  • See anti-pattern table for ADD+FILTER and round-trip patterns.

Access Rights

IFDEFINED('Users roles', ...) wrapping is mandatory for access rights formulas. IFDEFINED(User, ...) is an optional additional trim — not a substitute for IFDEFINED('Users roles', ...).

pigment
// Mandatory wrappingIFDEFINED('Users roles', 'Can Edit'[BY: User])
// Optional additional trim layered on topIFDEFINED(User, IFDEFINED('Users roles', 'Can Edit'[BY: User]))

Use BLANK (not FALSE) for denied access to preserve sparsity.

Conditional Creation and Subsetting

Use IF(condition, value) to create values sparsely — [ADD: X][FILTER: condition] densifies first, then subsets.

  • Use FILTER only on already-computed values; prefer [FILTER: CurrentValue] over IF(expr, expr, BLANK).
  • Use EXCLUDE instead of FILTER: NOT(...).
  • When the goal is to pick one dimension item and drop the dimension, use SELECT (aggregates it away) rather than FILTER (keeps dimension in output).
  • Division by zero: Pigment handles it natively (returns BLANK); do not guard with IF(x <> 0, a / x).

Fix These Anti-Patterns Before Delivery

Scan every formula for these patterns. Each row is a rewrite trigger.

Anti-PatternWhy BadFix
ISBLANK/ISNOTBLANK for existence checksDensifies (TRUE/FALSE stored everywhere)ISDEFINED/IFDEFINED/IFBLANK; e.g. IFBLANK(A, B) not IF(ISBLANK(A), B, A)
ISBLANK/ISNOTBLANK in AND/OR chainsDensifies entire expression via blank-presenceEXCLUDE to remove blank rows, or nested IFDEFINED guards
0/FALSE for empty numeric/booleanStores explicit value, destroys sparsityBLANK (absence = not stored)
Calculations before scopingComputes irrelevant cellsFILTER / EXCLUDE / IFDEFINED first
PREVIOUS for simple lag; SELECT for iterative calcLag: iterative overhead; Iterative: circular refLag: [SELECT: Month - 1]; same-metric: PREVIOUS(Month); multi-metric: PREVIOUSOF(...) + cycle — skill:iterating-with-previous-and-cycles
ADD/ADD CONSTANT/ADD+FILTER when mapping or IF fitsDense cross-product or dense replicationBY with mapping; BY CONSTANT for replication; IF(condition, value) for conditional rows
IF/ISBLANK guard on BY with dim-typed metricRedundant, densifiesRemove guard
IF(Date >= Start AND Date <= End, 1, BLANK)Verbose, error-pronePRORATA(TimeDim, Start, End + 1)
ISBLANK(PRORATA(...)) for presenceDensifiesISDEFINED(PRORATA(...))
FILTER: NOT(condition)Less sparse-friendlyEXCLUDE: condition
IF(cond, val, 0) or IF(cond, TRUE, FALSE)DensifiesIF(cond, val) or IFBLANK
IF(expr, expr, BLANK) for subsettingRedundant branching[FILTER: CurrentValue]
FILTER to aggregate away a dimensionKeeps dimension in outputSELECT to aggregate; FILTER to keep dimension
IF(x<>0, a/x) for safe divisionUnnecessary guardJust divide — Pigment returns BLANK for division by zero
Access rights without IFDEFINED('Users roles', ...)Densifies across usersIFDEFINED('Users roles', ...) mandatory; IFDEFINED(User, ...) is a trim, not a substitute
[ADD: X][REMOVE: X] or [REMOVE: X][ADD: Y] round-tripsUnnecessary expand/collapseBY with a mapping
Chained [BY:][BY:] on Transaction ListsSilently drops list properties between stepsSingle BY with comma-separated mappings
[REMOVE: Version] without verificationCollapses scenario meaningVerify collapse is intentional
CUMULATE/MOVINGSUM/FIND/SUBSTITUTE on large listsExpensive per-cellSubset with FILTER first
Multiple PREVIOUS(...) in one formulaMultiplies iterative passesSingle PREVIOUS call
IFBLANK(X, PREVIOUS(Dim)) or IFBLANK(X, PREVIOUSOF(...))Verbose, triggers iterationFILLFORWARD
ACCESSRIGHTS(x, FALSE) for denied accessDensifies with explicit FALSEACCESSRIGHTS(x, BLANK)
2-arg IF(condition, expr) on 6+ dim metricExpands scope across all intersectionsexpr[FILTER: condition]
Hard-coded year literals or DATE(YYYY, ...)Breaks across fiscal yearsDate-typed or Dimension-typed input metrics

Remember: BLANK = undefined = not stored. FALSE ≠ BLANK (stored, densifies). 0 ≠ BLANK (stored). Always prefer absence over explicit empty values unless business logic demands a stored zero or boolean.

Related Skills

  • skill:diagnosing-performance-issues — profiler-based troubleshooting of delivered formulas
  • skill:iterating-with-previous-and-cycles — iterative calculation optimization
  • skill:using-formula-functions — ISBLANK rare-valid-exception allow-list

來源與署名

來源:gopigment/ai-plugins位於skills/writing-performant-formulas提交6fec49f

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架