Skip to content

lib-rule 库参考 ​

原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793390485/FIN+5.3.1+lib-rule 中文整理基于 FIN 5.3.1

导读: 规则引擎用于计算火花、关键绩效指标和当前值

以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。


目录(导读) ​

  • lib
  • meta
  • docs
  • tags
  • apps
  • funcs
  • views
  • def
  • supertypes
  • enum
  • Overview
  • Rules
  • Roster
  • Spark Rules
    • Sparks
    • Cost
  • KPI Rules
    • KPI Types
    • KPIs
  • Historical Rules
    • Start Date
    • Hot Period
    • Folio Cache
    • Orphans
  • Cur Rules
  • Comps
  • Comp Examples
  • Tuning
  • Clustering
  • Rule Ready Funcs
  • ruleDebug(mode, arg1: null, arg2: null)
  • ruleDelete(targets, span: null, rules: null, opts: null)
  • ruleErrs(rules: null)
  • ruleKpis(targets, span, rules: null)
  • ruleKpisDigest(targets, span, rules: null)
  • ruleOrphans(targets, span)
  • ruleRecompute(targets, span, rules, opts: null)
  • ruleReobserve(targets: null, rules: null)
  • ruleRosterRefresh()
  • ruleSparkExplain(spark)
  • ruleSparkHis(sparks)
  • ruleSparks(targets, span, rules: null)
  • ruleSparksCount(targets, span, rules: null)
  • ruleSparksDigest(targets, since, rules: null)
  • ruleTargetsUnder(parents)
  • ruleTest(rule, target: null, date: null, tuning: null)
  • ruleToTargets(rule)
  • ruleTuning(target, rule)
  • ruleTunings()
  • rulesToTargets(rules)
  • targetToRules(target)
  • targetsToRules(targets)

概述(中译) ​

规则引擎用于计算火花、关键绩效指标和当前值


API 正文(英文) ​

docs ​

Overview • Rules • Roster • Spark Rules • KPI Rules • Historical Rules • Cur Rules • Comps • Comp Examples • Tuning • Clustering • Rule Ready Funcs


tags ​

bindStatusCurrent status of a component cell binding
durTotal duration of the spark periods measured in hours
kpiMarker tag to indicate a KPI dict
obsRuleFilterFilter string for rule records to observe
obsSparksSubscribe to rule engine sparks - see docs
obsTargetFilterFilter string for target records to observe
ruleMarker tag for a rule record
ruleCostSpecifies formula used to apply a cost tag to sparks
ruleFreqExecution frequency of a curRule
ruleFuncSpecifies the function to run for a rule
ruleRefReference to rule which contains this entity
ruleStatusCurrent status of a rule
ruleTuningMarker applied to a rec which defines a rule tuning configuration
ruleTuningTargetFilterFilter string to match rule target records
ruleTuningTargetRefReference to a specific rule target or target parent
sparkMarker tag to indicate a spark dict
targetRefReference to the target record of a rule result or associated record

apps ​

kpiViews used to visualize KPI rule results
ruleViews used to manage configured analytic rules
sparkViews used to visualize spark rule results

funcs ​

ruleDebugReturn a debug grid from the rule engine
ruleDeleteDelete works just like ruleRecompute() except it also deletes the sparks/KPIs from the cache
ruleErrsReturn grid of all the rule+targets which have errors
ruleKpisQuery local KPIs along three dimensions of target x dates x rules
ruleKpisDigestReturn grid of KPIs to use for a notification
ruleOrphansSearch the database for all previously cached sparks and KPIs which no longer have a valid rule record
ruleRecomputeRecompute local sparks or KPIs for the given targets/dates/rules
ruleReobserveClear today's observed flag to re-observe sparks
ruleRosterRefreshForce roster refresh
ruleSparkExplainReturn explanation information for a spark
ruleSparkHisTurn a grid of sparks as returned by ruleSparks() into a history grid of the spark periods
ruleSparksQuery local sparks along three dimensions of target x dates x rules
ruleSparksCountReturn number of sparks as queried by ruleSparks()
ruleSparksDigestReturn grid of sparks to use for a notification
ruleTargetsUnderGet a grid of all the rule targets which are contained by the given parent
ruleTestPerform test run of rule
ruleToTargetsGet all the target records the rule is registered on by the ruleOn tag
ruleTuningReturn the effective tuning Dict for the given target/rule pair
ruleTuningsRead grid of tuning records sorted from lowest to highest priority
rulesToTargetsGet all the target records the list of rules is registered on by the ruleOn tag
targetToRulesGet all the rule records which are registered on given target
targetsToRulesGet all the rule records which are registered on given list of targets

views ​

kpiChartVisualize historized KPI analytical results using charts
kpiSwivelVisualize KPI analytical results using graphical pivot tables
kpiTableVisualize KPI analytical results in tabular format
ruleClusterView all rule records configured across the cluster
ruleDebugDebug the rule engine
ruleLocalManage rules configured in the local project database
ruleSettingsSettings for the rule extension
ruleTuningManage rule tuning records in the local project database
sparkEquipVisualize spark analytical results for a single equipment
sparkSwivelVisualize spark analytical results using graphical pivot tables
sparkTableVisualize spark analytical results in tabular format


def ​

app:kpi ​

Views used to visualize KPI rule results


meta ​

defapp:kpi
disKeyui::kpi
iconkpi
isapp
liblib:rule

supertypes ​

featureFeature namespace of definitions formatted as feature:name
appUI application grouping of views


def ​

app:rule ​

