use of gov.sandia.n2a.language.Type in project n2a by frothga.
the class JobC method generateStatic.
public void generateStatic(final EquationSet s, final StringBuilder result) {
for (EquationSet p : s.parts) generateStatic(p, result);
// Generate static definitions
final BackendDataC bed = (BackendDataC) s.backendData;
class CheckStatic extends Visitor {
public boolean global;
public boolean visit(Operator op) {
if (op instanceof Constant) {
Type m = ((Constant) op).value;
if (m instanceof Matrix) {
Matrix A = (Matrix) m;
int rows = A.rows();
int cols = A.columns();
String matrixName = "Matrix" + matrixNames.size();
matrixNames.put(op, matrixName);
if (rows == 3 && cols == 1)
result.append("Vector3 " + matrixName + " = Matrix<float>");
else
result.append("Matrix<float> " + matrixName);
result.append(" (\"" + A + "\");\n");
}
// Don't try to descend tree from here
return false;
}
if (op instanceof Function) {
Function f = (Function) op;
if (// We need to auto-generate the column name.
f instanceof Output && f.operands.length < 3) {
String stringName = "columnName" + stringNames.size();
stringNames.put(op, stringName);
if (global) {
bed.setGlobalNeedPath(s);
bed.globalColumns.add(stringName);
} else {
bed.setLocalNeedPath(s);
bed.localColumns.add(stringName);
}
}
// Detect functions that need static handles
if (f.operands.length > 0) {
Operator operand0 = f.operands[0];
if (operand0 instanceof Constant) {
Constant c = (Constant) operand0;
Type o = c.value;
if (o instanceof Text) {
String fileName = ((Text) o).value;
if (op instanceof ReadMatrix) {
if (!matrixNames.containsKey(fileName)) {
String matrixName = "Matrix" + matrixNames.size();
matrixNames.put(fileName, matrixName);
result.append("MatrixInput * " + matrixName + " = matrixHelper (\"" + fileName + "\");\n");
}
} else if (f instanceof Input) {
if (!inputNames.containsKey(fileName)) {
String inputName = "Input" + inputNames.size();
inputNames.put(fileName, inputName);
result.append("InputHolder * " + inputName + " = inputHelper (\"" + fileName + "\");\n");
}
} else if (f instanceof Output) {
if (!outputNames.containsKey(fileName)) {
String outputName = "Output" + outputNames.size();
outputNames.put(fileName, outputName);
result.append("OutputHolder * " + outputName + " = outputHelper (\"" + fileName + "\");\n");
}
}
}
} else // Dynamic file name (no static handle)
{
if (f instanceof ReadMatrix) {
matrixNames.put(op, "Matrix" + matrixNames.size());
stringNames.put(operand0, "fileName" + stringNames.size());
} else if (f instanceof Input) {
inputNames.put(op, "Input" + inputNames.size());
stringNames.put(operand0, "fileName" + stringNames.size());
} else if (f instanceof Output) {
outputNames.put(op, "Output" + outputNames.size());
stringNames.put(operand0, "fileName" + stringNames.size());
}
}
}
// Functions could be nested, so continue descent.
return true;
}
return true;
}
}
CheckStatic checkStatic = new CheckStatic();
for (Variable v : s.ordered) {
checkStatic.global = v.hasAttribute("global");
v.visit(checkStatic);
}
}
use of gov.sandia.n2a.language.Type 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.language.Type in project n2a by frothga.
the class Part method finish.
public boolean finish(Simulator simulator) {
InternalBackendData bed = (InternalBackendData) equations.backendData;
int populations = equations.parts.size();
for (int i = 0; i < populations; i++) ((Population) valuesObject[i]).finish(simulator);
if (bed.liveStorage == InternalBackendData.LIVE_STORED) {
// early-out if we are already dead, to avoid another call to die()
if (((Scalar) get(bed.live)).value == 0)
return false;
}
// Events
for (EventSource es : bed.eventSources) {
@SuppressWarnings("unchecked") List<Instance> monitors = (ArrayList<Instance>) valuesObject[es.monitorIndex];
if (monitors.size() == 0)
continue;
EventTarget eventType = es.target;
if (es.testEach) {
for (Instance i : monitors) {
if (i == null)
continue;
double delay = eventType.test(i, simulator);
// the trigger condition was not satisfied
if (delay < -1)
continue;
EventSpikeSingle spike;
if (// event was triggered, but timing is no-care
delay < 0) {
spike = new EventSpikeSingleLatch();
// queue immediately after current cycle, so latches get set for next full cycle
spike.t = simulator.currentEvent.t;
} else if (// process as close to current cycle as possible
delay == 0) {
// fully execute the event (not latch it)
spike = new EventSpikeSingle();
// queue immediately
spike.t = simulator.currentEvent.t;
} else {
// Is delay an quantum number of $t' steps?
double ratio = delay / event.dt;
int step = (int) Math.round(ratio);
if (Math.abs(ratio - step) < 1e-3) {
if (simulator.eventMode == Simulator.DURING)
spike = new EventSpikeSingleLatch();
else
spike = new EventSpikeSingle();
if (simulator.eventMode == Simulator.AFTER)
delay = (step + 1e-6) * event.dt;
else
delay = (step - 1e-6) * event.dt;
} else {
spike = new EventSpikeSingle();
}
spike.t = simulator.currentEvent.t + delay;
}
spike.eventType = eventType;
spike.target = i;
simulator.queueEvent.add(spike);
}
} else // All monitors share same condition, so only test one.
{
double delay = -2;
for (Instance i : monitors) {
if (i == null)
continue;
delay = eventType.test(i, simulator);
break;
}
// the trigger condition was not satisfied
if (delay < -1)
continue;
if (// Each target instance may require a different delay.
es.delayEach) {
for (Instance i : monitors) {
if (i == null)
continue;
// This results in one redundant eval, of first entry in monitors. Not clear if it's worth the work to avoid this.
delay = eventType.delay(i, simulator);
EventSpikeSingle spike;
if (delay < 0) {
spike = new EventSpikeSingleLatch();
spike.t = simulator.currentEvent.t;
} else if (delay == 0) {
spike = new EventSpikeSingle();
spike.t = simulator.currentEvent.t;
} else {
double ratio = delay / event.dt;
int step = (int) Math.round(ratio);
if (Math.abs(ratio - step) < 1e-3) {
if (simulator.eventMode == Simulator.DURING)
spike = new EventSpikeSingleLatch();
else
spike = new EventSpikeSingle();
if (simulator.eventMode == Simulator.AFTER)
delay = (step + 1e-6) * event.dt;
else
delay = (step - 1e-6) * event.dt;
} else {
spike = new EventSpikeSingle();
}
spike.t = simulator.currentEvent.t + delay;
}
spike.eventType = eventType;
spike.target = i;
simulator.queueEvent.add(spike);
}
} else // All delays are the same.
{
EventSpikeMulti spike;
if (delay < 0) {
spike = new EventSpikeMultiLatch();
spike.t = simulator.currentEvent.t;
} else if (delay == 0) {
spike = new EventSpikeMulti();
spike.t = simulator.currentEvent.t;
} else {
double ratio = delay / event.dt;
int step = (int) Math.round(ratio);
if (Math.abs(ratio - step) < 1e-3) {
if (simulator.eventMode == Simulator.DURING)
spike = new EventSpikeMultiLatch();
else
spike = new EventSpikeMulti();
if (simulator.eventMode == Simulator.AFTER)
delay = (step + 1e-6) * event.dt;
else
delay = (step - 1e-6) * event.dt;
} else {
spike = new EventSpikeMulti();
}
spike.t = simulator.currentEvent.t + delay;
}
spike.eventType = eventType;
// We don't copy the array, just keep a reference to it. What could go wrong with this?
// If a part dies and tries to remove itself from the list while it is being used to deliver spikes,
// then we could get a null pointer exception. Solution is to synchronize access to the list.
// If a connection is born while the spike is in flight, one could argue that it shouldn't
// receive it, but one could also argue that it should. In nature these two things (spikes
// and synapse creation) occur at vastly different timescales. Wouldn't a nascent synapse
// receive spikes even as it is forming?
spike.targets = monitors;
simulator.queueEvent.add(spike);
}
}
}
// Other stuff
if (bed.lastT != null)
setFinal(bed.lastT, new Scalar(simulator.currentEvent.t));
for (Variable v : bed.localBufferedExternal) setFinal(v, getFinal(v));
for (Integer i : bed.eventLatches) valuesFloat[i] = 0;
for (Variable v : bed.localBufferedExternalWrite) {
switch(v.assignment) {
case Variable.ADD:
// initial value is zero-equivalent (additive identity)
set(v, v.type);
break;
case Variable.MULTIPLY:
case Variable.DIVIDE:
// multiplicative identity
if (v.type instanceof Matrix)
set(v, ((Matrix) v.type).identity());
else
set(v, new Scalar(1));
break;
case Variable.MIN:
if (v.type instanceof Matrix)
set(v, ((Matrix) v.type).clear(Double.POSITIVE_INFINITY));
else
set(v, new Scalar(Double.POSITIVE_INFINITY));
break;
case Variable.MAX:
if (v.type instanceof Matrix)
set(v, ((Matrix) v.type).clear(Double.NEGATIVE_INFINITY));
else
set(v, new Scalar(Double.NEGATIVE_INFINITY));
break;
}
}
if (bed.type != null) {
int type = (int) ((Scalar) get(bed.type)).value;
if (type > 0) {
ArrayList<EquationSet> split = equations.splits.get(type - 1);
if (// Make sure $type != me. Otherwise it's a null operation
split.size() > 1 || split.get(0) != equations) {
// indicates that this instance is one of the resulting parts
boolean used = false;
int countParts = split.size();
for (int i = 0; i < countParts; i++) {
EquationSet other = split.get(i);
Scalar splitPosition = new Scalar(i + 1);
if (other == equations && !used) {
used = true;
setFinal(bed.type, splitPosition);
} else {
InternalBackendData otherBed = (InternalBackendData) other.backendData;
Part p = new Part(other, (Part) container);
// If this is a connection, keep the same bindings
Conversion conversion = bed.conversions.get(other);
if (conversion.bindings != null) {
for (int j = 0; j < conversion.bindings.length; j++) {
p.valuesObject[otherBed.endpoints + conversion.bindings[j]] = valuesObject[bed.endpoints + j];
}
}
event.enqueue(p);
p.resolve();
// accountable connections are updated here
p.init(simulator);
// Copy over variables
int count = conversion.from.size();
for (int v = 0; v < count; v++) {
Variable from = conversion.from.get(v);
Variable to = conversion.to.get(v);
p.setFinal(to, get(from));
}
// Set $type to be our position in the split
p.setFinal(otherBed.type, splitPosition);
}
}
if (!used) {
die();
return false;
}
}
}
}
if (equations.lethalP) {
double p;
if (bed.p.hasAttribute("temporary")) {
InstanceTemporaries temp = new InstanceTemporaries(this, simulator, false);
for (Variable v : bed.Pdependencies) {
Type result = v.eval(temp);
if (result != null && v.writeIndex >= 0)
temp.set(v, result);
}
Type result = bed.p.eval(temp);
if (result == null)
p = 1;
else
p = ((Scalar) result).value;
} else {
p = ((Scalar) get(bed.p)).value;
}
if (p == 0 || p < 1 && p < simulator.random.nextDouble()) {
die();
return false;
}
}
if (equations.lethalConnection) {
int count = equations.connectionBindings.size();
for (int i = 0; i < count; i++) {
if (!getPart(i).getLive()) {
die();
return false;
}
}
}
if (equations.lethalContainer) {
if (!((Part) container).getLive()) {
die();
return false;
}
}
return true;
}
use of gov.sandia.n2a.language.Type in project n2a by frothga.
the class Part method getP.
public double getP(Simulator simulator) {
InstancePreLive temp = new InstancePreLive(this, simulator);
// N2A language defines default to be 1 (always create)
if (temp.bed.p == null)
return 1;
for (Variable v : temp.bed.Pdependencies) {
Type result = v.eval(temp);
if (result != null && v.writeIndex >= 0)
temp.set(v, result);
}
Type result = temp.bed.p.eval(temp);
if (result == null)
return 1;
return ((Scalar) result).value;
}
use of gov.sandia.n2a.language.Type in project n2a by frothga.
the class Gaussian method eval.
public Type eval(Instance context) throws EvaluationException {
Random random;
Simulator simulator = Simulator.getSimulator(context);
if (simulator == null)
random = new Random();
else
random = simulator.random;
if (operands.length == 0)
return new Scalar(random.nextGaussian());
Type sigma = operands[0].eval(context);
if (sigma instanceof Scalar) {
return new Scalar(random.nextGaussian() * ((Scalar) sigma).value);
} else if (sigma instanceof Matrix) {
Matrix scale = (Matrix) sigma;
int rows = scale.rows();
int columns = scale.columns();
if (columns == 1) {
Matrix result = new MatrixDense(rows, 1);
for (int i = 0; i < rows; i++) result.set(i, random.nextGaussian() * scale.get(i, 0));
return result;
} else if (rows == 1) {
Matrix result = new MatrixDense(columns, 1);
for (int i = 0; i < columns; i++) result.set(i, random.nextGaussian() * scale.get(0, i));
return result;
} else {
Matrix temp = new MatrixDense(columns, 1);
for (int i = 0; i < columns; i++) temp.set(i, random.nextGaussian());
return sigma.multiply(temp);
}
} else {
// We could throw an exception, but this is easy enough.
return new Scalar(random.nextGaussian());
}
}
Aggregations