# How do I total a subscripted value and remember a past one?

A model with regions needs their total, their best and their worst, and a planner often needs a value from the past: the opening price, the stock at the last stock-take, or goods sent four days ago. The array functions fold a subscripted value, and the memory functions keep or delay one. The script runs three regions for 20 days and prints each answer on day 0 and on day 20.

```python
from nagasim import build as nb

# Three regions sell 10, 20 and 30 a day. SUM, PROD, VMAX and VMIN fold the region vector; INITIAL
# keeps day 0's price, SAMPLE_IF_TRUE keeps the stock read at the last stock-take (every 7 days),
# DELAY reads a 4-day shipping pipeline, ACTIVE_INITIAL gives a forecast of 25 while the initial
# values are set up (54 once the run moves it), and TABLE_EXTRAPOLATE continues a learning curve
# past its last point (10, 8, 7 hours at 0, 5 and 10 units, so 6 at 15).
m = nb.Model(time_limit=20, time_unit="days", sd={"dt": 1, "method": "euler"})
m.add_subscript(name="region", elements=["north", "south", "east"])
m.add_auxiliary(name="sales", dims=["region"], expr="10", elements={"south": "20", "east": "30"})
m.add_auxiliary(name="total", expr='SUM(AUX("sales[*]"))')
m.add_auxiliary(name="product", expr='PROD(AUX("sales[*]"))')
m.add_auxiliary(name="best", expr='VMAX(AUX("sales[*]"))')
m.add_auxiliary(name="worst", expr='VMIN(AUX("sales[*]"))')
m.add_auxiliary(name="price", expr="5 + 0.1 * TNOW")
m.add_auxiliary(name="opening_price", expr='INITIAL(AUX("price"))')
m.add_level(name="Stock", initial=100)
m.add_flow(name="sell", rate='AUX("total") / 10', rate_time_unit="days", **{"from": "Stock"})
m.add_auxiliary(name="stock_take", expr='SAMPLE_IF_TRUE(TNOW % 7 < 0.5, LEVEL("Stock"), 100)')
m.add_delay(name="shipping", input='AUX("total")', delay_time="4", kind="material")
m.add_auxiliary(name="arriving", expr='DELAY("shipping")')
m.add_auxiliary(name="forecast", expr='ACTIVE_INITIAL(AUX("total") * 0.9, 25)')
m.add_table(name="learning", keys=[0, 5, 10], values=[10, 8, 7], key_mode="linear")
m.add_auxiliary(name="hours_at_15", expr='TABLE_EXTRAPOLATE("learning", 15)')

series = m.run(seed=1)["timeseries"].pivot(index="Time", columns="Series", values="Value")
for name in ("total", "product", "best", "worst", "opening_price", "stock_take", "arriving",
             "forecast", "hours_at_15"):
    first, last = series["aux/" + name].iloc[0], series["aux/" + name].iloc[-1]
    print(f"{name:<14} day 0 {first:8.2f}   day 20 {last:8.2f}")

```

Save it as `recipe-regions-memory.py` and run it with `python`. Nothing here is random, so the numbers below are the same on your machine.

```text
total          day 0    60.00   day 20    60.00
product        day 0  6000.00   day 20  6000.00
best           day 0    30.00   day 20    30.00
worst          day 0    10.00   day 20    10.00
opening_price  day 0     5.00   day 20     5.00
stock_take     day 0   100.00   day 20    16.00
arriving       day 0     0.00   day 20    59.81
forecast       day 0    54.00   day 20    54.00
hours_at_15    day 0     6.00   day 20     6.00

```

## How it works

1. `SUM`, `PROD`, `VMAX` and `VMIN` fold `AUX("sales[*]")` over every region of the subscript.
2. `INITIAL` holds day 0's value, `SAMPLE_IF_TRUE` keeps the last value read while its condition held, and `DELAY` reads a named delay's output.
3. `ACTIVE_INITIAL` gives one value while initial values are set up and another while running; `TABLE_EXTRAPOLATE` continues a table's last slope.

## Elements used

- Functions: [`SUM`](../../reference/functions/arrays.md#sum), [`PROD`](../../reference/functions/arrays.md#prod), [`VMAX`](../../reference/functions/arrays.md#vmax), [`VMIN`](../../reference/functions/arrays.md#vmin), [`INITIAL`](../../reference/functions/system-dynamics.md#initial), [`SAMPLE_IF_TRUE`](../../reference/functions/system-dynamics.md#sample_if_true), [`ACTIVE_INITIAL`](../../reference/functions/system-dynamics.md#active_initial), [`DELAY`](../../reference/functions/model-state.md#delay), [`TABLE_EXTRAPOLATE`](../../reference/functions/model-state.md#table_extrapolate), [`LEVEL`](../../reference/functions/model-state.md#level), [`AUX`](../../reference/functions/model-state.md#aux).
- Model-file sections: [`subscripts`](../../reference/model-file/subscripts.md), [`auxiliaries`](../../reference/model-file/auxiliaries.md), [`delays`](../../reference/model-file/delays.md), [`tables`](../../reference/model-file/tables.md), [`levels`](../../reference/model-file/levels.md), [`flows`](../../reference/model-file/flows.md).
- Python: [`Model`](../../reference/api/Model.md).

Back to all [recipes](index.md).