Views used to manage configured analytic rules


meta ​

defapp:rule
disKeyui::rule
iconrule
isapp
liblib:rule

supertypes ​

featureFeature namespace of definitions formatted as feature:name
appUI application grouping of views


def ​

app:spark ​

Views used to visualize spark rule results


meta ​

defapp:spark
disKeyui::spark
iconspark
isapp
liblib:rule

supertypes ​

featureFeature namespace of definitions formatted as feature:name
appUI application grouping of views


def ​

bindStatus ​

Current status of a component cell binding


meta ​

defbindStatus
enumSee below
isstr
liblib:rule
transient✓

enum ​

okAll is okay
errBinding error
unboundNo binding configured

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters

lib rule ​

Overview ​

The ruleExt provides a rule engine designed to run analytics against the entities in your system such as site, equip, and points. The entities we wish to analyze are called targets and are identified with filters. Analytic computations are implemented as Axon functions.

There are three types of rules:

  • spark rules: generate sparks - historical anomalies of interest represented as a timeline
  • kpi rules: provide a historical daily rollup calculation for a key performance indicator
  • cur rules: used to create computed curVal points in real-time

We use the term historic rules to describe both spark and kpi rules because they operate on history data going back in time. Historical rules cache their computations in Folio for fast access.

Rules ​

A rule is a record in folio with the following tags:

  • rule: marker tag
  • dis: all rules should define a nice display name
  • help: rules should define documentation for end users
  • ruleOn: filter which specifies targets of rule
  • ruleFunc: Axon expression which evaluates to function to run
  • disabled: marker tag to temporarily disable the rule from running
  • color: optional tag to assign a color to visualizations; this should be one of the predefined chart colors
  • ruleCost: optional cost formula (spark rules only)

All rules must be further typed with one of the following markers:

  • sparkRule
  • kpiRule
  • curRule

Roster ​

The rule engine is continually scanning the Folio database looking for new rules and new targets. The term roster describes the full list of all rules and targets. Refreshing the roster can be expensive, so it is performed only if it detects that a persistent change has been made to Folio. It is further constrained by a refresh limit. By default the rosterRefresh limit is 1min, but can be configured via Settings|Rule. You can force a roster refresh via the ruleRosterRefresh() function.

Spark Rules ​

Spark rules are used to generate sparks for a given target record and date via a function with two parameters: (target, date). The rule function must return a Grid of history periods or null. Return null if no spark occurred on the date or if data is missing. Otherwise return a history Grid of timestamp/duration pairs. Many history functions such as hisFindPeriods() are designed to return grids in the proper format.

The rule engine will automatically manage the built-in tags described below. Additional tags may be defined in the resulting Grid's meta using the prefix "spark_". For example to add a kwh tag into your sparks:

sparkPeriods.addMeta({spark_kwh:13kWh})

Sparks ​

Sparks are represented as a dict with the following tags:

  • spark: marker tag
  • date: Date for the rule hit
  • ruleRef: Ref to the generating rule
  • targetRef: Ref to the target the rule ran against
  • periods: Base64 encoded timeline of the sparks during the date
  • dur: total hours of periods in the true condition
  • tz: timezone to use to convert date into timestamps
  • any other tags generated by the rule function

Note that sparks are not first class records in the folio database with an id tag. They are stored in Folio as a separate data structure attached to their target record which may be read with the ruleSparks() function.

Cost ​

Apply the ruleCost tag on a spark rule to automatically compute a cost tag on each spark for that rule. This tag is a Str formatted as:

{amount} per {time}

The amount should be a number with a unit of currency (remember units are always specified as suffix to scalar). The time must be one of the following:

  • "hour": spark cost is total date's duration x amount (proportional to hours in day)
  • "period": spark cost is total number of discrete periods x amount (occurances within the day)
  • "date": spark cost is amount (fixed amount per date)

If the ruleCost tag is missing or is the empty string, then cost is not computed for the rule's sparks.

For example, let's suppose we have a spark on a given date for these periods:

// two discrete periods with total duration of 4hr
9:00 1hr
12:00 3hr

// cost formula examples
"5$ per hour"    >>>  $20   // $5 x 4hr of duration
"5$ per period"  >>>  $10   // $5 x 2 discrete periods
"5$ per date"    >>>  $5    // $5 for entire date

If you need a more advanced computations for cost, you can also calculate in your function's Axon code and apply the spark_cost tag to the resulting grid meta.

KPI Rules ​

KPI rules are used to generate key performance indicators for a given target record and date via a function with two parameters: (target, date). The rule function must return Dict or null. Return null if they KPI cannot be calculated for the date (if data is missing).

All the tags in your resulting Dict will be stored in the KPI for that target and date. Plus the rule engine will automatically manage the built-in tags described below.

KPI Types ​

In order to use any of the built-in visualizations your KPI result must use one of the following tagging conventions:

  • sum: totalized value such as total energy, cost, runtime hours
  • avg: averaged value
  • delta: positive or negative difference between two variables with a zero based center-point
  • min and max: spread or range of a variable

Each of these has a specific folding function for rollups:

  • sum: fold using sum()
  • avg: fold using avg()
  • delta: fold using avg()
  • min and max: fold using min() and max()

KPIs ​

KPIs are represented as a dict with the following tags:

  • kpi: marker tag
  • date: Date for the KPI hit
  • ruleRef: Ref to the generating rule
  • targetRef: Ref to the target the rule ran against
  • any other tags returned by the rule function

