use of gov.sandia.n2a.eqset.VariableReference in project n2a by frothga.
the class InternalBackendData method analyzeEvents.
public static void analyzeEvents(final EquationSet s, final List<EventTarget> eventTargets, final List<Variable> eventReferences) {
class EventVisitor extends Visitor {
public boolean found;
public boolean visit(Operator op) {
if (op instanceof Event) {
found = true;
Event de = (Event) op;
if (// this event has not yet been analyzed
de.eventType == null) {
final EventTarget et = new EventTarget(de);
int targetIndex = eventTargets.indexOf(et);
if (// event target already exists
targetIndex >= 0) {
de.eventType = eventTargets.get(targetIndex);
} else // we must create a new event target, or more properly, fill in the event target we just used as a query object
{
// Create an entry and save the index
targetIndex = eventTargets.size();
eventTargets.add(et);
de.eventType = et;
et.container = s;
// Determine edge type
if (de.operands.length < 3) {
et.edge = EventTarget.RISE;
} else if (de.operands[2] instanceof Constant) {
Constant c = (Constant) de.operands[2];
if (c.value instanceof Text) {
Text t = (Text) c.value;
if (t.value.equalsIgnoreCase("nonzero"))
et.edge = EventTarget.NONZERO;
else if (t.value.equalsIgnoreCase("change"))
et.edge = EventTarget.CHANGE;
else if (t.value.equalsIgnoreCase("fall"))
et.edge = EventTarget.FALL;
else
et.edge = EventTarget.RISE;
} else {
Backend.err.get().println("ERROR: event() edge type must be a string.");
throw new Backend.AbortRun();
}
} else {
Backend.err.get().println("ERROR: event() edge type must be constant.");
throw new Backend.AbortRun();
}
// Allocate auxiliary variable
if (de.operands[0] instanceof AccessVariable) {
AccessVariable av = (AccessVariable) de.operands[0];
VariableReference reference = av.reference;
Variable v = reference.variable;
// then the user has broken the rule that we can't see temporaries in other parts.
if (v.hasAttribute("temporary") && v.container != s) {
Backend.err.get().println("WARNING: Cannot be temporary due to event monitor: " + v.container.name + "." + v.nameString() + " from " + s.name);
v.removeAttribute("temporary");
}
// so fall through to the !trackOne case below.
if (!v.hasAttribute("temporary")) {
// ensure it's buffered, so we can detect change
v.addAttribute("externalRead");
et.trackOne = true;
// just a holder for the reference
et.track = new Variable();
et.track.reference = reference;
}
}
if (// Expression, so create auxiliary variable. Aux not needed for NONZERO, because no change detection.
!et.trackOne && et.edge != EventTarget.NONZERO) {
et.track = new Variable("eventAux" + targetIndex, 0);
et.track.type = new Scalar(0);
et.track.reference = new VariableReference();
et.track.reference.variable = et.track;
}
// Locate any temporaries for evaluation. TODO: for more efficiency, we could have separate lists of temporaries for the condition and delay operands
// Tie into the dependency graph using a phantom variable (which can go away afterward without damaging the graph).
final Variable phantom = new Variable("event");
phantom.uses = new IdentityHashMap<Variable, Integer>();
for (int i = 0; i < et.event.operands.length; i++) et.event.operands[i].visit(new Visitor() {
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
Variable v = av.reference.variable;
if (!phantom.uses.containsKey(v))
phantom.uses.put(v, 1);
return false;
}
return true;
}
});
// Scan all variables in equation set to see if we need them
for (Variable t : s.variables) {
if (t.hasAttribute("temporary") && phantom.dependsOn(t) != null)
et.dependencies.add(t);
}
// Note the default is already set to -1 (no care)
class DelayVisitor extends Visitor {
TreeSet<EquationSet> containers = new TreeSet<EquationSet>();
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
// could include the target part itself, if in fact we use local variables
containers.add(av.reference.variable.container);
return false;
}
return true;
}
}
DelayVisitor dv = new DelayVisitor();
if (de.operands.length >= 2) {
if (de.operands[1] instanceof Constant) {
Constant c = (Constant) de.operands[1];
et.delay = (float) ((Scalar) c.value).value;
if (et.delay < 0)
et.delay = -1;
} else {
// indicates that we need to evaluate delay at run time
et.delay = -2;
de.operands[1].visit(dv);
}
}
// Set up monitors in source parts
class ConditionVisitor extends Visitor {
TreeSet<EquationSet> containers = new TreeSet<EquationSet>();
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
Variable v = av.reference.variable;
EquationSet sourceContainer = v.container;
containers.add(sourceContainer);
// Set up monitors for values that can vary during update.
if (!v.hasAttribute("constant") && !v.hasAttribute("initOnly") && !et.monitors(sourceContainer)) {
EventSource es = new EventSource(sourceContainer, et);
// null means self-reference, a special case handled in Part
if (sourceContainer != s)
es.reference = av.reference;
et.sources.add(es);
}
return false;
}
return true;
}
}
ConditionVisitor cv = new ConditionVisitor();
de.operands[0].visit(cv);
// Special case for event with no references that vary
if (et.sources.isEmpty()) {
// We can avoid creating a self monitor if we know for certain that the event will never fire
boolean neverFires = false;
if (de.operands[0] instanceof Constant) {
if (et.edge == EventTarget.NONZERO) {
Type op0 = ((Constant) de.operands[0]).value;
if (op0 instanceof Scalar) {
neverFires = ((Scalar) op0).value == 0;
} else {
Backend.err.get().println("ERROR: Condition for event() must resolve to a number.");
throw new Backend.AbortRun();
}
} else {
neverFires = true;
}
}
if (!neverFires) {
EventSource es = new EventSource(s, et);
// This is a self-reference, so es.reference should be null.
et.sources.add(es);
}
}
// Determine if monitor needs to test every target, or if one representative target is sufficient
for (EventSource source : et.sources) {
// associated with any given source instance, so every target must be evaluated separately.
if (cv.containers.size() > 1)
source.testEach = true;
if (dv.containers.size() > 1 || (dv.containers.size() == 1 && dv.containers.first() != source.container))
source.delayEach = true;
}
}
}
}
return true;
}
}
EventVisitor eventVisitor = new EventVisitor();
for (Variable v : s.variables) {
eventVisitor.found = false;
v.visit(eventVisitor);
if ((eventVisitor.found || v.dependsOnEvent()) && v.reference.variable != v)
eventReferences.add(v);
}
}
use of gov.sandia.n2a.eqset.VariableReference in project n2a by frothga.
the class JobC method generateDefinitionsLocal.
public void generateDefinitionsLocal(RendererC context) throws Exception {
EquationSet s = context.part;
BackendDataC bed = context.bed;
StringBuilder result = context.result;
context.global = false;
String ns = prefix(s) + "::";
// Unit ctor
if (bed.needLocalCtor) {
result.append(ns + prefix(s) + " ()\n");
result.append("{\n");
if (bed.needLocalDerivative) {
result.append(" stackDerivative = 0;\n");
}
if (bed.needLocalPreserve) {
result.append(" preserve = 0;\n");
}
for (EquationSet p : s.parts) {
result.append(" " + mangle(p.name) + ".container = this;\n");
BackendDataC pbed = (BackendDataC) p.backendData;
if (pbed.singleton) {
result.append(" " + mangle(p.name) + ".instance.container = this;\n");
}
}
if (s.accountableConnections != null) {
for (EquationSet.AccountableConnection ac : s.accountableConnections) {
result.append(" int " + prefix(ac.connection) + "_" + mangle(ac.alias) + "_count = 0;\n");
}
}
if (bed.refcount) {
result.append(" refcount = 0;\n");
}
if (bed.index != null) {
// -1 indicates that an index needs to be assigned. This should only be done once.
result.append(" __24index = -1;\n");
}
if (bed.localMembers.size() > 0) {
result.append(" clear ();\n");
}
result.append("}\n");
result.append("\n");
}
// Unit dtor
if (bed.needLocalDtor) {
result.append(ns + "~" + prefix(s) + " ()\n");
result.append("{\n");
if (bed.needLocalDerivative) {
result.append(" while (stackDerivative)\n");
result.append(" {\n");
result.append(" Derivative * temp = stackDerivative;\n");
result.append(" stackDerivative = stackDerivative->next;\n");
result.append(" delete temp;\n");
result.append(" }\n");
}
if (bed.needLocalPreserve) {
result.append(" if (preserve) delete preserve;\n");
}
result.append("}\n");
result.append("\n");
}
// Unit clear
if (bed.localMembers.size() > 0) {
result.append("void " + ns + "clear ()\n");
result.append("{\n");
for (Variable v : bed.localMembers) {
result.append(" " + zero(mangle(v), v) + ";\n");
}
result.append("}\n");
result.append("\n");
}
// Unit setPeriod
if (// instance of top-level population, so set period on wrapper whenever our period changes
s.container == null) {
result.append("void " + ns + "setPeriod (" + T + " dt)\n");
result.append("{\n");
result.append(" PartTime<" + T + ">::setPeriod (dt);\n");
result.append(" if (container->visitor->event != visitor->event) container->setPeriod (dt);\n");
result.append("}\n");
result.append("\n");
}
// Unit die
if (bed.needLocalDie) {
result.append("void " + ns + "die ()\n");
result.append("{\n");
if (s.metadata.getFlag("backend", "all", "fastExit")) {
result.append(" Simulator<" + T + ">::instance.stop = true;\n");
} else {
// tag part as dead
if (// $live is stored in this part
bed.liveFlag >= 0) {
result.append(" flags &= ~((" + bed.localFlagType + ") 0x1 << " + bed.liveFlag + ");\n");
}
// instance counting
if (bed.n != null && !bed.singleton)
result.append(" container->" + mangle(s.name) + ".n--;\n");
for (String alias : bed.accountableEndpoints) {
result.append(" " + mangle(alias) + "->" + prefix(s) + "_" + mangle(alias) + "_count--;\n");
}
// release event monitors
for (EventTarget et : bed.eventTargets) {
for (EventSource es : et.sources) {
String part = "";
if (es.reference != null)
part = resolveContainer(es.reference, context, "");
String eventMonitor = "eventMonitor_" + prefix(s);
if (es.monitorIndex > 0)
eventMonitor += "_" + es.monitorIndex;
result.append(" removeMonitor (" + part + eventMonitor + ", this);\n");
}
}
}
result.append("}\n");
result.append("\n");
}
// Unit enterSimulation
if (bed.localReference.size() > 0) {
result.append("void " + ns + "enterSimulation ()\n");
result.append("{\n");
// String rather than EquationSet, because we may have references to several different instances of the same EquationSet, and all must be accounted
TreeSet<String> touched = new TreeSet<String>();
for (VariableReference r : bed.localReference) {
String container = resolveContainer(r, context, "");
if (touched.add(container))
result.append(" " + container + "refcount++;\n");
}
result.append("}\n");
result.append("\n");
}
// Unit leaveSimulation
{
result.append("void " + ns + "leaveSimulation ()\n");
result.append("{\n");
if (!bed.singleton) {
result.append(" " + containerOf(s, false, "") + mangle(s.name) + ".remove (this);\n");
}
TreeSet<String> touched = new TreeSet<String>();
for (VariableReference r : bed.localReference) {
String container = resolveContainer(r, context, "");
if (touched.add(container))
result.append(" " + container + "refcount--;\n");
}
result.append("}\n");
result.append("\n");
}
// Unit isFree
if (bed.refcount) {
result.append("bool " + ns + "isFree ()\n");
result.append("{\n");
result.append(" return refcount == 0;\n");
result.append("}\n");
result.append("\n");
}
// Unit init
if (bed.needLocalInit) {
result.append("void " + ns + "init ()\n");
result.append("{\n");
s.setInit(1);
for (Variable v : bed.localBufferedExternal) {
// Clear both buffered and regular values, so we can use a proper combiner during init.
result.append(" " + clearAccumulator(mangle("next_", v), v, context) + ";\n");
result.append(" " + clearAccumulator(mangle(v), v, context) + ";\n");
}
for (EventTarget et : bed.eventTargets) {
if (et.timeIndex >= 0) {
// Normal values are modulo 1 second. This initial value guarantees no match.
result.append(" eventTime" + et.timeIndex + " = 10;\n");
}
// Auxiliary variables get initialized as part of the regular list below.
}
if (!bed.localFlagType.isEmpty()) {
if (bed.liveFlag >= 0) {
if (bed.newborn >= 0) {
result.append(" flags |= (" + bed.localFlagType + ") 0x1 << " + bed.liveFlag + ";\n");
} else {
result.append(" flags = (" + bed.localFlagType + ") 0x1 << " + bed.liveFlag + ";\n");
}
} else {
if (bed.newborn < 0) {
result.append(" flags = 0;\n");
}
// else flags has already been initialized by Population::add()
}
}
// Initialize static objects
for (// non-optimized list, so hopefully all variables are covered
Variable v : // non-optimized list, so hopefully all variables are covered
bed.localInit) {
for (EquationEntry e : v.equations) {
prepareStaticObjects(e.expression, context, " ");
if (e.condition != null)
prepareStaticObjects(e.condition, context, " ");
}
}
// Compute variables
if (bed.lastT) {
result.append(" lastT = Simulator<" + T + ">::instance.currentEvent->t;\n");
}
s.simplify("$init", bed.localInit);
if (T.equals("int"))
EquationSet.determineExponentsSimplified(bed.localInit);
EquationSet.determineOrderInit(bed.localInit);
if (bed.localInit.contains(bed.dt)) {
result.append(" EventStep<" + T + "> * event = getEvent ();\n");
context.hasEvent = true;
result.append(" " + type(bed.dt) + " " + mangle(bed.dt) + ";\n");
}
for (// optimized list: only variables with equations that actually fire during init
Variable v : // optimized list: only variables with equations that actually fire during init
bed.localInit) {
multiconditional(v, context, " ");
}
// TODO: may need to deal with REPLACE for buffered variables. See internal.Part
if (bed.localInit.contains(bed.dt)) {
result.append(" if (" + mangle(bed.dt) + " != event->dt) setPeriod (" + mangle(bed.dt) + ");\n");
} else if (// implies that bed.dt exists and is constant
bed.setDt) {
result.append(" setPeriod (" + resolve(bed.dt.reference, context, false) + ");\n");
}
// instance counting
if (bed.trackN)
result.append(" " + containerOf(s, false, "") + mangle(s.name) + ".n++;\n");
for (String alias : bed.accountableEndpoints) {
result.append(" " + mangle(alias) + "->" + prefix(s) + "_" + mangle(alias) + "_count++;\n");
}
// Request event monitors
for (EventTarget et : bed.eventTargets) {
for (EventSource es : et.sources) {
String part = "";
if (es.reference != null)
part = resolveContainer(es.reference, context, "");
String eventMonitor = "eventMonitor_" + prefix(s);
if (es.monitorIndex > 0)
eventMonitor += "_" + es.monitorIndex;
result.append(" " + part + eventMonitor + ".push_back (this);\n");
}
}
// contained populations
if (s.parts.size() > 0) {
// If there are parts at all, then orderedParts must be filled in correctly. Otherwise it may be null.
for (EquationSet e : s.orderedParts) {
if (((BackendDataC) e.backendData).needGlobalInit) {
result.append(" " + mangle(e.name) + ".init ();\n");
}
}
}
s.setInit(0);
context.hasEvent = false;
result.append("}\n");
result.append("\n");
}
// Unit integrate
if (bed.needLocalIntegrate) {
result.append("void " + ns + "integrate ()\n");
result.append("{\n");
push_region(result, ns + "integrate()");
if (bed.localIntegrated.size() > 0) {
if (bed.lastT) {
result.append(" " + T + " dt = Simulator<" + T + ">::instance.currentEvent->t - lastT;\n");
} else {
result.append(" EventStep<" + T + "> * event = getEvent ();\n");
context.hasEvent = true;
result.append(" " + T + " dt = event->dt;\n");
}
// Note the resolve() call on the left-hand-side below has lvalue==false.
// Integration always takes place in the primary storage of a variable.
String pad = "";
if (bed.needLocalPreserve) {
pad = " ";
result.append(" if (preserve)\n");
result.append(" {\n");
for (Variable v : bed.localIntegrated) {
result.append(" " + resolve(v.reference, context, false) + " = preserve->" + mangle(v) + " + ");
int shift = v.derivative.exponent + bed.dt.exponent - Operator.MSB - v.exponent;
if (shift != 0 && T.equals("int")) {
result.append("(int) ((int64_t) " + resolve(v.derivative.reference, context, false) + " * dt" + context.printShift(shift) + ");\n");
} else {
result.append(resolve(v.derivative.reference, context, false) + " * dt;\n");
}
}
result.append(" }\n");
result.append(" else\n");
result.append(" {\n");
}
for (Variable v : bed.localIntegrated) {
result.append(pad + " " + resolve(v.reference, context, false) + " += ");
int shift = v.derivative.exponent + bed.dt.exponent - Operator.MSB - v.exponent;
if (shift != 0 && T.equals("int")) {
result.append("(int) ((int64_t) " + resolve(v.derivative.reference, context, false) + " * dt" + context.printShift(shift) + ");\n");
} else {
result.append(resolve(v.derivative.reference, context, false) + " * dt;\n");
}
}
if (bed.needLocalPreserve)
result.append(" }\n");
}
// contained populations
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalIntegrate) {
result.append(" " + mangle(e.name) + ".integrate ();\n");
}
}
context.hasEvent = false;
pop_region(result);
result.append("}\n");
result.append("\n");
}
// Unit update
if (bed.needLocalUpdate) {
result.append("void " + ns + "update ()\n");
result.append("{\n");
push_region(result, ns + "update()");
for (Variable v : bed.localBufferedInternalUpdate) {
result.append(" " + type(v) + " " + mangle("next_", v) + ";\n");
}
s.simplify("$live", bed.localUpdate);
if (T.equals("int"))
EquationSet.determineExponentsSimplified(bed.localUpdate);
for (Variable v : bed.localUpdate) {
multiconditional(v, context, " ");
}
for (Variable v : bed.localBufferedInternalUpdate) {
result.append(" " + mangle(v) + " = " + mangle("next_", v) + ";\n");
}
// contained populations
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalUpdate) {
result.append(" " + mangle(e.name) + ".update ();\n");
}
}
pop_region(result);
result.append("}\n");
result.append("\n");
}
// Unit finalize
if (bed.needLocalFinalize) {
result.append("bool " + ns + "finalize ()\n");
result.append("{\n");
// contained populations
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalFinalize) {
// ignore return value
result.append(" " + mangle(e.name) + ".finalize ();\n");
}
}
// Early-out if we are already dead
if (// $live is stored in this part
bed.liveFlag >= 0) {
// early-out if we are already dead, to avoid another call to die()
result.append(" if (! (flags & (" + bed.localFlagType + ") 0x1 << " + bed.liveFlag + ")) return false;\n");
}
// Preemptively fetch current event
boolean needT = bed.eventSources.size() > 0 || s.lethalP || bed.localBufferedExternal.contains(bed.dt);
if (needT) {
result.append(" EventStep<" + T + "> * event = getEvent ();\n");
context.hasEvent = true;
}
// Events
for (EventSource es : bed.eventSources) {
EventTarget et = es.target;
String eventMonitor = "eventMonitor_" + prefix(et.container);
if (es.monitorIndex > 0)
eventMonitor += "_" + es.monitorIndex;
if (es.testEach) {
result.append(" for (Part * p : " + eventMonitor + ")\n");
result.append(" {\n");
result.append(" if (! p->eventTest (" + et.valueIndex + ")) continue;\n");
eventGenerate(" ", et, context, false);
result.append(" }\n");
} else // All monitors share same condition, so only test one.
{
result.append(" if (! " + eventMonitor + ".empty () && " + eventMonitor + "[0]->eventTest (" + et.valueIndex + "))\n");
result.append(" {\n");
if (// Each target instance may require a different delay.
es.delayEach) {
result.append(" for (auto p : " + eventMonitor + ")\n");
result.append(" {\n");
eventGenerate(" ", et, context, false);
result.append(" }\n");
} else // All delays are the same.
{
eventGenerate(" ", et, context, true);
}
result.append(" }\n");
}
}
int eventCount = bed.eventTargets.size();
if (eventCount > 0) {
result.append(" flags &= ~(" + bed.localFlagType + ") 0 << " + eventCount + ";\n");
}
// Finalize variables
if (bed.lastT) {
result.append(" lastT = Simulator<" + T + ">::instance.currentEvent->t;\n");
}
for (Variable v : bed.localBufferedExternal) {
if (v == bed.dt) {
result.append(" if (" + mangle("next_", v) + " != event->dt) setPeriod (" + mangle("next_", v) + ");\n");
} else {
result.append(" " + mangle(v) + " = " + mangle("next_", v) + ";\n");
}
}
for (Variable v : bed.localBufferedExternalWrite) {
result.append(" " + clearAccumulator(mangle("next_", v), v, context) + ";\n");
}
if (bed.type != null) {
result.append(" switch (" + mangle("$type") + ")\n");
result.append(" {\n");
// Each "split" is one particular set of new parts to transform into.
// Each combination requires a separate piece of code. Thus, the outer
// structure here is a switch statement. Each case within the switch implements
// a particular combination of new parts. At this point, $type merely indicates
// which combination to process. Afterward, it will be set to an index within that
// combination, per the N2A language document.
int countSplits = s.splits.size();
for (int i = 0; i < countSplits; i++) {
ArrayList<EquationSet> split = s.splits.get(i);
// Check if $type = me. Ignore this particular case, since it is a null operation
if (split.size() == 1 && split.get(0) == s) {
continue;
}
result.append(" case " + (i + 1) + ":\n");
result.append(" {\n");
// indicates that this instance is one of the resulting parts
boolean used = false;
int countParts = split.size();
for (int j = 0; j < countParts; j++) {
EquationSet to = split.get(j);
if (to == s && !used) {
used = true;
result.append(" " + mangle("$type") + " = " + (j + 1) + ";\n");
} else {
result.append(" " + containerOf(s, false, "") + mangle(s.name) + "_2_" + mangle(to.name) + " (this, " + (j + 1) + ");\n");
}
}
if (used) {
result.append(" break;\n");
} else {
result.append(" die ();\n");
result.append(" return false;\n");
}
result.append(" }\n");
}
result.append(" }\n");
}
if (s.lethalP) {
// lethalP implies that $p exists, so no need to check for null
if (bed.p.hasAttribute("constant")) {
double pvalue = ((Scalar) ((Constant) bed.p.equations.first().expression).value).value;
if (pvalue != 0) {
// If $t' is exactly 1, then pow() is unnecessary here. However, that is a rare situation.
result.append(" if (pow (" + resolve(bed.p.reference, context, false) + ", " + resolve(bed.dt.reference, context, false));
if (context.useExponent) {
// second operand must have exponent=15
result.append(context.printShift(bed.dt.exponent - 15));
// exponentA
result.append(", " + bed.p.exponent);
// exponentResult
result.append(", " + bed.p.exponent);
}
result.append(") < uniform<" + T + "> ()");
// -1 is hard-coded from the Uniform function.
if (context.useExponent)
result.append(context.printShift(-1 - bed.p.exponent));
result.append(")\n");
}
} else {
if (bed.p.hasAttribute("temporary")) {
// Assemble a minimal set of expressions to evaluate $p
List<Variable> list = new ArrayList<Variable>();
for (Variable t : s.ordered) if (t.hasAttribute("temporary") && bed.p.dependsOn(t) != null)
list.add(t);
list.add(bed.p);
s.simplify("$live", list, bed.p);
if (T.equals("int"))
EquationSet.determineExponentsSimplified(list);
for (Variable v : list) {
multiconditional(v, context, " ");
}
}
result.append(" if (" + mangle("$p") + " <= 0 || " + mangle("$p") + " < " + context.print(1, bed.p.exponent) + " && pow (" + mangle("$p") + ", " + resolve(bed.dt.reference, context, false));
if (context.useExponent) {
result.append(context.printShift(bed.dt.exponent - 15));
result.append(", " + bed.p.exponent);
result.append(", " + bed.p.exponent);
}
result.append(") < uniform<" + T + "> ()");
if (context.useExponent)
result.append(context.printShift(-1 - bed.p.exponent));
result.append(")\n");
}
result.append(" {\n");
result.append(" die ();\n");
result.append(" return false;\n");
result.append(" }\n");
}
if (s.lethalConnection) {
for (ConnectionBinding c : s.connectionBindings) {
VariableReference r = s.resolveReference(c.alias + ".$live");
if (!r.variable.hasAttribute("constant")) {
result.append(" if (" + resolve(r, context, false, "", true) + " == 0)\n");
result.append(" {\n");
result.append(" die ();\n");
result.append(" return false;\n");
result.append(" }\n");
}
}
}
if (s.lethalContainer) {
VariableReference r = s.resolveReference("$up.$live");
if (!r.variable.hasAttribute("constant")) {
result.append(" if (" + resolve(r, context, false, "", true) + " == 0)\n");
result.append(" {\n");
result.append(" die ();\n");
result.append(" return false;\n");
result.append(" }\n");
}
}
result.append(" return true;\n");
context.hasEvent = false;
result.append("}\n");
result.append("\n");
}
// Unit updateDerivative
if (bed.needLocalUpdateDerivative) {
result.append("void " + ns + "updateDerivative ()\n");
result.append("{\n");
push_region(result, ns + "updateDerivative()");
for (Variable v : bed.localBufferedInternalDerivative) {
result.append(" " + type(v) + " " + mangle("next_", v) + ";\n");
}
s.simplify("$live", bed.localDerivativeUpdate);
if (T.equals("int"))
EquationSet.determineExponentsSimplified(bed.localDerivativeUpdate);
for (Variable v : bed.localDerivativeUpdate) {
multiconditional(v, context, " ");
}
for (Variable v : bed.localBufferedInternalDerivative) {
result.append(" " + mangle(v) + " = " + mangle("next_", v) + ";\n");
}
// contained populations
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalUpdateDerivative) {
result.append(" " + mangle(e.name) + ".updateDerivative ();\n");
}
}
pop_region(result);
result.append("}\n");
result.append("\n");
}
// Unit finalizeDerivative
if (bed.needLocalFinalizeDerivative) {
result.append("void " + ns + "finalizeDerivative ()\n");
result.append("{\n");
for (Variable v : bed.localBufferedExternalDerivative) {
result.append(" " + mangle(v) + " = " + mangle("next_", v) + ";\n");
}
for (Variable v : bed.localBufferedExternalWriteDerivative) {
result.append(" " + clearAccumulator(mangle("next_", v), v, context) + ";\n");
}
// contained populations
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalFinalizeDerivative) {
result.append(" " + mangle(e.name) + ".finalizeDerivative ();\n");
}
}
result.append("}\n");
result.append("\n");
}
if (bed.needLocalPreserve) {
// Unit snapshot
result.append("void " + ns + "snapshot ()\n");
result.append("{\n");
if (bed.needLocalPreserve) {
result.append(" preserve = new Preserve;\n");
for (Variable v : bed.localIntegrated) {
result.append(" preserve->" + mangle(v) + " = " + mangle(v) + ";\n");
}
for (Variable v : bed.localDerivativePreserve) {
result.append(" preserve->" + mangle(v) + " = " + mangle(v) + ";\n");
}
for (Variable v : bed.localBufferedExternalWriteDerivative) {
result.append(" preserve->" + mangle("next_", v) + " = " + mangle("next_", v) + ";\n");
result.append(" " + clearAccumulator(mangle("next_", v), v, context) + ";\n");
}
}
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalPreserve) {
result.append(" " + mangle(e.name) + ".snapshot ();\n");
}
}
result.append("}\n");
result.append("\n");
// Unit restore
result.append("void " + ns + "restore ()\n");
result.append("{\n");
if (bed.needLocalPreserve) {
for (Variable v : bed.localDerivativePreserve) {
result.append(" " + mangle(v) + " = preserve->" + mangle(v) + ";\n");
}
for (Variable v : bed.localBufferedExternalWriteDerivative) {
result.append(" " + mangle("next_", v) + " = preserve->" + mangle("next_", v) + ";\n");
}
result.append(" delete preserve;\n");
result.append(" preserve = 0;\n");
}
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalPreserve) {
result.append(" " + mangle(e.name) + ".restore ();\n");
}
}
result.append("}\n");
result.append("\n");
}
if (bed.needLocalDerivative) {
// Unit pushDerivative
result.append("void " + ns + "pushDerivative ()\n");
result.append("{\n");
if (bed.localDerivative.size() > 0) {
result.append(" Derivative * temp = new Derivative;\n");
result.append(" temp->next = stackDerivative;\n");
result.append(" stackDerivative = temp;\n");
for (Variable v : bed.localDerivative) {
result.append(" temp->" + mangle(v) + " = " + mangle(v) + ";\n");
}
}
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalDerivative) {
result.append(" " + mangle(e.name) + ".pushDerivative ();\n");
}
}
result.append("}\n");
result.append("\n");
// Unit multiplyAddToStack
result.append("void " + ns + "multiplyAddToStack (" + T + " scalar)\n");
result.append("{\n");
for (Variable v : bed.localDerivative) {
result.append(" stackDerivative->" + mangle(v) + " += ");
if (T.equals("int")) {
result.append("(int) ((int64_t) " + mangle(v) + " * scalar >> " + (Operator.MSB - 1) + ");\n");
} else {
result.append(mangle(v) + " * scalar;\n");
}
}
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalDerivative) {
result.append(" " + mangle(e.name) + ".multiplyAddToStack (scalar);\n");
}
}
result.append("}\n");
result.append("\n");
// Unit multiply
result.append("void " + ns + "multiply (" + T + " scalar)\n");
result.append("{\n");
for (Variable v : bed.localDerivative) {
if (T.equals("int")) {
result.append(" " + mangle(v) + " = (int64_t) " + mangle(v) + " * scalar >> " + (Operator.MSB - 1) + ";\n");
} else {
result.append(" " + mangle(v) + " *= scalar;\n");
}
}
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalDerivative) {
result.append(" " + mangle(e.name) + ".multiply (scalar);\n");
}
}
result.append("}\n");
result.append("\n");
// Unit addToMembers
result.append("void " + ns + "addToMembers ()\n");
result.append("{\n");
if (bed.localDerivative.size() > 0) {
for (Variable v : bed.localDerivative) {
result.append(" " + mangle(v) + " += stackDerivative->" + mangle(v) + ";\n");
}
result.append(" Derivative * temp = stackDerivative;\n");
result.append(" stackDerivative = stackDerivative->next;\n");
result.append(" delete temp;\n");
}
for (EquationSet e : s.parts) {
if (((BackendDataC) e.backendData).needGlobalDerivative) {
result.append(" " + mangle(e.name) + ".addToMembers ();\n");
}
}
result.append("}\n");
result.append("\n");
}
// Unit setPart
if (s.connectionBindings != null) {
result.append("void " + ns + "setPart (int i, Part * part)\n");
result.append("{\n");
result.append(" switch (i)\n");
result.append(" {\n");
for (ConnectionBinding c : s.connectionBindings) {
result.append(" case " + c.index + ": " + mangle(c.alias) + " = (" + prefix(c.endpoint) + " *) part; return;\n");
}
result.append(" }\n");
result.append("}\n");
result.append("\n");
}
// Unit getPart
if (s.connectionBindings != null) {
result.append("Part<" + T + "> * " + ns + "getPart (int i)\n");
result.append("{\n");
result.append(" switch (i)\n");
result.append(" {\n");
for (ConnectionBinding c : s.connectionBindings) {
result.append(" case " + c.index + ": return " + mangle(c.alias) + ";\n");
}
result.append(" }\n");
result.append(" return 0;\n");
result.append("}\n");
result.append("\n");
}
// Unit getCount
if (bed.accountableEndpoints.size() > 0) {
result.append("int " + ns + "getCount (int i)\n");
result.append("{\n");
result.append(" switch (i)\n");
result.append(" {\n");
for (ConnectionBinding c : s.connectionBindings) {
if (bed.accountableEndpoints.contains(c.alias)) {
result.append(" case " + c.index + ": return " + mangle(c.alias) + "->" + prefix(s) + "_" + mangle(c.alias) + "_count;\n");
}
}
result.append(" }\n");
result.append(" return 0;\n");
result.append("}\n");
result.append("\n");
}
// Unit getProject
if (bed.hasProject) {
result.append("void " + ns + "getProject (int i, MatrixFixed<" + T + ",3,1> & xyz)\n");
result.append("{\n");
// $project is evaluated similar to $p. The result is not stored.
s.setConnect(1);
result.append(" switch (i)\n");
result.append(" {\n");
boolean needDefault = false;
for (ConnectionBinding c : s.connectionBindings) {
result.append(" case " + c.index + ":");
Variable project = s.find(new Variable(c.alias + ".$project"));
if (// fetch $xyz from endpoint
project == null) {
VariableReference fromXYZ = s.resolveReference(c.alias + ".$xyz");
if (fromXYZ.variable == null) {
needDefault = true;
} else {
if (// calculated value
fromXYZ.variable.hasAttribute("temporary")) {
result.append(" " + mangle(c.alias) + "->getXYZ (xyz); break;\n");
} else // stored value or "constant"
{
result.append(" xyz = " + resolve(fromXYZ, context, false) + "; break;\n");
}
}
} else // compute $project
{
// to complete the "case" line
result.append("\n");
result.append(" {\n");
if (// it could also be "constant", but no other type
project.hasAttribute("temporary")) {
// Assemble a minimal set of expressions to evaluate $project
List<Variable> list = new ArrayList<Variable>();
for (Variable t : s.ordered) {
if ((t.hasAttribute("temporary") || bed.localMembers.contains(t)) && project.dependsOn(t) != null)
list.add(t);
}
list.add(project);
s.simplify("$connect", list, project);
if (T.equals("int"))
EquationSet.determineExponentsSimplified(list);
for (Variable v : list) {
multiconditional(v, context, " ");
}
}
result.append(" xyz = " + resolve(project.reference, context, false) + ";\n");
result.append(" break;\n");
result.append(" }\n");
}
}
if (needDefault) {
result.append(" default:\n");
result.append(" xyz[0] = 0;\n");
result.append(" xyz[1] = 0;\n");
result.append(" xyz[2] = 0;\n");
}
result.append(" }\n");
result.append("}\n");
s.setConnect(0);
}
// Unit mapIndex
if (s.connectionMatrix != null && s.connectionMatrix.needsMapping) {
result.append("int " + ns + "mapIndex (int i, int rc)\n");
result.append("{\n");
Variable rc = new Variable("rc");
rc.reference = new VariableReference();
rc.reference.variable = rc;
rc.container = s;
rc.addAttribute("preexistent");
AccessVariable av = new AccessVariable();
av.reference = rc.reference;
ConnectionMatrix cm = s.connectionMatrix;
cm.rowMapping.replaceRC(av);
cm.colMapping.replaceRC(av);
result.append(" if (i == " + cm.rows.index + ") return ");
cm.rowMapping.rhs.render(context);
result.append(";\n");
result.append(" return ");
cm.colMapping.rhs.render(context);
result.append(";\n");
result.append("}\n");
result.append("\n");
}
// Unit getNewborn
if (bed.newborn >= 0) {
result.append("bool " + ns + "getNewborn ()\n");
result.append("{\n");
result.append(" return flags & (" + bed.localFlagType + ") 0x1 << " + bed.newborn + ";\n");
result.append("}\n");
result.append("\n");
}
// Unit getLive
if (bed.live != null && !bed.live.hasAttribute("constant")) {
result.append(T + " " + ns + "getLive ()\n");
result.append("{\n");
if (// "accessor" indicates whether or not $value is actually stored
!bed.live.hasAttribute("accessor")) {
result.append(" if (" + resolve(bed.live.reference, context, false, "", true) + " == 0) return 0;\n");
}
if (s.lethalConnection) {
for (ConnectionBinding c : s.connectionBindings) {
VariableReference r = s.resolveReference(c.alias + ".$live");
if (!r.variable.hasAttribute("constant")) {
result.append(" if (" + resolve(r, context, false, "", true) + " == 0) return 0;\n");
}
}
}
if (s.lethalContainer) {
VariableReference r = s.resolveReference("$up.$live");
if (!r.variable.hasAttribute("constant")) {
result.append(" if (" + resolve(r, context, false, "", true) + " == 0) return 0;\n");
}
}
result.append(" return 1;\n");
result.append("}\n");
result.append("\n");
}
// Unit getP
if (// Only connections need to provide an accessor
bed.p != null && s.connectionBindings != null) {
result.append(T + " " + ns + "getP ()\n");
result.append("{\n");
s.setConnect(1);
if (!bed.p.hasAttribute("constant")) {
// Assemble a minimal set of expressions to evaluate $p
List<Variable> list = new ArrayList<Variable>();
for (Variable t : s.ordered) {
if ((t.hasAttribute("temporary") || bed.localMembers.contains(t)) && bed.p.dependsOn(t) != null)
list.add(t);
}
list.add(bed.p);
s.simplify("$connect", list, bed.p);
if (T.equals("int"))
EquationSet.determineExponentsSimplified(list);
for (Variable v : list) {
multiconditional(v, context, " ");
}
}
result.append(" return " + resolve(bed.p.reference, context, false) + ";\n");
s.setConnect(0);
result.append("}\n");
result.append("\n");
}
// Unit getXYZ
if (// Connection targets need to provide an accessor.
bed.xyz != null && s.connected) {
result.append("void " + ns + "getXYZ (MatrixFixed<" + T + ",3,1> & xyz)\n");
result.append("{\n");
// If stored, then simply copy into the return value.
if (bed.xyz.hasAttribute("temporary")) {
// Assemble a minimal set of expressions to evaluate $xyz
List<Variable> list = new ArrayList<Variable>();
for (Variable t : s.ordered) if (t.hasAttribute("temporary") && bed.xyz.dependsOn(t) != null)
list.add(t);
list.add(bed.xyz);
// evaluate in $live phase, because endpoints already exist when connection is evaluated.
s.simplify("$live", list, bed.xyz);
if (T.equals("int"))
EquationSet.determineExponentsSimplified(list);
for (Variable v : list) {
multiconditional(v, context, " ");
}
}
result.append(" xyz = " + resolve(bed.xyz.reference, context, false) + ";\n");
result.append("}\n");
result.append("\n");
}
// Unit events
if (bed.eventTargets.size() > 0) {
result.append("bool " + ns + "eventTest (int i)\n");
result.append("{\n");
result.append(" switch (i)\n");
result.append(" {\n");
for (EventTarget et : bed.eventTargets) {
result.append(" case " + et.valueIndex + ":\n");
result.append(" {\n");
// Not safe or useful to simplify et.dependencies before emitting.
for (Variable v : et.dependencies) {
multiconditional(v, context, " ");
}
if (et.edge != EventTarget.NONZERO) {
result.append(" " + T + " before = ");
if (et.trackOne)
result.append(resolve(et.track.reference, context, false));
else
result.append(mangle(et.track.name));
result.append(";\n");
}
if (// This is a single variable, so check its value directly.
et.trackOne) {
result.append(" " + T + " after = " + resolve(et.track.reference, context, true) + ";\n");
} else // This is an expression, so use our private auxiliary variable.
{
result.append(" " + T + " after = ");
et.event.operands[0].render(context);
result.append(";\n");
if (et.edge != EventTarget.NONZERO) {
result.append(" " + mangle(et.track.name) + " = after;\n");
}
}
switch(et.edge) {
case EventTarget.NONZERO:
if (et.timeIndex >= 0) {
// Guard against multiple events in a given cycle.
// Note that other trigger types don't need this because they set the auxiliary variable,
// so the next test in the same cycle will no longer see change.
result.append(" if (after == 0) return false;\n");
if (T.equals("int")) {
// No need for modulo arithmetic. Rather, int time should be wrapped elsewhere.
result.append(" " + T + " moduloTime = Simulator<" + T + ">::instance.currentEvent->t;\n");
} else // float, double
{
// Wrap time at 1 second, to fit in float precision.
result.append(" " + T + " moduloTime = (" + T + ") fmod (Simulator<" + T + ">::instance.currentEvent->t, 1);\n");
}
result.append(" if (eventTime" + et.timeIndex + " == moduloTime) return false;\n");
result.append(" eventTime" + et.timeIndex + " = moduloTime;\n");
result.append(" return true;\n");
} else {
result.append(" return after != 0;\n");
}
break;
case EventTarget.CHANGE:
result.append(" return before != after;\n");
break;
case EventTarget.FALL:
result.append(" return before != 0 && after == 0;\n");
break;
case EventTarget.RISE:
default:
result.append(" return before == 0 && after != 0;\n");
}
result.append(" }\n");
}
result.append(" }\n");
result.append(" return false;\n");
result.append("}\n");
result.append("\n");
if (bed.needLocalEventDelay) {
result.append(T + " " + ns + "eventDelay (int i)\n");
result.append("{\n");
result.append(" switch (i)\n");
result.append(" {\n");
for (EventTarget et : bed.eventTargets) {
if (et.delay >= -1)
continue;
// Need to evaluate expression
result.append(" case " + et.valueIndex + ":\n");
result.append(" {\n");
for (Variable v : et.dependencies) {
multiconditional(v, context, " ");
}
result.append(" " + T + " result = ");
et.event.operands[1].render(context);
result.append(";\n");
result.append(" if (result < 0) return -1;\n");
result.append(" return result;\n");
result.append(" }\n");
}
result.append(" }\n");
result.append(" return -1;\n");
result.append("}\n");
result.append("\n");
}
result.append("void " + ns + "setLatch (int i)\n");
result.append("{\n");
result.append(" flags |= (" + bed.localFlagType + ") 0x1 << i;\n");
result.append("}\n");
result.append("\n");
if (bed.eventReferences.size() > 0) {
result.append("void " + ns + "finalizeEvent ()\n");
result.append("{\n");
for (Variable v : bed.eventReferences) {
String current = resolve(v.reference, context, false);
String buffered = resolve(v.reference, context, true);
result.append(" " + current);
switch(v.assignment) {
case Variable.ADD:
result.append(" += " + buffered + ";\n");
result.append(" " + zero(buffered, v) + ";\n");
break;
case Variable.MULTIPLY:
case Variable.DIVIDE:
{
// The current and buffered values of the variable have the same exponent.
// raw = exponentV + exponentV - MSB
// shift = raw - exponentV = exponentV - MSB
int shift = v.exponent - Operator.MSB;
if (shift != 0 && T.equals("int")) {
result.append(" = (int64_t) " + current + " * " + buffered + context.printShift(shift) + ";\n");
} else {
result.append(" *= " + buffered + ";\n");
}
result.append(" " + clear(buffered, v, 1, context) + ";\n");
break;
}
case Variable.MIN:
// TODO: Write elementwise min() and max() for matrices.
result.append(" = min (" + current + ", " + buffered + ");\n");
result.append(" " + clear(buffered, v, Double.POSITIVE_INFINITY, context) + ";\n");
break;
case Variable.MAX:
result.append(" = max (" + current + ", " + buffered + ");\n");
result.append(" " + clear(buffered, v, Double.NEGATIVE_INFINITY, context) + ";\n");
break;
default:
// REPLACE
result.append(" = " + buffered + ";\n");
break;
}
}
result.append("}\n");
result.append("\n");
}
}
// Unit path
if (bed.needLocalPath) {
result.append("void " + ns + "path (String & result)\n");
result.append("{\n");
if (// Not a connection, or a unary connection
s.connectionBindings == null || s.connectionBindings.size() == 1) {
// We assume that result is passed in as the empty string.
if (s.container != null) {
if (// Will our container provide a non-empty path?
((BackendDataC) s.container.backendData).needLocalPath) {
result.append(" container->path (result);\n");
result.append(" result += \"." + s.name + "\";\n");
} else {
result.append(" result = \"" + s.name + "\";\n");
}
}
if (bed.index != null) {
result.append(" result += __24index;\n");
} else if (s.connectionBindings != null) {
ConnectionBinding c = s.connectionBindings.get(0);
BackendDataC cbed = (BackendDataC) c.endpoint.backendData;
if (cbed.index != null)
result.append(" result += " + mangle(c.alias) + "->__24index;\n");
}
} else // binary or higher connection
{
boolean first = true;
boolean temp = false;
for (ConnectionBinding c : s.connectionBindings) {
if (first) {
result.append(" " + mangle(c.alias) + "->path (result);\n");
first = false;
} else {
if (!temp) {
result.append(" String temp;\n");
temp = true;
}
result.append(" " + mangle(c.alias) + "->path (temp);\n");
result.append(" result += \"-\";\n");
result.append(" result += temp;\n");
}
}
}
result.append("}\n");
result.append("\n");
}
// Unit conversions
Set<Conversion> conversions = s.getConversions();
for (Conversion pair : conversions) {
EquationSet source = pair.from;
EquationSet dest = pair.to;
boolean connectionSource = source.connectionBindings != null;
boolean connectionDest = dest.connectionBindings != null;
if (connectionSource != connectionDest) {
Backend.err.get().println("Can't change $type between connection and non-connection.");
throw new Backend.AbortRun();
// Why not? Because a connection *must* know the instances it connects, while
// a compartment cannot know those instances. Thus, one can never be converted
// to the other.
}
// The "2" functions only have local meaning, so they are never virtual.
// Must do everything init() normally does, including increment $n.
// Parameters:
// from -- the source part
// visitor -- the one managing the source part
// $type -- The integer index, in the $type expression, of the current target part. The target part's $type field will be initialized with this number (and zeroed after one cycle).
result.append("void " + ns + mangle(source.name) + "_2_" + mangle(dest.name) + " (" + mangle(source.name) + " * from, int " + mangle("$type") + ")\n");
result.append("{\n");
// if this is a recycled part, then clear() is called
result.append(" " + mangle(dest.name) + " * to = " + mangle(dest.name) + ".allocate ();\n");
if (connectionDest) {
// Match connection bindings
for (ConnectionBinding c : dest.connectionBindings) {
ConnectionBinding d = source.findConnection(c.alias);
if (d == null) {
Backend.err.get().println("Unfulfilled connection binding during $type change.");
throw new Backend.AbortRun();
}
result.append(" to->" + mangle(c.alias) + " = from->" + mangle(c.alias) + ";\n");
}
}
// TODO: Convert contained populations from matching populations in the source part?
result.append(" to->enterSimulation ();\n");
result.append(" getEvent ()->enqueue (to);\n");
// Match variables between the two sets.
// TODO: a match between variables should be marked as a dependency. This might change some "dummy" variables into stored values.
String[] forbiddenAttributes = new String[] { "global", "constant", "accessor", "reference", "temporary", "dummy", "preexistent" };
for (Variable v : dest.variables) {
if (v.name.equals("$type")) {
// initialize new part with its position in the $type split
result.append(" to->" + mangle(v) + " = " + mangle("$type") + ";\n");
continue;
}
if (v.hasAny(forbiddenAttributes))
continue;
Variable v2 = source.find(v);
if (v2 != null) {
result.append(" to->" + mangle(v) + " = " + resolve(v2.reference, context, false, "from->", false) + ";\n");
}
}
// Unless the user qualifies code with $type, the values just copied above will simply be overwritten.
result.append(" to->init ();\n");
result.append("}\n");
result.append("\n");
}
}
use of gov.sandia.n2a.eqset.VariableReference in project n2a by frothga.
the class JobC method findLiveReferences.
@SuppressWarnings("unchecked")
public void findLiveReferences(EquationSet s, ArrayList<Object> resolution, NavigableSet<EquationSet> touched, List<VariableReference> localReference, boolean terminate) {
if (terminate) {
Variable live = s.find(new Variable("$live"));
if (live == null || live.hasAttribute("constant"))
return;
if (live.hasAttribute("initOnly")) {
if (touched.add(s)) {
VariableReference result = new VariableReference();
result.variable = live;
result.resolution = (ArrayList<Object>) resolution.clone();
localReference.add(result);
s.referenced = true;
}
return;
}
// The third possibility is "accessor", in which case we fall through ...
}
// Recurse up to container
if (s.lethalContainer) {
resolution.add(s.container);
findLiveReferences(s.container, resolution, touched, localReference, true);
resolution.remove(resolution.size() - 1);
}
// Recurse into connections
if (s.lethalConnection) {
for (ConnectionBinding c : s.connectionBindings) {
resolution.add(c);
findLiveReferences(c.endpoint, resolution, touched, localReference, true);
resolution.remove(resolution.size() - 1);
}
}
}
use of gov.sandia.n2a.eqset.VariableReference in project n2a by frothga.
the class ExportJob method makeExecutable.
/**
* Make eqset minimally executable.
*/
public static void makeExecutable(EquationSet equations, boolean findConstants) {
// This name should be unique enough that we don't have to check.
EquationSet fakePart = new EquationSet(equations, "N2A_fakePart");
// Always added, even if we don't need it.
equations.parts.add(fakePart);
fakeConnectionTarget(equations);
try {
equations.resolveConnectionBindings();
}// Still try to finish rest of compilation. Maybe only one or two minor parts were affected.
catch (Exception e) {
}
try {
equations.addGlobalConstants();
// $connect, $index, $init, $n, $t, $t', $type
equations.addSpecials();
equations.resolveLHS();
equations.fillIntegratedVariables();
equations.findIntegrated();
LinkedList<UnresolvedVariable> unresolved = new LinkedList<UnresolvedVariable>();
equations.resolveRHS(unresolved);
if (// Make one attempt to fake the variables
unresolved.size() > 0) {
for (UnresolvedVariable uv : unresolved) {
if (!uv.name.startsWith("A.") && !uv.name.startsWith("B."))
continue;
String name = uv.name.substring(2);
Variable v = Variable.from(name + "=0");
if (fakePart.add(v)) {
v.reference = new VariableReference();
v.reference.variable = v;
}
}
// Creates excess dependency counts on connection bindings, but is otherwise OK to run again.
equations.resolveRHS();
}
equations.findExternal();
equations.sortParts();
equations.determineUnits();
// This can hurt the analysis. It simplifies expressions and substitutes constants, breaking some dependency chains.
if (findConstants)
equations.findConstants();
equations.determineTraceVariableName();
equations.determineTypes();
equations.clearVariables();
}// It may still be possible to complete the export.
catch (Exception e) {
e.printStackTrace();
}
}
use of gov.sandia.n2a.eqset.VariableReference in project n2a by frothga.
the class InternalBackendData method analyze.
public void analyze(final EquationSet s) {
boolean headless = AppData.properties.getBoolean("headless");
if (!headless)
System.out.println(s.name);
if (s.connectionBindings != null) {
// Note that populations have already been allocated in the constructor.
endpoints = countLocalObject;
countLocalObject += s.connectionBindings.size();
}
fastExit = s.metadata.getFlag("backend", "all", "fastExit");
for (// we want the sub-lists to be ordered correctly
Variable v : // we want the sub-lists to be ordered correctly
s.ordered) {
if (!headless) {
String className = "null";
if (v.type != null)
className = v.type.getClass().getSimpleName();
String dimensionName = "";
if (v.unit != null)
dimensionName = v.unit.toString();
System.out.println(" " + v.nameString() + " " + v.attributeString() + " " + className + " " + dimensionName);
}
if (v.name.equals("$connect"))
connect = v;
else if (v.name.equals("$index"))
index = v;
else if (v.name.equals("$init"))
init = v;
else if (v.name.equals("$live"))
live = v;
else if (v.name.equals("$n") && v.order == 0)
n = v;
else if (v.name.equals("$p") && v.order == 0)
p = v;
else if (v.name.equals("$type"))
type = v;
else if (v.name.equals("$xyz") && v.order == 0)
xyz = v;
else if (v.name.equals("$t")) {
if (v.order == 0)
t = v;
else if (v.order == 1)
dt = v;
}
boolean initOnly = v.hasAttribute("initOnly");
boolean emptyCombiner = v.isEmptyCombiner();
boolean updates = !initOnly && v.equations.size() > 0 && !emptyCombiner && (v.derivative == null || v.hasAttribute("updates"));
boolean temporary = v.hasAttribute("temporary");
boolean unusedTemporary = temporary && !v.hasUsers();
if (v.hasAttribute("externalWrite"))
v.externalWrite = true;
if (v.hasAttribute("global")) {
v.global = true;
v.visit(new Visitor() {
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
if (av.reference.resolution.size() > 0)
addReferenceGlobal(av.reference, s);
return false;
}
if (op instanceof Output) {
Output o = (Output) op;
if (!o.hasColumnName) {
o.index = countGlobalObject++;
namesGlobalObject.add("columnName" + o.index);
}
// Continue descent, because parameters of output() may contain variable references
return true;
}
return true;
}
});
if (// eliminate non-computed values, unless they refer to a variable outside the immediate equation set
!v.hasAny(new String[] { "constant", "accessor", "readOnly" }) || v.hasAll(new String[] { "constant", "reference" })) {
if (updates)
globalUpdate.add(v);
if (!unusedTemporary && !emptyCombiner)
globalInit.add(v);
if (v.hasAttribute("reference")) {
addReferenceGlobal(v.reference, s);
} else if (!temporary && !v.hasAttribute("dummy")) {
if (!v.hasAttribute("preexistent"))
globalMembers.add(v);
boolean external = false;
if (v.externalWrite || v.assignment != Variable.REPLACE) {
external = true;
globalBufferedExternalWrite.add(v);
}
if (external || (v.hasAttribute("externalRead") && updates)) {
external = true;
globalBufferedExternal.add(v);
}
if (!external && v.hasAttribute("cycle")) {
globalBufferedInternal.add(v);
if (!initOnly)
globalBufferedInternalUpdate.add(v);
}
}
}
} else // local
{
v.visit(new Visitor() {
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
if (av.reference.resolution.size() > 0)
addReferenceLocal(av.reference, s);
return false;
}
if (op instanceof Output) {
Output o = (Output) op;
if (!o.hasColumnName) {
o.index = countLocalObject++;
namesLocalObject.add("columnName" + o.index);
}
// Continue descent, because parameters of output() may contain variable references
return true;
}
return true;
}
});
if (!v.hasAny(new String[] { "constant", "accessor", "readOnly" }) || v.hasAll(new String[] { "constant", "reference" })) {
if (updates)
localUpdate.add(v);
if (!unusedTemporary && !emptyCombiner && !forbiddenLocalInit.contains(v.name))
localInit.add(v);
if (v.hasAttribute("reference")) {
addReferenceLocal(v.reference, s);
} else if (!temporary && !v.hasAttribute("dummy")) {
if (!v.hasAttribute("preexistent"))
localMembers.add(v);
boolean external = false;
if (v.externalWrite || v.assignment != Variable.REPLACE) {
external = true;
localBufferedExternalWrite.add(v);
}
if (external || (v.hasAttribute("externalRead") && updates)) {
external = true;
localBufferedExternal.add(v);
}
if (!external && v.hasAttribute("cycle")) {
localBufferedInternal.add(v);
if (!initOnly)
localBufferedInternalUpdate.add(v);
}
}
}
}
}
for (// we need these to be in order by differential level, not by dependency
Variable v : // we need these to be in order by differential level, not by dependency
s.variables) {
if (v.derivative != null && !v.hasAny(new String[] { "constant", "initOnly" })) {
if (v.hasAttribute("global"))
globalIntegrated.add(v);
else
localIntegrated.add(v);
}
}
if (dt != null && dt.hasAttribute("constant")) {
setDt = true;
// However, if the nearest container that defines $t' matches our value, then don't set $t'.
if (s.container != null) {
Variable pdt = s.container.findDt();
if (pdt != null && pdt.hasAttribute("constant")) {
double value = dt.equations.first().expression.getDouble();
double pvalue = pdt.equations.first().expression.getDouble();
setDt = value != pvalue;
}
}
}
determineOrderInit("$init", s, localInit);
determineOrderInit("$init", s, globalInit);
singleton = s.isSingleton(true);
populationCanGrowOrDie = s.lethalP || s.lethalType || s.canGrow();
if (n != null && !singleton) {
populationCanResize = globalMembers.contains(n);
// See EquationSet.forceTemporaryStorageForSpecials() for a related issue.
if (!populationCanResize && populationCanGrowOrDie && n.hasUsers()) {
Backend.err.get().println("WARNING: $n can change (due to structural dynamics) but it was detected as a constant. Equations that depend on $n may give incorrect results.");
}
}
if (index != null && !singleton) {
indexNext = allocateGlobalFloat("indexNext");
indexAvailable = allocateGlobalObject("indexAvailable");
}
if (// track instances
singleton || s.connected || s.needInstanceTracking || populationCanResize) {
// The reason populationCanResize forces use of the instances array is to enable pruning of parts when $n decreases.
// The reason to "track instances" for a singleton is to allocate a slot for direct storage of the single instance in valuesObject.
instances = allocateGlobalObject("instances");
if (// in addition, track newly created instances
s.connected) {
if (!singleton)
firstborn = allocateGlobalFloat("firstborn");
newborn = allocateLocalFloat("newborn");
}
}
// Just give name of connection part itself.
if (s.connectionBindings != null) {
singleConnection = true;
for (ConnectionBinding cb : s.connectionBindings) {
if (cb.endpoint.container != s.container || !cb.endpoint.isSingleton(true)) {
singleConnection = false;
break;
}
}
}
if (p != null) {
Pdependencies = new ArrayList<Variable>();
PdependenciesTemp = new ArrayList<Variable>();
for (Variable t : s.ordered) {
boolean temporary = t.hasAttribute("temporary");
if ((temporary || localMembers.contains(t)) && p.dependsOn(t) != null) {
Pdependencies.add(t);
if (temporary)
PdependenciesTemp.add(t);
}
}
determineOrderInit("$connect", s, Pdependencies);
// determineOrderInit() is not needed for PdepenciesTemp, because temps are already in the correct order.
// Default is no polling
String pollString = "-1";
if (p.metadata != null)
pollString = p.metadata.getOrDefault(pollString, "poll");
poll = new UnitValue(pollString).get();
if (poll >= 0) {
pollDeadline = allocateGlobalFloat("pollDeadline");
pollSorted = allocateGlobalObject("pollSorted");
}
}
if (type != null) {
for (EquationEntry e : type.equations) {
Split split = (Split) e.expression;
split.index = type.reference.variable.container.splits.indexOf(split.parts);
}
}
if (xyz != null) {
XYZdependencies = new ArrayList<Variable>();
XYZdependenciesTemp = new ArrayList<Variable>();
for (Variable t : s.ordered) {
boolean temporary = t.hasAttribute("temporary");
if ((temporary || localMembers.contains(t)) && xyz.dependsOn(t) != null) {
XYZdependencies.add(t);
if (temporary)
XYZdependenciesTemp.add(t);
}
}
}
populationIndex = 0;
if (// check for null specifically to guard against the Wrapper equation set (which is not fully constructed)
s.container != null && s.container.parts != null) {
populationIndex = s.container.parts.indexOf(s);
}
if (// connection-specific stuff
s.connectionBindings != null) {
int size = s.connectionBindings.size();
// endpoints is allocated at the top of this function, because it is needed for reference handling in the variable analysis loop
projectDependencies = new Object[size];
projectReferences = new Object[size];
count = new int[size];
k = new Variable[size];
max = new Variable[size];
min = new Variable[size];
project = new Variable[size];
radius = new Variable[size];
for (int i = 0; i < s.connectionBindings.size(); i++) {
ConnectionBinding c = s.connectionBindings.get(i);
count[i] = -1;
k[i] = s.find(new Variable(c.alias + ".$k"));
max[i] = s.find(new Variable(c.alias + ".$max"));
min[i] = s.find(new Variable(c.alias + ".$min"));
project[i] = s.find(new Variable(c.alias + ".$project"));
radius[i] = s.find(new Variable(c.alias + ".$radius"));
if (c.endpoint.accountableConnections != null) {
AccountableConnection query = new AccountableConnection(s, c.alias);
AccountableConnection ac = c.endpoint.accountableConnections.floor(query);
if (// Only true if this endpoint is accountable.
ac.equals(query)) {
// Allocate space for counter in target part
InternalBackendData endpointBed = (InternalBackendData) c.endpoint.backendData;
count[i] = endpointBed.allocateLocalFloat(s.prefix() + ".$count");
if (// $count is referenced explicitly, so need to finish setting it up
ac.count != null) {
ac.count.readIndex = ac.count.writeIndex = count[i];
}
}
}
// Note that countLocalObject has already been incremented above
namesLocalObject.add(c.alias);
if (project[i] != null) {
ArrayList<Variable> dependencies = new ArrayList<Variable>();
// Always assign, even if empty.
projectDependencies[i] = dependencies;
for (Variable t : s.ordered) {
if (project[i].dependsOn(t) != null) {
dependencies.add(t);
}
}
final TreeSet<VariableReference> references = new TreeSet<VariableReference>();
class ProjectVisitor implements Visitor {
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
if (av.reference.resolution.size() > 0)
references.add(av.reference);
return false;
}
return true;
}
}
ProjectVisitor visitor = new ProjectVisitor();
project[i].visit(visitor);
for (Variable v : dependencies) v.visit(visitor);
if (references.size() > 0)
projectReferences[i] = references;
}
c.resolution = translateResolution(c.resolution, s);
}
}
// Locals
for (Variable v : localMembers) {
// in the object array rather than the float array.
if (v.type instanceof Scalar && v.reference.variable == v) {
v.readIndex = v.writeIndex = allocateLocalFloat(v.nameString());
} else {
v.readIndex = v.writeIndex = allocateLocalObject(v.nameString());
}
}
for (Variable v : localBufferedExternal) {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.writeIndex = allocateLocalFloat("next_" + v.nameString());
} else {
v.writeIndex = allocateLocalObject("next_" + v.nameString());
}
}
for (Variable v : localBufferedInternal) {
v.writeTemp = true;
if (v.type instanceof Scalar && v.reference.variable == v) {
v.writeIndex = allocateLocalTempFloat("next_" + v.nameString());
} else {
v.writeIndex = allocateLocalTempObject("next_" + v.nameString());
}
}
// Globals
for (Variable v : globalMembers) {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.readIndex = v.writeIndex = allocateGlobalFloat(v.nameString());
} else {
v.readIndex = v.writeIndex = allocateGlobalObject(v.nameString());
}
}
for (Variable v : globalBufferedExternal) {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.writeIndex = allocateGlobalFloat("next_" + v.nameString());
} else {
v.writeIndex = allocateGlobalObject("next_" + v.nameString());
}
}
for (Variable v : globalBufferedInternal) {
v.writeTemp = true;
if (v.type instanceof Scalar && v.reference.variable == v) {
v.writeIndex = allocateGlobalTempFloat("next_" + v.nameString());
} else {
v.writeIndex = allocateGlobalTempObject("next_" + v.nameString());
}
}
// fully temporary values
for (Variable v : s.variables) {
if (!v.hasAttribute("temporary"))
continue;
v.readTemp = v.writeTemp = true;
if (v.hasAttribute("global")) {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.readIndex = v.writeIndex = allocateGlobalTempFloat(v.nameString());
} else {
v.readIndex = v.writeIndex = allocateGlobalTempObject(v.nameString());
}
} else {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.readIndex = v.writeIndex = allocateLocalTempFloat(v.nameString());
} else {
v.readIndex = v.writeIndex = allocateLocalTempObject(v.nameString());
}
}
}
if (live.hasAttribute("constant"))
liveStorage = LIVE_CONSTANT;
else if (live.hasAttribute("accessor"))
liveStorage = LIVE_ACCESSOR;
else
// $live is "initOnly"
liveStorage = LIVE_STORED;
for (VariableReference r : localReference) r.resolution = translateResolution(r.resolution, s);
for (VariableReference r : globalReference) r.resolution = translateResolution(r.resolution, s);
}
Aggregations