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 从公开仓库中收录这些内容。

举报或申请下架