Note that KPIs are not first class records in the folio database with an id tag. They are stored in Folio as a separate data structure attached to their target record which may be read with the ruleKpis() function.

Historical Rules ​

Both spark and kpi rules are historic rules - they compute against history data and cache the results into Folio. These results are organized as a "data cube" along three dimensions: targets, rules, and dates.

Start Date ​

The historic rule cache is populated based on each rule's start date. By default the start date is 90 days from today. You can change the default startDate in Settings|Rules. You can also configure a per rule start date by adding the startDate tag directly on your rule (which will trump the default start date).

Hot Period ​

There is a configurable hot period which is used to periodically recompute sparks/kpis for the most recent window of time. The hot period is our active window of time. For example over the course of today the periods of a spark will change. The hot period refresh is controlled by configuring a number of hot days and a refresh frequency. For example given 2 hot days and a refresh frequency of 3 hours, then we will recompute all rules/targets every 3 hours for today and yesterday. The hotPeriod and hotRefreshFreq are configured in Settings|Rule.

Folio Cache ​

The rule engine continually scans your folio database looking for new rules and new targets. For each target/rule combination, the rule engine computes results starting from today's date and working back in time to the configured start date. All the rules for a given target and date are processed in one batch and then stored to Folio.

Each target maintains an index which persistently stores one of the follow four states for each rule+date combination:

  • ⚫ Hit: rule function returned a non-null dict result
  • ⚪ Miss: rule function returned null result
  • ❌ Err: rule function raised an exception
  • ? Unknown: rule function has not been run yet

Separately, each target stores the hits (non-null Dicts) for all its rules on a per date basis.

You can force a recompute on any target/rule/date combination. Recompute resets the index state to unknown, but does not immediately update the associated sparks/KPIs. The old spark/KPI dicts remain cached and in-effect until the rule engine reruns the rule function for a given target/date. You can manually recompute selections in Rule|Debug or use the ruleRecompute() function. To force a recompute and delete current spark/KPI dicts use ruleDelete().

Orphans ​

Sparks and KPIs are cached on a per target basis. When you delete the target record, all of the associated spark/KPIs are automatically deleted. But the same is not true for rules. If you delete rules from your database, it is likely that you will leave orphaned data in your cache. This is because all the sparks/KPIs for a given target and date are serialized into a single blob.

When you query or visualize sparks/KPIs the orphaned data is automatically skipped. So it does not technically hurt anything. However, it is taking disk space in your database and it must be deserialized everytime a read is performed. So if you are deleting rules extensively, this situation will decrease system performance.

You can use the ruleOrphans() function to report on your orphaned sparks and KPIs:

// run narrow report on specific targets and span
readAll(ah).ruleOrphans(thisMonth)

// report on all orphaned data across database
ruleOrphans(null, null)

Once you have reviewed the report, you can pipe the result directly to the ruleDelete() function:

ruleOrphans(null, null).ruleDelete

The ruleDelete function is very expensive and can take a long time. Unless your database is very small it should be run within a task.

Cur Rules ​

Current rules or curRules are used to implement soft real-time analytics and control logic. There are two mechanisms to output data from a current rule:

  • drive curVal of a point as "computed current value"
  • drive write level of a writable point

Additionally curRules can support putting their input points into a watch. This ensures that connectors are subscribed to provide fresh up-to-date data.

Current rules use the curRule marker tag and must use a component for their ruleFunc. A unique component is used per rule+target combination. The component instance will maintain its last state between executions. However if the rule record or function component is modified, then the component is re-instantiated and its state will be lost.

The default execution frequency for current rules is 10sec. This may be tuned on a per rule basis with the ruleFreq tag.

Comps ​

Axon components can be used for a ruleFunc. Using comps for rule logic provides several advantages:

  • can declaratively setup point bindings
  • bindings are read from Folio only at roster refresh time which is more efficient then embedding read calls into your rule logic
  • allow watches to be setup on input points
  • provide more detailed debugging

Comps used by the rule engine must conform to a specific shape. The following named cells are used:

  • target: cell used to input the target record (used by spark, kpi, and cur rules)
  • date: cell used to input Date parameter (spark, kpi rules only)
  • out: cell used to output the spark grid or KPI dict (spark, kpi rules only)

Additional cells may be configured to bind inputs and outputs. The following cell meta tags are used:

  • bind: filter macro to bind to an input record
  • bindAll: filter macro to bind to an input list of records for all matches
  • bindOut: filter macro to bind curRule output
  • bindTuning: bind to a tuning parameter (see below)
  • toCurVal: marker used with bindOut to output a computed curVal
  • toWriteLevel: number between 1 and 16 used with bindOut to output to writable point
  • watch: marker tag used to subscribe input point to a watch
  • readonly: marker tag that prevents the cell from being written by another component

Both bind and bindOut are filters processed using the {{var}} macro syntax. The following variables are supported:

  • target->id: rec id of the target
  • target->foo: tag name "foo" on the target

Comp Examples ​

Here are some examples:

// KPI rule example bind to discharge temp to compute daily average
defcomp
  target: {}
  date: {}
  out: {readonly}
  dat: {bind:"discharge and air and temp and equipRef=={{target->id}}"}
  do
    avgTemp: hisRead(dat, date).foldCol("v0", avg)
    out = {avg:avgTemp}
  end
end

// current rule example
//  - in1 input point is subscribed with a watch
//  - out1 outputs curVal to 123
//  - out2 outputs write level 14 to 987
//  - bind/bindOut filters not shown
defcomp
  target: {}
  in1: {bind:"...", watch}
  out1: {bindOut:"...", toCurVal}
  out2: {bindOut:"...", toWriteLevel:14}
  do
    out1 = 123
    out2 = 987
  end
