Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ Version 1.9 adds explicit report-only categorical outputs and fixed-period recur

## Development and operations

Scalar compatibility includes run-bound STARTTIME/STOPTIME values and calls,
inverse-trigonometric XMILE spellings, safe division and integer operations, and
[additional source-preserving MDL functions](docs/MDL-FUNCTION-COMPATIBILITY.md).
[Pinned Simlin observations](docs/COMPATIBILITY-REFERENCE-2026-10.md) distinguish
verified agreement from source-dialect differences and unsupported constructs;
these additions do not establish full Simlin/Vensim parity.

[Architecture](docs/ARCHITECTURE.md) · [Analytics](docs/ANALYTICS.md) · [Testing](docs/TESTING.md) · [UI direction](docs/UI-DIRECTION.md) · [UI QA](docs/UI-QA.md)

```bash
Expand Down
12 changes: 10 additions & 2 deletions app/core/adaptive.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
from app.core.limits import MAX_WORK_UNITS


DISCRETE_FUNCTIONS = {'FLOOR', 'CEIL', 'ROUND', 'SIGN', 'MOD', 'MODULO', 'INT', 'TRUNC', 'QUANTUM'}
SAFE_DIVISION_FUNCTIONS = {'SAFEDIV', 'ZIDZ', 'XIDZ'}


class _UncertifiedBoundary(Exception):
pass

Expand Down Expand Up @@ -270,7 +274,9 @@ def references(node):
findings.append({"element":elements[name].name,"operation":"state-dependent lookup forcing"})
elif function in {"IF", "IF_THEN_ELSE"} and len(node.args) == 3:
condition,yes,no = node.args
elif function in {"FLOOR", "CEIL", "ROUND", "SIGN", "MOD"} and references(node) & state_names:
elif function in DISCRETE_FUNCTIONS and references(node) & state_names:
findings.append({"element":elements[name].name,"operation":function})
elif function in SAFE_DIVISION_FUNCTIONS and len(node.args) >= 2 and references(node.args[1]) & state_names:
findings.append({"element":elements[name].name,"operation":function})
if condition is not None:
condition_nodes.update(id(n) for n in ast.walk(condition))
Expand Down Expand Up @@ -336,7 +342,9 @@ def references(node):
if table_key(function) not in table_names:
if function in {"IF", "IF_THEN_ELSE"} and node.args:
condition = node.args[0]
elif function in {"FLOOR", "CEIL", "ROUND", "SIGN", "MOD"} and references(node) & time_names:
elif function in DISCRETE_FUNCTIONS and references(node) & time_names:
findings.append({"element": name, "operation": function})
elif function in SAFE_DIVISION_FUNCTIONS and len(node.args) >= 2 and references(node.args[1]) & time_names:
findings.append({"element": name, "operation": function})
if isinstance(node, (ast.Compare, ast.BoolOp)):
condition = node
Expand Down
33 changes: 29 additions & 4 deletions app/core/equations.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,9 @@ def segment(x1, y1, x2, y2):
"asin": math.asin,
"acos": math.acos,
"atan": math.atan,
"arcsin": math.asin,
"arccos": math.acos,
"arctan": math.atan,
"atan2": math.atan2,
"sign": lambda value: float((value > 0) - (value < 0)),
"exp": math.exp,
Expand All @@ -187,9 +190,18 @@ def segment(x1, y1, x2, y2):
"max": max,
"pow": pow,
"floor": math.floor,
# INT is XMILE floor; TRUNC is the distinct toward-zero operation.
"int": math.floor,
"trunc": math.trunc,
"quantum": lambda x, q: x if q <= 0 else math.trunc(_finite_real(x / q)) * q,
# Keep exact-zero SAFEDIV separate from Vensim near-zero aliases.
"safediv": lambda a, b, fallback=0.0: fallback if b == 0 else a / b,
"zidz": lambda a, b: 0.0 if abs(b) < 1e-6 else a / b,
"xidz": lambda a, b, fallback: fallback if abs(b) < 1e-6 else a / b,
"ceil": math.ceil,
"round": round,
"mod": operator.mod,
"modulo": math.fmod, # Vensim/C remainder keeps the dividend's sign.
# Conditional function
"IF_THEN_ELSE": if_then_else,
"IF": if_then_else, # Alias for IF_THEN_ELSE
Expand All @@ -206,7 +218,7 @@ def segment(x1, y1, x2, y2):
"DELAYN": "DELAY_N", "DELAY": "DELAY_FIXED"}
STATEFUL_FUNCTIONS = {"DELAY1", "DELAY3", "DELAY_N", "DELAY_FIXED",
"SMOOTH", "SMOOTH3", "SMOOTH_N"} | set(STATEFUL_ALIASES)
CONTEXT_FUNCTIONS = {"STEP", "PULSE", "RAMP", "LOOKUP", "WITH_LOOKUP"} | STATEFUL_FUNCTIONS | STOCHASTIC_FUNCTIONS
CONTEXT_FUNCTIONS = {"STEP", "PULSE", "RAMP", "LOOKUP", "WITH_LOOKUP", "STARTTIME", "STOPTIME"} | STATEFUL_FUNCTIONS | STOCHASTIC_FUNCTIONS

SAFE_CONSTANTS: dict[str, float] = {
"pi": math.pi,
Expand Down Expand Up @@ -328,7 +340,10 @@ class SimulationContext:
def __init__(self, time: float = 0.0, dt: float = 0.25,
tables: Optional[dict[str, list[tuple[float, float]]]] = None,
delay_state: Optional[dict] = None,
smooth_state: Optional[dict] = None, random_runtime=None):
smooth_state: Optional[dict] = None, random_runtime=None,
start_time: float = 0.0, stop_time: float = 100.0):
self.start_time = start_time
self.stop_time = stop_time
self.time = time
# RK4 holds declared test-input primitives at the accepted left time.
# Ordinary TIME and algebra still use the current RK stage time.
Expand Down Expand Up @@ -474,6 +489,11 @@ def visit_Name(self, node: ast.Name) -> float:
if canonical in getattr(self.context, "declared_names", ()):
raise EquationError(f"Unknown variable: {name}", code="unknown_variable",
details={"symbol": name})
# Bounds are defaults only: authored declarations retain ownership.
if name_upper == "STARTTIME":
return _finite_real(self.context.start_time)
if name_upper == "STOPTIME":
return _finite_real(self.context.stop_time)
if name.lower() in SAFE_CONSTANTS:
return SAFE_CONSTANTS[name.lower()]
raise EquationError(f"Unknown variable: {name}", code="unknown_variable", details={"symbol": name})
Expand Down Expand Up @@ -606,6 +626,11 @@ def _handle_context_function(self, func_name: str, args: list) -> float:
call_key = getattr(self.context, "equation_key", "") + ":" + str(
(getattr(args[0], "col_offset", 0) if args else 0)) + ":" + (ast.dump(args[0]) if args else "")

if func_name in {"STARTTIME", "STOPTIME"}:
if args:
raise EquationError(f"{func_name} requires no arguments")
return _finite_real(self.context.start_time if func_name == "STARTTIME" else self.context.stop_time)

if func_name == "LOOKUP":
# LOOKUP(table_name, input) - table_name must be a string literal or name
if len(args) != 2:
Expand Down Expand Up @@ -1186,7 +1211,7 @@ def validate_equation(equation: str, available_variables: list[str],
tree = _parse_expression(preprocess_equation(equation))
known = {canonical_name(name) for name in available_variables}
known |= {canonical_name(name) for name in SAFE_CONSTANTS}
known |= {"time", "dt", "time_step"}
known |= {"time", "dt", "time_step", "starttime", "stoptime"}
tables = {canonical_name(name) for name in (table_names or [])}
functions = {name.upper() for name in SAFE_FUNCTIONS} | CONTEXT_FUNCTIONS
allowed_nodes = (ast.Expression, ast.Constant, ast.Name, ast.Load, ast.BinOp,
Expand All @@ -1211,7 +1236,7 @@ def validate_equation(equation: str, available_variables: list[str],
return False, f"Unknown lookup table: {table}"
unknown = {name for name in _reference_names(tree)
if resolve_name(name, available_variables) is None
and symbol_identity(name) not in {*SAFE_CONSTANTS, "time", "dt", "time_step"}}
and symbol_identity(name) not in {*SAFE_CONSTANTS, "time", "dt", "time_step", "starttime", "stoptime"}}
if unknown:
return False, f"Unknown variables: {', '.join(sorted(unknown))}"
return True, ""
Expand Down
5 changes: 5 additions & 0 deletions app/core/integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ def _plan_for(model):
def simulation_context(model, t, dt, delay, smooth, random_runtime=None, input_time=None, input_snapshot=None):
plan = _plan_for(model)
context = SimulationContext(t, dt, plan.tables if plan else {table.name: table.to_list() for table in model.tables}, delay, smooth, random_runtime)
context.start_time = model.time_settings.start
context.stop_time = model.time_settings.end
# Declared e/pi must wait for authored initializers, never constant fallback.
context.declared_names = plan.declared_names if plan else frozenset(canonical_name(element.name)
for element in (*model.stocks, *model.flows, *model.variables))
Expand Down Expand Up @@ -151,6 +153,9 @@ def integrate(model: Model, settings: TimeSettings):
except ValueError as exc:
raise EquationError(str(exc), code="discrete_period_mismatch", details={"period": period}) from exc
settings = settings.model_copy(update={"discrete_period": period})
# Context-bound time constants must reflect this run's overrides without
# mutating the saved model or leaking settings into concurrent simulations.
model = model.model_copy(update={"time_settings": settings})
numeric_model, reports = prepare_reports(model)
if not reports:
return _integrate_numeric(model, settings)
Expand Down
43 changes: 41 additions & 2 deletions app/core/mdl_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,15 +151,32 @@ def numeric_control(key, default):
legacy.setdefault(canonical_name(name), []).append(name)
candidates.update({key: names[0] for key,names in legacy.items()
if len(names) == 1 and key not in candidates})
candidates.update({"time":"TIME","time_step":"DT","initial_time":str(start),"final_time":str(end)})
candidates.update({"time":"TIME","time_step":"DT","initial_time":"STARTTIME","final_time":"STOPTIME"})
patterns=[]
for key,name in candidates.items():
pattern=r"[ _\n\u00a0]+".join(re.escape(part) for part in key.split("_"))
patterns.append((re.compile(pattern,re.I),key,name))
patterns.sort(key=lambda x:len(x[1]),reverse=True)
funcs={"IF THEN ELSE":"IF_THEN_ELSE",
"SIN":"sin","COS":"cos","TAN":"tan","ARCSIN":"asin","ARCCOS":"acos","ARCTAN":"atan",
"EXP":"exp","LN":"ln","SQRT":"sqrt","ABS":"abs","MIN":"min","MAX":"max","STEP":"STEP"}
"EXP":"exp","LN":"ln","SQRT":"sqrt","ABS":"abs","MIN":"min","MAX":"max","STEP":"STEP",
"LOG":"log","POWER":"pow","INTEGER":"TRUNC","MODULO":"MODULO","ZIDZ":"ZIDZ","XIDZ":"XIDZ","SMOOTH":"SMOOTH","SMOOTHI":"SMOOTH",
"SMOOTH3":"SMOOTH3","SMOOTH3I":"SMOOTH3"}
# Vensim function contracts, not spelling-based aliases. LOG has an explicit
# base; information smooths share the engine's continuous hidden-stock law.
# https://vensim.com/documentation/fn_log.html (x, base)
# https://vensim.com/documentation/fn_power.html (base, exponent)
# https://vensim.com/documentation/fn_smooth.html and fn_smooth3.html
# https://vensim.com/documentation/fn_integer.html truncates toward zero, not floor.
# https://vensim.com/documentation/fn_xidz.html and fn_zidz.html require
# abs(denominator)<1e-6; never translate these into exact-zero SAFEDIV.
# Simlin0.8.5 MDL currently translates them to SAFEDIV: that dialect mismatch
# is intentional here in favor of the documented Vensim source semantics.
# MODULO uses its distinct C-remainder primitive, never Python mod.
# https://vensim.com/documentation/fn_modulo.html
# Deliberately no PULSE (width/height), RANDOM (seed /
# truncation), SMOOTH N (discrete/order reduction), or material DELAY aliases.
strict_arities={"LOG":2,"POWER":2,"INTEGER":1,"MODULO":2,"ZIDZ":2,"XIDZ":3,"SMOOTH":2,"SMOOTHI":3,"SMOOTH3":2,"SMOOTH3I":3}
function_patterns=[(re.compile(r"[ _\s]+".join(k.split()),re.I),v) for k,v in sorted(funcs.items(),key=lambda x:-len(x[0]))]
translation_work = 0
def charge_translation(record):
Expand All @@ -177,6 +194,25 @@ def translate(expr, record):
charge_translation(record)
m=pattern.match(expr,pos)
if m and expr[m.end():].lstrip().startswith("("):
spelling=re.sub(r"[ _\s]+"," ",m.group()).upper()
if spelling in strict_arities:
begin=m.end()
while expr[begin].isspace():begin+=1
depth=0;quoted=False;escaped=False;end=None
for index in range(begin,len(expr)):
charge_translation(record)
char=expr[index]
if char=='"' and not escaped:quoted=not quoted
if not quoted:
if char=='(':depth+=1
elif char==')':
depth-=1
if depth==0:end=index;break
escaped=char=='\\' and not escaped if quoted else False
if end is None:fail("Unbalanced function arguments","invalid_syntax",record)
arguments=split_args(expr[begin+1:end],record)
if len(arguments)!=strict_arities[spelling] or not all(arguments):
fail(spelling+" requires "+str(strict_arities[spelling])+" arguments","invalid_syntax",record)
output.append(fn);pos=m.end();matched=True;break
if matched:continue
if expr[pos]=='"':
Expand All @@ -196,6 +232,9 @@ def translate(expr, record):
charge_translation(record)
m=pattern.match(expr,pos)
if m and (m.end()==len(expr) or not (expr[m.end()].isalnum() or expr[m.end()]=="_")):
if key in ("initial_time","final_time"):
if resolve_name(name,model_names.values()) is not None:
fail("Dynamic simulation control "+key+" conflicts with declared "+name,record=record)
output.append(json.dumps(name) if key in model_names else name)
pos=m.end();matched=True;break
if matched:continue
Expand Down
23 changes: 18 additions & 5 deletions app/core/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def expr(node, depth=0):
element = exact.get(owner)
if element is not None:
return units[element.id]
if name.upper() in {'TIME', 'DT', 'TIME_STEP'}:
if name.upper() in {'TIME', 'DT', 'TIME_STEP', 'STARTTIME', 'STOPTIME'}:
return clock
if name.lower() in {'pi', 'e', 'true', 'false'}:
return {}
Expand Down Expand Up @@ -231,10 +231,18 @@ def expr(node, depth=0):
note('unknown', 'lookup_axis_units', 'Inline or unresolved lookup has no declared input/output axis units')
return None
args = [visit(n) for n in node.args]
if upper in {'STARTTIME', 'STOPTIME'}:
if args or node.keywords:
note('unknown', 'function_signature', f'{upper} requires no arguments')
return None
return clock
counts = {'SIN':(1,1),'COS':(1,1),'TAN':(1,1),'ASIN':(1,1),'ACOS':(1,1),'ATAN':(1,1),
'ARCSIN':(1,1),'ARCCOS':(1,1),'ARCTAN':(1,1),
'INT':(1,1),'TRUNC':(1,1),'QUANTUM':(2,2),
'SAFEDIV':(2,3),'ZIDZ':(2,2),'XIDZ':(3,3),
'ATAN2':(2,2),'EXP':(1,1),'LOG':(1,2),'LN':(1,2),'LOG10':(1,1),'SQRT':(1,1),
'ABS':(1,1),'FLOOR':(1,1),'CEIL':(1,1),'ROUND':(1,2),'SIGN':(1,1),
'POW':(2,3),'MOD':(2,2),'IF':(3,3),'IF_THEN_ELSE':(3,3),
'POW':(2,3),'MOD':(2,2),'MODULO':(2,2),'IF':(3,3),'IF_THEN_ELSE':(3,3),
'STEP':(2,2),'PULSE':(2,3),'RAMP':(2,3),
'RANDOM':(2,3),'RANDOM_UNIFORM':(2,3),'RANDOM_NORMAL':(2,3),'NORMAL':(2,3),
'RANDOM_BINOMIAL':(2,3),'MIN':(2,1000),'MAX':(2,1000)}
Expand All @@ -250,16 +258,21 @@ def expr(node, depth=0):
note('unknown','unsupported_function','Three-argument POW units are not established')
return None
return visit(ast.BinOp(left=node.args[0], op=ast.Pow(), right=node.args[1]))
if upper == 'MOD':
if upper in {'MOD', 'MODULO'}:
return match(args[0],args[1],'MOD arguments')
if upper == 'QUANTUM':
return match(args[0], args[1], 'QUANTUM arguments')
if upper in {'SAFEDIV', 'ZIDZ', 'XIDZ'}:
quotient = _LITERAL if args[0] is _LITERAL and args[1] is _LITERAL else _combine(args[0], args[1], -1)
return match(quotient, args[2], f'{upper} fallback') if len(args) == 3 else quotient
if upper == 'RANDOM_BINOMIAL':
for value in args:
match(value, {}, 'Binomial argument')
return {}
if upper in {'IF', 'IF_THEN_ELSE'} and len(args) == 3:
match(args[0], {}, 'Condition')
return match(args[1], args[2], 'Conditional branches')
if upper in {'SIN','COS','TAN','ASIN','ACOS','ATAN','EXP','LOG','LN','LOG10'}:
if upper in {'SIN','COS','TAN','ASIN','ACOS','ATAN','ARCSIN','ARCCOS','ARCTAN','EXP','LOG','LN','LOG10'}:
for value in args:
match(value, {}, f'{upper} argument')
return {}
Expand All @@ -268,7 +281,7 @@ def expr(node, depth=0):
return {}
if upper == 'SQRT' and len(args) == 1:
return args[0] if args[0] is None or args[0] is _LITERAL else _combine({}, {k:v/2 for k,v in args[0].items()})
if upper in {'ABS','FLOOR','CEIL','ROUND'} and args:
if upper in {'ABS','FLOOR','CEIL','ROUND','INT','TRUNC'} and args:
if upper == 'ROUND' and len(args)>1:
match(args[1], {}, 'ROUND precision')
return args[0]
Expand Down
Loading
Loading