Part VII: Operators and Standard Library
Version: 1.0 Draft Last Updated: 2025-12-20
1. Introduction
HGraph provides a comprehensive set of built-in operators and functions for common time-series operations. These are organized into categories:
graph TD
OPS[Operators & Functions]
OPS --> ARITH[Arithmetic]
OPS --> CMP[Comparison]
OPS --> LOGIC[Logical]
OPS --> FLOW[Flow Control]
OPS --> COLL[Collection]
OPS --> UTIL[Utility]
OPS --> MATH[Mathematical]
OPS --> STR[String]
OPS --> TIME[Temporal]
2. Arithmetic Operators
2.1 Binary Arithmetic
Operator |
Function |
Description |
|---|---|---|
|
|
Addition |
|
|
Subtraction |
|
|
Multiplication |
|
|
Division |
|
|
Floor division |
|
|
Modulo |
|
|
Power |
2.2 Unary Arithmetic
Operator |
Function |
Description |
|---|---|---|
|
|
Negation |
|
|
Positive (identity) |
|
|
Absolute value |
2.3 Type Signatures
# Scalar time-series
add_(lhs: TS[SCALAR], rhs: TS[SCALAR]) -> TS[SCALAR]
# With scalar constant
add_(lhs: TS[SCALAR], rhs: SCALAR) -> TS[SCALAR]
add_(lhs: SCALAR, rhs: TS[SCALAR]) -> TS[SCALAR]
# Collection time-series
add_(lhs: TSD[K, TS[V]], rhs: TSD[K, TS[V]]) -> TSD[K, TS[V]]
2.4 Example
@graph
def arithmetic_example(x: TS[float], y: TS[float]) -> TS[float]:
sum_ = x + y
diff = x - y
product = sum_ * diff
result = product / const(2.0)
return result
3. Comparison Operators
3.1 Comparison Functions
Operator |
Function |
Description |
|---|---|---|
|
|
Equal |
|
|
Not equal |
|
|
Less than |
|
|
Less or equal |
|
|
Greater than |
|
|
Greater or equal |
3.2 Type Signatures
eq_(lhs: TS[SCALAR], rhs: TS[SCALAR]) -> TS[bool]
lt_(lhs: TS[SCALAR], rhs: TS[SCALAR]) -> TS[bool]
3.3 Example
@graph
def comparison_example(temp: TS[float], threshold: float) -> TS[bool]:
return temp > const(threshold)
4. Logical Operators
4.1 Boolean Operations
Operator |
Function |
Description |
|---|---|---|
|
|
Logical AND |
|
|
Logical OR |
|
|
Logical NOT |
|
|
Logical XOR |
4.2 Type Signatures
and_(lhs: TS[bool], rhs: TS[bool]) -> TS[bool]
not_(a: TS[bool]) -> TS[bool]
4.3 Short-Circuit Behavior
Unlike Python’s native operators, HGraph’s logical operators evaluate both branches (reactive semantics):
graph LR
A["TS[bool]"]
B["TS[bool]"]
AND["and_(a, b)"]
A --> AND
B --> AND
AND --> R["TS[bool]"]
Note["Both a and b are evaluated<br/>and tracked for modifications"]
5. Flow Control
5.1 Conditional Functions
Function |
Description |
|---|---|
|
Conditional selection |
|
Wiring-time conditional |
|
Multi-way selection |
|
Pattern matching |
5.2 if_
Runtime conditional that outputs based on condition:
@graph
def conditional(flag: TS[bool], a: TS[int], b: TS[int]) -> TS[int]:
return if_(flag, a, b)
Behavior:
When
flagis True, output followsaWhen
flagis False, output followsbBoth branches remain active
5.3 switch_
Dynamic multi-branch selection:
@graph
def multi_select(key: TS[str], sources: TSD[str, TS[float]]) -> TS[float]:
return switch_({
"fast": sources["fast"],
"slow": sources["slow"],
"default": const(0.0)
}, key)
5.4 gate
Controls output based on condition:
gate(condition: TS[bool], ts: TS[T]) -> TS[T]
# Output ts.value only when condition is True
5.5 sample
Samples value when trigger fires:
sample(trigger: TS[bool], ts: TS[T]) -> TS[T]
# Output ts.value when trigger becomes True
6. Collection Operations
6.1 TSD (Dictionary) Operations
Function |
Description |
|---|---|
|
Get value for key |
|
Get all keys |
|
Number of entries |
|
Check key existence |
|
Merge dictionaries |
6.2 TSL (List) Operations
Function |
Description |
|---|---|
|
Get element at index |
|
Number of elements |
|
Sum all elements |
|
Average of elements |
6.3 TSS (Set) Operations
Function |
Description |
|---|---|
|
Check membership |
|
Number of items |
|
Set union |
|
Set intersection |
|
Set difference |
6.4 Map Operations
# Apply function to each element
map_(func, tsd) -> TSD[K, TS[W]]
map_(func, tsl) -> TSL[TS[W], Size]
# Example
@graph
def double_all(prices: TSD[str, TS[float]]) -> TSD[str, TS[float]]:
return map_(lambda p: p * 2, prices)
6.5 Reduce Operations
# Reduce collection to single value
reduce_(func, tsd, initial) -> TS[T]
reduce_(func, tsl, initial) -> TS[T]
# Example
@graph
def sum_prices(prices: TSD[str, TS[float]]) -> TS[float]:
return reduce_(add_, prices.values(), const(0.0))
7. Window Operations
7.1 Window Creation
window(ts: TS[T], size: int) -> TSW[T, Size]
# Create sliding window of last N values
7.2 Window Functions
Function |
Description |
|---|---|
|
Sum of window values |
|
Mean of window values |
|
Minimum value |
|
Maximum value |
|
Standard deviation |
|
Variance |
7.3 Example
@graph
def moving_average(price: TS[float], period: int) -> TS[float]:
w = window(price, period)
return mean_(w)
8. Temporal Operations
8.1 Time Functions
Function |
Description |
|---|---|
|
Current evaluation time |
|
Delay by N ticks |
|
Delay by time duration |
|
Difference from previous |
|
True when ts modified |
8.2 Scheduling Functions
Function |
Description |
|---|---|
|
Emit at scheduled time |
|
Limit update rate |
|
Delay until quiet |
|
Detect no updates |
8.3 Example
@graph
def rate_of_change(price: TS[float]) -> TS[float]:
prev = lag(price, timedelta(seconds=1))
return if_(prev.valid, price - prev, const(0.0))
9. Aggregation Functions
9.1 Basic Aggregations
Function |
Description |
|---|---|
|
Sum values |
|
Average values |
|
Minimum value |
|
Maximum value |
|
Count items |
9.2 Statistical Aggregations
Function |
Description |
|---|---|
|
Standard deviation |
|
Variance |
|
Median value |
|
Percentile calculation |
9.3 Time-Weighted
# Time-weighted average
twap_(price: TS[float]) -> TS[float]
# Volume-weighted average
vwap_(price: TS[float], volume: TS[float]) -> TS[float]
10. String Operations
10.1 String Functions
Function |
Description |
|---|---|
|
String formatting |
|
String concatenation |
|
Split string |
|
Join strings |
|
Uppercase |
|
Lowercase |
|
Remove whitespace |
10.2 Example
@graph
def format_message(symbol: TS[str], price: TS[float]) -> TS[str]:
return format_("{}: ${:.2f}", symbol, price)
11. Mathematical Functions
11.1 Basic Math
Function |
Description |
|---|---|
|
Square root |
|
Exponential |
|
Natural logarithm |
|
Base-10 logarithm |
|
Floor |
|
Ceiling |
|
Round to n decimals |
11.2 Trigonometric
Function |
Description |
|---|---|
|
Sine |
|
Cosine |
|
Tangent |
|
Arc sine |
|
Arc cosine |
|
Arc tangent |
|
Two-argument arc tangent |
12. Utility Functions
12.1 Type Conversion
Function |
Description |
|---|---|
|
Type conversion |
|
Convert to int |
|
Convert to float |
|
Convert to string |
12.2 Default Values
Function |
Description |
|---|---|
|
Use value if ts invalid |
|
First valid value |
12.3 Debugging
Function |
Description |
|---|---|
|
Print to console |
|
Trace modifications |
|
Log with level |
12.4 Example
@graph
def safe_divide(a: TS[float], b: TS[float]) -> TS[float]:
result = a / b
return default_(result, const(0.0))
13. Collection Constructors
13.1 const
Create constant time-series:
const(value: T) -> TS[T]
const(42) # TS[int]
const("hello") # TS[str]
const({"a": 1}) # TS[dict]
13.2 nothing
Create null/empty time-series:
nothing(TS[int]) # Unbound TS[int]
13.3 feedback
Create delayed feedback loop:
@graph
def accumulator() -> TS[int]:
fb = feedback(TS[int], delay=1)
current = add(source(), default_(fb(), const(0)))
fb(current)
return current
14. Higher-Order Functions
14.1 map_
Apply function to collection elements:
map_(func: Callable[[TS[T]], TS[U]], coll: TSD[K, TS[T]]) -> TSD[K, TS[U]]
14.2 filter_
Filter collection by predicate:
filter_(pred: Callable[[TS[T]], TS[bool]], coll: TSD[K, TS[T]]) -> TSD[K, TS[T]]
14.3 reduce_
Reduce collection to single value:
reduce_(func: Callable[[TS[T], TS[T]], TS[T]], coll, initial) -> TS[T]
14.4 fold_
Fold with state:
fold_(func: Callable[[TS[S], TS[T]], TS[S]], coll, initial: TS[S]) -> TS[S]
15. Operator Overloading
Python operators are mapped to HGraph functions:
15.1 Arithmetic Operators
Python |
HGraph |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15.2 Comparison Operators
Python |
HGraph |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
15.3 Logical Operators
Python |
HGraph |
|---|---|
|
|
|
|
|
|
|
|
15.4 Indexing
Python |
HGraph |
|---|---|
|
|
|
|
16. Extending Operators
16.1 Creating New Operators
Define new operators using the @operator decorator:
@operator
def custom_op(lhs: TIME_SERIES_TYPE, rhs: TIME_SERIES_TYPE) -> TIME_SERIES_TYPE:
"""Custom binary operation."""
16.2 Adding Overloads
Register implementations using overloads parameter:
@compute_node(overloads=custom_op)
def custom_op_ints(lhs: TS[int], rhs: TS[int]) -> TS[int]:
return lhs.value + rhs.value * 2
@compute_node(overloads=custom_op)
def custom_op_floats(lhs: TS[float], rhs: TS[float]) -> TS[float]:
return lhs.value + rhs.value * 2.0
16.3 Overload Resolution
When an operator is called, the best overload is selected by:
Type matching: Try to resolve each overload’s signature
Rank calculation: Calculate specificity rank for each candidate
Selection: Choose the candidate with lowest rank (most specific)
graph LR
CALL["custom_op(TS[int], TS[int])"]
CALL --> MATCH[Match Overloads]
MATCH --> R1["custom_op_ints: rank 0.001"]
MATCH --> R2["custom_op_floats: rank 0.001"]
MATCH --> R3["custom_op_generic: rank 1.0"]
R1 --> |"lowest rank"| SELECT[Selected]
16.4 Generic Rank
Type specificity is quantified by generic rank:
Type |
Rank |
|---|---|
Concrete ( |
~0.001 |
TypeVar ( |
~1.0 |
Most generic ( |
~1.0+ |
Lower rank = more specific = preferred.
16.5 Import Requirements
Overloads must be imported before use:
# In __init__.py or imported module
from my_package._impl._operators import custom_op_ints, custom_op_floats
For more details on operator overloading and custom resolvers, see 08_ADVANCED_CONCEPTS.md.
17. Reference Locations
Category |
Location |
|---|---|
Operators |
|
OperatorWiringNodeClass |
|
Generic Rank |
|
18. Standard Library Reference Locations
Category |
Location |
|---|---|
Arithmetic |
|
Comparison |
|
Logical |
|
Flow Control |
|
Collection |
|
Window |
|
Temporal |
|
Math |
|
String |
|
Utility |
|
19. Summary
HGraph’s operator system provides:
Familiar Python syntax through operator overloading
Type-safe operations with automatic type resolution
Reactive semantics with modification tracking
Collection support for TSD, TSL, TSS, TSW
Higher-order functions for functional programming
Extensibility through the
@operatordecorator