end

Tuning ​

The rule tuning framework is used to customize specific rule/target combinations. Tuning can be used to tweak the behavior of a rule for a specific project, site, or equipment. But tuning should not be used to fundamentally change the condition a given spark rule is detecting - in that case its better to use a different rule.

Tuning parameters are configured as tags on a ruleTuning record. All tuning records are scoped to a specific rule via the ruleRef tag and optionally scoped to targets via the ruleTuningTargetRef or ruleTuningTargetFilter tag.

Examples for ruleTuning records:

// tuning which applies to all targets of a specific rule
dis: "Tuning on Rule"
ruleTuning
ruleRef: @rule-id
tag1: "val1"
tag2: "val2"

// tuning which applies to targets under a specific site
dis: "Tuning on Targets under Site"
ruleTuning
ruleRef: @rule-id
ruleTuningTargetRef: @site-id
tag1: "val1"
tag2: "val2"

// tuning which applies to specific targets using a filter
dis: "Tuning on Targets Site in Virginia"
ruleTuning
ruleRef: @rule-id
ruleTuningTargetFilter: "siteRef->geoState==\"VA\""
tag1: "val1"
tag2: "val2"

If ruleTuningTargetRef is configured then the tuning record is applied if the target matches by id, siteRef, equipRef, or spaceRef. This allows selection of a specific target record or to select a parent record such as the parent site.

The results are merged together into a single Dict on a per target+rule basis. Tuning parameters are available inside each rule via the ruleTuning tag in the current context:

tuning: context()->ruleTuning

You can also pre-bind specific tuning parameters to component cells using the bindTuning in the cell meta as follows:

myTuningParam: {bindTuning:"myTuningTag", defVal:10sec}

The design allows multiple tuning records to apply for a given target+rule combination. The tuning record tags are merged together by ordering the tuning records from lowest to highest priority. Higher priority tuning record tags will override tags from lower priority tuning records. The priority is determined by sorting the the records with the order tag and then by the dis tag. Call the function ruleTunings() to see all your tuning records sorted by the priority order.

Clustering ​

Rules are configured and run locally in each project in the cluster. However end users work with rule data across the cluster (in apps such Spark and KPI). End user apps consider any rule with the same dis to the same logical rule. When deploying the same rule across the cluster, use a consistent dis, help, and color tag.

Rule Ready Funcs ​

Some functions are defined explicitly to be used as rules. We call these functions rule ready. Rule ready functions must define the following tags:

  • ruleOn: suitable default for rule's ruleOn tag
  • dis: suitable default for the rule's dis tag
  • help: suitable default for the rule's help tag
  • sparkRule, kpiRule, or curRule tag

Tools used to configure rules will query the project's function library for rule ready functions for easy configuration.



def ​

dur ​

Total duration of the spark periods measured in hours


meta ​

defdur
isduration
liblib:rule

supertypes ​

valData value type
scalarScalar is an atomic value kind
numberInteger or floating point numbers annotated with an optional unit
durationNumber with a unit of time


def ​

func:ruleDebug ​

ruleDebug(mode, arg1: null, arg2: null) ​

Return a debug grid from the rule engine. The mode string determines what information is queried:

  • summary: configuration and KPIs for rule engine
  • rules: summary of configured rules and their status
  • rule (ruleId): targets and status for a specific rule
  • targets: summary of all targets and their status
  • target (targetId): rules and status for a specific target
  • targetRule (targetId, ruleId): matrix of dates for given target/rule
  • comp (targetId, ruleId): component bindings

Note: the grid format of each mode response maps to what is shown in the Rule|Debug screen. However, the grid format is subject to change.

Examples:

ruleDebug("summary")
ruleDebug("rules")
ruleDebug("rule", @ruleId)
ruleDebug("targets")
ruleDebug("target", read(ahu))
ruleDebug("targetRule", read(ahu), read(rule and ruleOn=="ahu"))
ruleDebug("comp", read(ahu), read(dis=="AHU Cool Failure"))

meta ​

admin✓
deffunc:ruleDebug
isfunc
liblib:rule
nameruleDebug

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleDelete ​

ruleDelete(targets, span: null, rules: null, opts: null) ​

Delete works just like ruleRecompute() except it also deletes the sparks/KPIs from the cache. This function can be very expensive compared to a simple recompute. Recompute only requires updating the index to reset specific rule/date combinations to the unknown state. This function does the same, but also removes the actual cached spark/KPI for each rule/date combination.

This function deletes the sparks synchronously and can take a long time if there are many targets. If you deleting many targets then run this function within a task.

The default behavior is to automatically call ruleRosterRefresh() before the recompute to ensure the rules/targets are up-to-date. This behavior can be overridden by passing {noRefreshRoster} for options.

This function will also accept the result of the ruleOrphans() report.


meta ​

admin✓
deffunc:ruleDelete
isfunc
liblib:rule
nameruleDelete

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleErrs ​

ruleErrs(rules: null) ​

Return grid of all the rule+targets which have errors. The rules parameter may be any set of recs accepted by toRecList() or null to query all rules. This function does not automatically refresh the roster. The grid contains the following columns:

  • ruleRef: id of the rule rec
  • targetRef: id of the target or null if entire rule is in fault
  • status: type of error
  • errTrace: last exception (if rule has been run since reboot)

meta ​

admin✓
deffunc:ruleErrs
isfunc
liblib:rule
nameruleErrs

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleKpis ​

ruleKpis(targets, span, rules: null) ​

Query local KPIs along three dimensions of target x dates x rules. Targets and rules are any expr accepted by toRecList() or null for all. Span is any expr accepted by toSpan().


meta ​

deffunc:ruleKpis
isfunc
liblib:rule
nameruleKpis

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleKpisDigest ​

ruleKpisDigest(targets, span, rules: null) ​

Return grid of KPIs to use for a notification. The parameters follow the same semantics as ruleKpis(). The grid formatted as a card view suitable for an HTML email body.


meta ​

deffunc:ruleKpisDigest
isfunc
liblib:rule
nameruleKpisDigest

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleOrphans ​

ruleOrphans(targets, span) ​

Search the database for all previously cached sparks and KPIs which no longer have a valid rule record. The targets parameter may be any expr accepted by toRecList() or null for all. Span is any expr accepted by toSpan(). This situation occurs when you delete rule records from the database which have already cached their results. Or this function will also report targets which no longer match an existing rule's ruleOn filter.

The result is a grid with a row for each unique target+rule combination. The grid has following columns:

  • targetRef: target id
  • ruleRef: orphaned rule id
  • ruleType: "spark" or "kpi"
  • numDates: number of dates with orphaned sparks or kpis

You may pipe the results of this function directly to ruleDelete() to delete the orphaned data.

Also see the documentation.

Examples:

// run narrow report on specific targets and span
readAll(ahu).ruleOrphans(thisMonth)

// report on all orphaned data across database
ruleOrphans(null, null)

// delete all orphans across all targets and all time
ruleOrphans(null, null).ruleDelete

meta ​

admin✓
deffunc:ruleOrphans
isfunc
liblib:rule
nameruleOrphans

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleRecompute ​

ruleRecompute(targets, span, rules, opts: null) ​

Recompute local sparks or KPIs for the given targets/dates/rules. Targets and rules are any expr accepted by toRecList(). Span is any expr accepted by toSpan(). If null is passed for any parameter then it means all.

Recomputation clears the index for the selected target/dates/rules. It does not immediately remove the actual spark/kpi dicts. So until the engine gets a chance to re-run a rule, existing sparks/kpis remain in effect.

The default behavior is to automatically call ruleRosterRefresh() before the recompute to ensure the rules/targets are up-to-date. This behavior can be overridden by passing {noRefreshRoster} for options.

Examples:

// refresh single target/date/rule combination
ruleRecompute(@some-target, today, @some-rule)

// clear all rules/dates for given target
ruleRecompute(@some-target, null, null)

// clear all targets/dates for given rule
ruleRecompute(null, null, @some-rule)

meta ​

admin✓
deffunc:ruleRecompute
isfunc
liblib:rule
nameruleRecompute

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleReobserve ​

ruleReobserve(targets: null, rules: null) ​

Clear today's observed flag to re-observe sparks. Targets and rules may be null for wildcard or any value accepted by toRecList(). This function only clears the observed flag. New observations will not be fired until the rule is re-run by hot period or ruleRecompute. Note: this function is subject to change.


meta ​

admin✓
deffunc:ruleReobserve
isfunc
liblib:rule
nameruleReobserve

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleRosterRefresh ​

ruleRosterRefresh() ​

Force roster refresh


meta ​

admin✓
deffunc:ruleRosterRefresh
isfunc
liblib:rule
nameruleRosterRefresh

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleSparkExplain ​

ruleSparkExplain(spark) ​

Return explanation information for a spark. The param must be a spark dict - typically a row from the ruleSparks() function.

The explanation result is a dict with following tags:

  • spark: the spark dict parameter
  • explain: fandoc string taken from explain tag on the spark if available
  • help: the fandoc string for rule help tag
  • points: Ref[] for points used as inputs for the spark
  • tuning: Dict of tuning parameters

If the spark itself defines a points tag with a Ref[] value, then it is used. Otherwise, the system will attempt to resolve point inputs from the rule's component input bindings.

If the spark defines a tuning tag, then it is used. Otherwise, the system will include the current tuning parameters. Note that it is possible that tuning tags have been modified since the spark was computed. So the tuning Dict included by this function may not reflect the tuning actually used.

This function is used by the Explain action in the Spark|Equip view. Override this function to provide customized explain information. Each tag in the explain dict is displayed in the UI as follows:

  • dicts are shown using an info icon popup
  • multi-line strings are shown as fandoc
  • all other values are shown using their string value

Example:

spark: ruleSparks(null, lastWeek, null).first
ruleSparkExplain(spark)

meta ​

deffunc:ruleSparkExplain
isfunc
liblib:rule
nameruleSparkExplain
overridable✓

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleSparkHis ​

ruleSparkHis(sparks) ​

Turn a grid of sparks as returned by ruleSparks() into a history grid of the spark periods. Each unique combination of targetRef and ruleRef becomes the value columns.


meta ​

deffunc:ruleSparkHis
isfunc
liblib:rule
nameruleSparkHis

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleSparks ​

ruleSparks(targets, span, rules: null) ​

Query local sparks along three dimensions of target x dates x rules. Targets and rules are any expr accepted by toRecList() or null for all. Span is any expr accepted by toSpan().

Examples:

// read sparks last month for all targets and all rules
ruleSparks(null, lastMonth, null)

// read sparks only where targetRef is a given equip
read(rtu).ruleSparks(lastMonth, null)

// read sparks for all targets for a given rule
ruleSparks(null, lastMonth, rule)

meta ​

deffunc:ruleSparks
isfunc
liblib:rule
nameruleSparks

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleSparksCount ​

ruleSparksCount(targets, span, rules: null) ​

Return number of sparks as queried by ruleSparks(). The parameters have the same semantics, except this function is more efficient since it does not build a result grid first.


meta ​

deffunc:ruleSparksCount
isfunc
liblib:rule
nameruleSparksCount

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleSparksDigest ​

ruleSparksDigest(targets, since, rules: null) ​

Return grid of sparks to use for a notification. The parameters follow the same semantics as ruleSparks(). The grid is formatted as a card view suitable for an HTML email body. If since parameter is a span, then all the sparks for the given span are included. Or since may be a DateTime for today in which case only sparks which have been detected since the given timestamp are included. The since timestamp is compared against the first observed time for today which may be reset via ruleReobserve().


meta ​

deffunc:ruleSparksDigest
isfunc
liblib:rule
nameruleSparksDigest

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleTargetsUnder ​

ruleTargetsUnder(parents) ​

Get a grid of all the rule targets which are contained by the given parent. For example given a site record, get a list of all rule targets under that site including spaces, equips, and points with a corresponding siteRef. This function is more effcicient than using navResolve() because it only returns records which are known to be rule targets in the current roster for the local project.

Example:

// query all sparks under a given site
read(site).ruleTargetsUnder.ruleSparks(lastMonth)

meta ​

deffunc:ruleTargetsUnder
isfunc
liblib:rule
nameruleTargetsUnder

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleTest ​

ruleTest(rule, target: null, date: null, tuning: null) ​

Perform test run of rule. The rule may be a rule ready function or a rule record itself. If the target is omitted, then a target is auto-selected by ruleOn. If date is omitted and the rule is is spark or KPI then yesterday will be used.

The tuning parameter is an optional dict of tuning name/value pairs which is used to bind to to any cells with a bindTuning tags. If the given rule already has rule tuning, then the tuning parameter will override tags from the current configuration.

NOTE: this function's parameters and output is subject to change.

Examples:

// rule ready function - pass function by name
ruleTest(ahuCoolAndHeat)

// rule ready function with explicit target
ruleTest(ahuCoolAndHeat, @2b80f96a-ee1d1270)

// rule ready function with explicit target and date
ruleTest(ahuCoolAndHeat, @p:demo:r:2b80f96a-ee1d1270, 2023-03-01)

// rule record
read(rule and dis=="AHU Fan Failure").ruleTest

meta ​

admin✓
deffunc:ruleTest
isfunc
liblib:rule
nameruleTest

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleToTargets ​

ruleToTargets(rule) ​

Get all the target records the rule is registered on by the ruleOn tag. The rule may be any value accepted by toRec().


meta ​

deffunc:ruleToTargets
isfunc
liblib:rule
nameruleToTargets

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleTuning ​

ruleTuning(target, rule) ​

Return the effective tuning Dict for the given target/rule pair. Both target and rule may be anything accepted by toRecId().

Examples:

ruleTuning(@targetId, @ruleId)
read(ahu).ruleTuning(read(rule and dis=="My Rule"))

meta ​

deffunc:ruleTuning
isfunc
liblib:rule
nameruleTuning

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:ruleTunings ​

ruleTunings() ​

Read grid of tuning records sorted from lowest to highest priority.


meta ​

deffunc:ruleTunings
isfunc
liblib:rule
nameruleTunings

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:rulesToTargets ​

rulesToTargets(rules) ​

Get all the target records the list of rules is registered on by the ruleOn tag. The rule may be any value accepted by toRecList().


meta ​

deffunc:rulesToTargets
isfunc
liblib:rule
namerulesToTargets

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:targetToRules ​

targetToRules(target) ​

Get all the rule records which are registered on given target. The target may be any value accepted by toRec().


meta ​

deffunc:targetToRules
isfunc
liblib:rule
nametargetToRules

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:targetsToRules ​

targetsToRules(targets) ​

Get all the rule records which are registered on given list of targets. The target may be any value accepted by toRecList().


meta ​

deffunc:targetsToRules
isfunc
liblib:rule
nametargetsToRules

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

kpi ​

Marker tag to indicate a KPI dict


meta ​

defkpi
ismarker
liblib:rule

supertypes ​

markerMarker labels a dict with typing information


def ​

obsRuleFilter ​

Filter string for rule records to observe


meta ​

defobsRuleFilter
isobsFilter
liblib:rule
tagOnobsSparks

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters
filterStrHaystack filter string
obsFilterFilter string to define the record data set observed


def ​

obsSparks ​

Subscribe to rule engine sparks - see docs


meta ​

defobsSparks
isobservable
liblib:rule

supertypes ​

markerMarker labels a dict with typing information
observableObservable subscription - see docs

tags ​

obsRuleFilterFilter string for rule records to observe
obsTargetFilterFilter string for target records to observe


def ​

obsTargetFilter ​

Filter string for target records to observe


meta ​

defobsTargetFilter
isobsFilter
liblib:rule
tagOnobsSparks

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters
filterStrHaystack filter string
obsFilterFilter string to define the record data set observed


def ​

rule ​

Marker tag for a rule record. See rule.


meta ​

defrule
isentity
liblib:rule
mandatory✓

supertypes ​

markerMarker labels a dict with typing information
entityTop-level dicts with a unique identifier

tags ​

colorColor encoded as #RRGGBB, #RGB, or a CSS color keyword
disDisplay name for an entity
disabledIndicates the entity is in a disabled state
helpEnd user documentation
idDefines the unique identifier of an entity in system using a ref value type
ruleCostSpecifies formula used to apply a cost tag to sparks
ruleFreqExecution frequency of a curRule
ruleFuncSpecifies the function to run for a rule
ruleOnTarget filter for a rule or rule ready func
ruleStatusCurrent status of a rule
ruleTypeRule type choice


def ​

ruleCost ​

Specifies formula used to apply a cost tag to sparks. See rule.


meta ​

defruleCost
isstr
liblib:rule
tagOnrule
uiInputruleExt::RuleCostInput

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters


def ​

ruleFreq ​

Execution frequency of a curRule.


meta ​

defruleFreq
isduration
liblib:rule
tagOnrule

supertypes ​

valData value type
scalarScalar is an atomic value kind
numberInteger or floating point numbers annotated with an optional unit
durationNumber with a unit of time


def ​

ruleFunc ​

Specifies the function to run for a rule.


meta ​

defruleFunc
isstr
liblib:rule
tagOnrule

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters


def ​

ruleRef ​

Reference to rule which contains this entity


meta ​

containedByrule
defruleRef
isref
liblib:rule
ofrule
tagOnruleTuning

supertypes ​

valData value type
scalarScalar is an atomic value kind
refReference to an entity


def ​

ruleStatus ​

Current status of a rule


meta ​

defruleStatus
enumSee below
isstr
liblib:rule
tagOnrule
transient✓

enum ​

unknownStatus not computed yet
okAll is okay
faultConfiguration problem
disabledManual disable
errRule has thrown exceptions

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters


def ​

ruleTuning ​

Marker applied to a rec which defines a rule tuning configuration. See rule


meta ​

defruleTuning
isentity
liblib:rule
mandatory✓

supertypes ​

markerMarker labels a dict with typing information
entityTop-level dicts with a unique identifier

tags ​

disDisplay name for an entity
idDefines the unique identifier of an entity in system using a ref value type
ruleRefReference to rule which contains this entity
ruleTuningTargetFilterFilter string to match rule target records
ruleTuningTargetRefReference to a specific rule target or target parent


def ​

ruleTuningTargetFilter ​

Filter string to match rule target records


meta ​

defruleTuningTargetFilter
isfilterStr
liblib:rule
tagOnruleTuning

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters
filterStrHaystack filter string


def ​

ruleTuningTargetRef ​

Reference to a specific rule target or target parent


meta ​

defruleTuningTargetRef
isref
liblib:rule
navSelAnyRec✓
ofpoint
tagOnruleTuning

supertypes ​

valData value type
scalarScalar is an atomic value kind
refReference to an entity


def ​

spark ​

Marker tag to indicate a spark dict


meta ​

defspark
ismarker
liblib:rule

supertypes ​

markerMarker labels a dict with typing information


def ​

targetRef ​

Reference to the target record of a rule result or associated record.


meta ​

deftargetRef
isref
liblib:rule

supertypes ​

valData value type
scalarScalar is an atomic value kind
refReference to an entity


def ​

view:kpiChart ​

Visualize historized KPI analytical results using charts


meta ​

appNamekpi
defview:kpiChart
disKeyui::chart
iconview
isview
liblib:rule
order110

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:      {inherit:"chart"}
targets:   {var input kind:"Ref<equip>[]" navCluster navSelAny share}
span:      {var input kind:"Span" defVal:Span("today") share}
rules:     {var input uiInput:"ruleExt::RulesInput" kind:"Str[]" defVal:[] share ruleType:"kpi"}
menu:      {action:"uiContextMenu" selInput:"targets"}
data:      {expr:"ruleKpiChart({{targets}}, {{span}}, {{rules}})"}


def ​

view:kpiSwivel ​

Visualize KPI analytical results using graphical pivot tables


meta ​

appNamekpi
defview:kpiSwivel
disKeyui::swivel
iconview
isview
liblib:rule
order100

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:      {uiType:"uiMisc::SwivelView"}
uiViewBar: {var navPath:"targets" }
targets:   {var input kind:"Ref<equip>[]" navCluster navSelAny share}
span:      {var input kind:"Span" defVal:Span("today") share}
rules:     {var input uiInput:"ruleExt::RulesInput" kind:"Str[]" defVal:[] share ruleType:"kpi"}
opts:      {var input uiInput:"ruleExt::KpiSwivelInput" kind:"Dict" defVal:{}}
menu:      {action:"uiContextMenu" selInput:"targets"}
data:      {expr:"ruleKpiSwivel({{targets}}, {{span}}, {{rules}}, {{opts}})"}


def ​

view:kpiTable ​

Visualize KPI analytical results in tabular format


meta ​

appNamekpi
defview:kpiTable
disKeyui::table
iconview
isview
liblib:rule
order120

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:      {inherit:"table"}
targets:   {var input kind:"Ref<equip>[]" navCluster navSelAny share}
span:      {var input kind:"Span" defVal:Span("today") share}
rules:     {var input uiInput:"ruleExt::RulesInput" kind:"Str[]" defVal:[] share ruleType:"kpi"}
menu:      {action:"uiContextMenu" selInput:"targets"}
data:      {expr:"ruleKpiTable({{targets}}, {{span}}, {{rules}})"}


def ​

view:ruleCluster ​

View all rule records configured across the cluster


meta ​

admin✓
appNamerule
defview:ruleCluster
disKeyui::cluster
iconview
isview
liblib:rule
order110
templateNamerule

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:   {inherit:"table"}
search: {input var kind:"Str" defVal:""}
type:   {var input kind:"Str" enum:"all,spark,kpi,cur" defVal:"all"}
data:   {expr:"ruleCluster({{type}}, { search:{{search}} })"}


def ​

view:ruleDebug ​

Debug the rule engine


meta ​

admin✓
appNamerule
defview:ruleDebug
disKeyui::debug
iconview
isview
liblib:rule
order800

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:          {inherit:"table"}
uiViewBar:     {var navPath:"ref" }
search:        {input var kind:"Str" defVal:""}
ref:           {var kind:"Ref" defExpr:"null"}
recompute:     {action:"ruleExt::RuleDebugAction.recompute" disKey:"ui::recompute" select multi}
reobserve:     {action:"ruleExt::RuleDebugAction.reobserve" disKey:"ui::reobserve" select multi}
actorDebug:    {disKey:"ui::actorDebug" action:"ruleDebugReport" }
refreshRoster: {action:"ruleRosterRefresh"}
menu:          {action:"uiContextMenu"}
data:          {expr:"ruleDebugView({{ref}}, { search:{{search}} })"}


def ​

view:ruleLocal ​

Manage rules configured in the local project database


meta ​

admin✓
appNamerule
defview:ruleLocal
defNamerule
disKeyui::local
iconview
isview
liblib:rule
order100

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:    {inherit:"table"}
search:  {input var kind:"Str" defVal:""}
type:    {var input kind:"Str" enum:"all,spark,kpi,cur" defVal:"all"}
new:     {action:"recNew" uiInput:"ruleExt::RuleReadyNew.button"}
edit:    {action:"recEdit"}
trash:   {action:"recTrash"}
enable:  {action:"recEnable"}
disable: {action:"recDisable"}
menu:    {action:"uiContextMenu"}
data:    {expr:"ruleLocal({{type}}, { search:{{search}} })"}


def ​

view:ruleSettings ​

Settings for the rule extension


meta ​

admin✓
appNamesettings
defview:ruleSettings
disKeyui::rule
iconview
isview
liblib:rule

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:   {inherit:"form"}
submit: {action:"extSettingsCommit"}
data:   {expr:"extSettings(\"rule\")"}


def ​

view:ruleTuning ​

Manage rule tuning records in the local project database


meta ​

admin✓
appNamerule
defview:ruleTuning
defNameruleTuning
disKeyui::tuning
iconview
isview
liblib:rule

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:    { inherit:"table" }
search:  { input var kind:"Str" defVal:"" }
new:     { action:"recNew" }
edit:    { action:"recEdit" }
trash:   { action:"recTrash" }
menu:    { action:"uiContextMenu" }
data:    { expr:"readAll(ruleTuning, { sort, search:{{search}} })" }


def ​

view:sparkEquip ​

Visualize spark analytical results for a single equipment


meta ​

appNamespark
defview:sparkEquip
disKeyui::equip
iconview
isview
liblib:rule
order120

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:      {uiType:"ruleExt::SparkEquipView" renderAs:"chart"}
uiViewBar: {var navPath:"equip" }
equip:     {var input kind:"Ref<equip>" navCluster share}
span:      {var input kind:"Span" defVal:Span("today") share}
rules:     {var input uiInput:"ruleExt::RulesInput" kind:"Str[]" defVal:[] share ruleType:"spark"}
opts:      {var input kind:"Dict" disKey:"ui::options" templateName:"sparkEquipOpts" defVal:{showWeather:T}}
explain:   {action:"ruleSparkExplain", uiInput:"ruleExt::SparkEquipView.explain"}
sparks:    {action:"ruleExt::SparkEquipView.sparks"}
menu:      {action:"uiContextMenu" selInput:"equip"}
data:      {expr:"ruleSparkEquip({{equip}}, {{span}}, {{rules}}, {{opts}})"}


def ​

view:sparkSwivel ​

Visualize spark analytical results using graphical pivot tables


meta ​

appNamespark
defview:sparkSwivel
disKeyui::swivel
iconview
isview
liblib:rule
order100

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:      {uiType:"ruleExt::SparkSwivelView"}
uiViewBar: {var navPath:"targets"}
targets:   {var input kind:"Ref<equip>[]" navCluster navSelAny share}
span:      {var input kind:"Span" defVal:Span("today") share}
rules:     {var input uiInput:"ruleExt::RulesInput" kind:"Str[]" defVal:[] share ruleType:"spark"}
opts:      {var input uiInput:"ruleExt::SparkSwivelInput" kind:"Dict" defVal:{}}
menu:      {action:"uiContextMenu" selInput:"targets"}
data:      {expr:"ruleSparkSwivel({{targets}}, {{span}}, {{rules}}, {{opts}})"}


def ​

view:sparkTable ​

Visualize spark analytical results in tabular format


meta ​

appNamespark
defview:sparkTable
disKeyui::table
iconview
isview
liblib:rule
order110

supertypes ​

featureFeature namespace of definitions formatted as feature:name
viewFresco UI view

src ​

view:      {inherit:"table"}
targets:   {var input kind:"Ref<equip>[]" navCluster navSelAny share}
span:      {var input kind:"Span" defVal:Span("today") share}
rules:     {var input uiInput:"ruleExt::RulesInput" kind:"Str[]" defVal:[] share ruleType:"spark"}
menu:      {action:"uiContextMenu" selInput:"targets"}
data:      {expr:"ruleSparkTable({{targets}}, {{span}}, {{rules}})"}