Search in sources :

Example 1 with UnitValue

use of gov.sandia.n2a.language.UnitValue in project n2a by frothga.

the class NodeJob method monitorProgress.

public synchronized void monitorProgress() {
    if (deleted)
        return;
    if (complete >= 1 && complete != 3)
        return;
    // Limit monitoring to no more than once per second.
    long elapsed = System.currentTimeMillis() - lastMonitored;
    long wait = 1000 - elapsed;
    if (wait > 0) {
        try {
            Thread.sleep(wait);
        } catch (InterruptedException e) {
        }
    }
    lastMonitored = System.currentTimeMillis();
    float oldComplete = complete;
    MNode source = getSource();
    Host env = Host.get(source);
    Path localJobDir = Host.getJobDir(Host.getLocalResourceDir(), source);
    // If job is remote, attempt to grab its state files.
    // TODO: handle remote jobs waiting in queue. Plan is to update "started" file with queue status.
    Path finished = localJobDir.resolve("finished");
    if (!Files.exists(finished) && env instanceof Remote) {
        @SuppressWarnings("resource") Remote remote = (Remote) env;
        if (remote.isConnected() || remote.isEnabled()) {
            try {
                Path remoteJobDir = Host.getJobDir(env.getResourceDir(), source);
                Path remoteFinished = remoteJobDir.resolve("finished");
                // throws an exception if the remote file does not exist
                Files.copy(remoteFinished, finished);
            } catch (Exception e) {
            }
        }
    }
    if (complete == -1) {
        Path started = localJobDir.resolve("started");
        if (Files.exists(started)) {
            complete = 0;
            dateStarted = new Date(Host.lastModified(started));
            lastActive = dateStarted.getTime();
        }
    }
    Backend simulator = Backend.getBackend(source.get("backend"));
    if (complete >= 0 && complete < 1) {
        float percentDone = 0;
        if (expectedSimTime == 0)
            expectedSimTime = new UnitValue(source.get("duration")).get();
        if (expectedSimTime > 0)
            percentDone = (float) (simulator.currentSimTime(source) / expectedSimTime);
        if (Files.exists(finished)) {
            checkFinished(finished);
        } else {
            try {
                long currentTime = System.currentTimeMillis();
                if (simulator.isActive(source)) {
                    lastActive = currentTime;
                } else if (currentTime - lastActive > activeTimeout) {
                    if (percentDone < 1) {
                        // Give it up for dead.
                        Files.copy(new ByteArrayInputStream("dead".getBytes("UTF-8")), finished);
                        complete = 4;
                    } else // Job appears to be actually finished, even though "finished" hasn't been written yet.
                    {
                        // Fake the "finished" file. This might be overwritten later by the batch process.
                        // Most likely, it will also report that we succeeded, so presume that things are fine.
                        Files.copy(new ByteArrayInputStream("success".getBytes("UTF-8")), finished);
                        complete = 1;
                    }
                }
            } catch (Exception e) {
            }
        }
        if (complete >= 0 && complete < 1)
            complete = Math.min(0.99999f, percentDone);
    }
    if (complete == 3) {
        // Check if process is still lingering
        if (!simulator.isActive(source))
            complete = 4;
    }
    PanelRun panelRun = PanelRun.instance;
    PanelStudy panelStudy = PanelStudy.instance;
    // Probably running headless, so skip all UI updates.
    if (panelRun == null)
        return;
    if (complete != oldComplete) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                panelRun.model.nodeChanged(NodeJob.this);
                if (panelRun.displayNode == NodeJob.this) {
                    panelRun.buttonStop.setEnabled(complete < 1 || complete == 3);
                    panelRun.viewJob(true);
                } else if (panelRun.displayNode instanceof NodeFile && panelRun.displayNode.getParent() == NodeJob.this) {
                    panelRun.buttonStop.setEnabled(complete < 1 || complete == 3);
                    // Update the display every 5 seconds during the run.
                    // Some displays, such as a chart, could take longer than 5s to construct, so don't interrupt those.
                    // Always update the display when a run finishes.
                    long currentTime = System.currentTimeMillis();
                    if (complete >= 1 && complete != 3 || panelRun.displayThread == null && currentTime - lastDisplay > 5000) {
                        lastDisplay = currentTime;
                        panelRun.viewFile(true);
                    }
                }
                // panelStudy could be null for a brief moment during startup
                if (panelStudy != null)
                    panelStudy.tableSamples.updateJob(key);
            }
        });
    }
    if (!panelRun.tree.isCollapsed(new TreePath(getPath())))
        build(panelRun.tree);
}
Also used : Path(java.nio.file.Path) TreePath(javax.swing.tree.TreePath) Remote(gov.sandia.n2a.host.Remote) UnitValue(gov.sandia.n2a.language.UnitValue) Host(gov.sandia.n2a.host.Host) MNode(gov.sandia.n2a.db.MNode) IOException(java.io.IOException) Date(java.util.Date) PanelStudy(gov.sandia.n2a.ui.studies.PanelStudy) Backend(gov.sandia.n2a.plugins.extpoints.Backend) TreePath(javax.swing.tree.TreePath) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 2 with UnitValue

use of gov.sandia.n2a.language.UnitValue 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);
}
Also used : Operator(gov.sandia.n2a.language.Operator) AccessVariable(gov.sandia.n2a.language.AccessVariable) Variable(gov.sandia.n2a.eqset.Variable) Visitor(gov.sandia.n2a.language.Visitor) AccessVariable(gov.sandia.n2a.language.AccessVariable) AccountableConnection(gov.sandia.n2a.eqset.EquationSet.AccountableConnection) VariableReference(gov.sandia.n2a.eqset.VariableReference) ConnectionBinding(gov.sandia.n2a.eqset.EquationSet.ConnectionBinding) ArrayList(java.util.ArrayList) UnitValue(gov.sandia.n2a.language.UnitValue) Scalar(gov.sandia.n2a.language.type.Scalar) TreeSet(java.util.TreeSet) Output(gov.sandia.n2a.language.function.Output) EquationEntry(gov.sandia.n2a.eqset.EquationEntry) Split(gov.sandia.n2a.language.Split)

Example 3 with UnitValue

use of gov.sandia.n2a.language.UnitValue in project n2a by frothga.

the class EquationTreeCellEditor method getTreeCellEditorComponent.

public Component getTreeCellEditorComponent(JTree tree, Object value, boolean expanded, boolean leaf, boolean isTitle) {
    editingTree = tree;
    editingNode = (NodeBase) value;
    editingTitle = isTitle;
    offset = renderer.getTextOffset();
    Font fontBase = tree.getFont();
    Font fontPlain = editingNode.getPlainFont(fontBase);
    Font fontStyled = editingNode.getStyledFont(fontBase);
    FontMetrics fm = tree.getFontMetrics(fontStyled);
    iconHolder.setIcon(renderer.getIconFor(editingNode, expanded, leaf));
    String text;
    String param;
    boolean isSimpleVariable = editingNode instanceof NodeVariable && !((NodeVariable) editingNode).hasEquations();
    boolean isAnnotation = editingNode instanceof NodeAnnotation;
    if (FilteredTreeModel.showParam && editingNode.isParam() && (isSimpleVariable || isAnnotation)) {
        // Add static labels for all columns except the value. See EquationTreeCellRenderer.getTreeCellRendererComponent()
        NodeBase p = editingNode.getTrueParent();
        List<Integer> columnWidths = p.getMaxColumnWidths(editingNode.getColumnGroup(), fm);
        // NodeVariable and NodeAnnotation return at least 3 columns.
        List<String> columns = editingNode.getColumns(true, expanded);
        for (// Set up the first two columns to display as fixed text in the editor.
        int i = 0; // Set up the first two columns to display as fixed text in the editor.
        i < 2; // Set up the first two columns to display as fixed text in the editor.
        i++) {
            JLabel l = labels.get(i);
            l.setText(columns.get(i));
            l.setFont(fontPlain);
            l.setVisible(true);
            l.setLocation(offset, 0);
            offset += columnWidths.get(i);
        }
        // 3rd column contains the value of the parameter.
        text = columns.get(2);
        if (isAnnotation)
            param = editingNode.source.get("param");
        else
            param = editingNode.source.get("$metadata", "param");
    } else {
        for (int i = 0; i < 2; i++) labels.get(i).setVisible(false);
        // Fetch user object.
        text = editingNode.toString();
        param = "";
    }
    // Update editing component
    if (editingComponent != null)
        editingContainer.remove(editingComponent);
    if (param.equals("flag")) {
        editingComponent = flagEditor;
        boolean isFalse = text.isEmpty() || text.equals("0");
        flagEditor.setSelected(!isFalse);
    } else if (// Dropdown list with fixed set of options.
    param.contains(",")) {
        editingComponent = choiceEditor;
        choiceEditor.removeAllItems();
        String[] pieces = param.split(",");
        for (String c : pieces) choiceEditor.addItem(c);
        choiceEditor.setSelectedItem(text);
    } else if (// Numeric range
    param.startsWith("[")) {
        editingComponent = rangeEditor;
        String[] pieces = param.substring(1).split("]", 2);
        rangeUnits = "";
        if (pieces.length == 2)
            rangeUnits = pieces[1];
        pieces = pieces[0].split(":");
        rangeLo = Double.valueOf(pieces[0]);
        rangeHi = Double.valueOf(pieces[1]);
        rangeStepSize = 1;
        if (pieces.length == 3)
            rangeStepSize = Double.valueOf(pieces[2]);
        int steps = (int) Math.round((rangeHi - rangeLo) / rangeStepSize);
        double current = new UnitValue(text).value;
        int c = (int) Math.round((current - rangeLo) / rangeStepSize);
        c = Math.max(c, 0);
        c = Math.min(c, steps);
        rangeEditor.setValues(c, 1, 0, steps + 1);
    } else // Plain text
    {
        int textWidth = fm.stringWidth(text);
        int treeWidth = tree.getWidth();
        if (!isTitle && (text.contains("\n") || textWidth > treeWidth || multiLineRequested)) {
            editingComponent = multiLinePane;
            multiLineEditor.setText(text);
            multiLineEditor.setFont(fontStyled);
            multiLineEditor.setEditable(!PanelModel.instance.panelEquations.locked);
            int equals = text.indexOf('=');
            if (equals >= 0)
                multiLineEditor.setCaretPosition(equals);
            multiLineRequested = false;
        } else {
            editingComponent = oneLineEditor;
            oneLineEditor.setText(text);
            oneLineEditor.setFont(fontStyled);
            oneLineEditor.setEditable(!PanelModel.instance.panelEquations.locked);
        }
        undoManager.discardAllEdits();
    }
    editingContainer.add(editingComponent);
    return editingContainer;
}
Also used : NodeVariable(gov.sandia.n2a.ui.eq.tree.NodeVariable) JLabel(javax.swing.JLabel) UnitValue(gov.sandia.n2a.language.UnitValue) Font(java.awt.Font) Point(java.awt.Point) NodeBase(gov.sandia.n2a.ui.eq.tree.NodeBase) NodeAnnotation(gov.sandia.n2a.ui.eq.tree.NodeAnnotation) FontMetrics(java.awt.FontMetrics)

Example 4 with UnitValue

use of gov.sandia.n2a.language.UnitValue in project n2a by frothga.

the class EquationSet method determinePoll.

/**
 *        Checks if connection requires polling.
 *        The result is a metadata tag on $p. If the tag exists, polling is required and the tag gives the time period
 *        (0 for every cycle, >0 for quantity of time to complete one poll).
 *        The user can specify this tag ahead of time. Specifying -1 will suppress polling even if it is required.
 *        Specifying poll >= 0 will not force polling if it is not required. Instead, the tag will be cleared by this function.
 *        Depends on results of: findInitOnly()
 *        Must be run before purgeInitOnlyTemporary(), because that function removes information critical for our processing.
 *        findConnectionMatrix() will clear the metadata tag if it succeeds, because that kind of connection is a one-time process,
 *        no need for polling.
 */
public void determinePoll() {
    for (EquationSet s : parts) s.determinePoll();
    if (connectionBindings == null)
        return;
    Variable p = find(new Variable("$p"));
    if (p == null)
        return;
    // Look up metadata to determine polling period.
    // Default is full poll every cycle. After determinePoll() finishes, the default will be no polling. This simplifies later processing.
    String pollString = p.metadata.getOrDefault("0", "poll");
    double pollValue = new UnitValue(pollString).get();
    if (// Don't do analysis if polling is suppressed in any case.
    pollValue < 0) {
        p.metadata.clear("poll");
        return;
    }
    List<EquationEntry> fires = new ArrayList<EquationEntry>();
    // All equations in "fires" return 0 or 1.
    boolean firesBoolean = true;
    ReplacePhaseIndicators replacePhase = new ReplacePhaseIndicators();
    // And other indicators are 0
    replacePhase.connect = 1;
    for (EquationEntry e : p.equations) {
        // Assume a condition always fires, unless we can prove it does not.
        boolean couldFire = true;
        boolean alwaysFires = true;
        if (e.condition != null) {
            Operator test = e.condition.deepCopy().transform(replacePhase).simplify(p, true);
            if (test.isScalar())
                couldFire = alwaysFires = test.getDouble() != 0;
            else
                alwaysFires = false;
        }
        if (couldFire) {
            fires.add(e);
            Operator expression = e.expression.deepCopy().transform(replacePhase).simplify(p, true);
            if (expression.isScalar()) {
                double value = expression.getDouble();
                if (value != 0 && value != 1)
                    firesBoolean = false;
            } else {
                firesBoolean = false;
            }
        }
        if (alwaysFires)
            break;
    }
    if (// $p has default value (1 at connect)
    fires.isEmpty()) {
        p.metadata.clear("poll");
        return;
    }
    boolean needsPoll;
    if (fires.size() > 1) {
        // Multiple connect conditions means unpredictable, so needs polling.
        // The exception is if $p is initOnly and all equations are either 0 or 1.
        // In that case, polling is unneeded because the existence of the part is
        // already known at init time.
        System.out.println("fires " + fires.size() + " " + prefix());
        needsPoll = !p.hasAttribute("initOnly") || !firesBoolean;
    } else {
        // Determine if the single expression for $p requires polling.
        // The possibilities for NOT polling are:
        // * a Scalar that is either 1 or 0
        // * a boolean expression that depends on nothing more than initOnly variables
        // Everything else requires polling. For example:
        // * a Scalar in (0,1) -- requires random draw
        // * a boolean expression that can vary during regular updates
        EquationEntry e = fires.get(0);
        if (e.expression.isScalar()) {
            double value = e.expression.getDouble();
            needsPoll = value > 0 && value < 1;
        } else {
            // The default is to poll, unless we can prove that we don't need to.
            needsPoll = true;
            VisitInitOnly visitor = new VisitInitOnly();
            if (e.condition != null)
                e.condition.visit(visitor);
            if (visitor.isInitOnly)
                e.expression.visit(visitor);
            if (visitor.isInitOnly) {
                // We have an initOnly equation. Now determine if the result is in (0,1).
                // The only values we can be sure about are logical results, which are exactly 1 or 0, and therefore not in (0,1).
                needsPoll = !(e.expression instanceof OperatorLogical);
            }
        }
    }
    if (needsPoll) {
        // If poll is not otherwise specified, then do full poll at every cycle.
        if (p.metadata.child("poll") == null)
            p.metadata.set("0", "poll");
    } else {
        p.metadata.clear("poll");
    }
}
Also used : Operator(gov.sandia.n2a.language.Operator) AccessVariable(gov.sandia.n2a.language.AccessVariable) ArrayList(java.util.ArrayList) UnitValue(gov.sandia.n2a.language.UnitValue) OperatorLogical(gov.sandia.n2a.language.OperatorLogical)

Example 5 with UnitValue

use of gov.sandia.n2a.language.UnitValue in project n2a by frothga.

the class OutputParser method parse.

public void parse(Path path) {
    try {
        if (reader == null)
            reader = new SafeReader(path);
        else
            reader.open(path);
        while (true) {
            String line = reader.readLine();
            // indicates end of stream
            if (line == null)
                break;
            if (line.length() == 0)
                continue;
            if (line.startsWith("End of"))
                continue;
            if (!delimiterSet) {
                if (// highest precedence
                line.contains("\t"))
                    // highest precedence
                    delimiter = "\t";
                else if (line.contains(","))
                    delimiter = ",";
                // space character is lowest precedence
                delimiterSet = !delimiter.equals(" ") || !line.isBlank();
            }
            // -1 means that trailing delimiters will produce additional columns. Internal and C backends do not produce trailing delimiters, but other simulators might.
            String[] parts = line.split(delimiter, -1);
            int lastSize = columns.size();
            while (columns.size() < parts.length) {
                Column c = new Column();
                c.startRow = rows;
                columns.add(c);
            }
            // first character. There should always be something in first column, because we put either "$t" or current timestamp there.
            char fc = parts[0].charAt(0);
            if (// number
            fc == '-' || fc == '+' || fc == '.' || fc >= '0' && fc <= '9') {
                // skip parsing Index column, since we don't use it
                int p = isXycePRN ? 1 : 0;
                for (; p < parts.length; p++) {
                    Column c = columns.get(p);
                    float value = defaultValue;
                    if (!parts[p].isEmpty()) {
                        value = Float.parseFloat(parts[p]);
                        c.textWidth = Math.max(c.textWidth, parts[p].length());
                    }
                    c.values.add(value);
                }
                // Because the structure is not sparse, we must fill out every row.
                for (; p < columns.size(); p++) columns.get(p).values.add(defaultValue);
                rows++;
            } else // column header
            {
                raw = false;
                isXycePRN = parts[0].equals("Index");
                for (int p = lastSize; p < parts.length; p++) {
                    columns.get(p).header = parts[p];
                }
            }
        }
    } catch (IOException e) {
    }
    if (reader != null)
        reader.close();
    if (columns.size() == 0)
        return;
    // If this is a Xyce PRN file, then there won't also be a columns file, so no need to worry about column numbering.
    if (isXycePRN)
        columns.remove(0);
    // If there is a separate columns file, open and parse it.
    MDoc columnFile = null;
    Path jobDir = path.getParent();
    Path columnPath = jobDir.resolve(path.getFileName().toString() + ".columns");
    if (Files.isReadable(columnPath)) {
        columnFile = new MDoc(columnPath);
        for (MNode n : columnFile) {
            int columnIndex = Integer.valueOf(n.key());
            if (columnIndex >= columns.size())
                break;
            Column c = columns.get(columnIndex);
            c.header = n.getOrDefault(c.header);
            String colorName = n.get("color");
            if (!colorName.isEmpty()) {
                try {
                    c.color = Color.decode(colorName);
                } catch (NumberFormatException error) {
                    // Attempt to interpret as a standard HTML color name.
                    // If no match is found, color remains null.
                    c.color = HTMLcolors.get(colorName.toLowerCase());
                }
            }
            // Like "color", but expects default values for saturation and brightness.
            colorName = n.get("hue");
            if (!colorName.isEmpty()) {
                float hue = 0;
                try {
                    hue = Float.valueOf(colorName);
                } catch (NumberFormatException error) {
                }
                c.color = Color.getHSBColor(hue, 1.0f, 0.8f);
            }
            String scale = n.get("scale");
            if (!scale.isEmpty()) {
                c.scale = new UnitValue(scale);
                if (c.scale.value == 0)
                    c.scale.value = 1;
                if (c.scale.unit == null)
                    c.scale.unit = AbstractUnit.ONE;
            }
            // Note that width=0 means narrowest line possible, which isn't necessarily the best default.
            c.width = (float) n.getOrDefault(1.0, "width");
            String dash = n.get("dash");
            if (!dash.isEmpty()) {
                String[] pieces = dash.split(":");
                c.dash = new float[pieces.length];
                for (int i = 0; i < pieces.length; i++) {
                    try {
                        c.dash[i] = Float.valueOf(pieces[i]);
                    } catch (NumberFormatException error) {
                    }
                }
            }
        }
    }
    // Determine time column
    // fallback, in case we don't find it by name
    time = columns.get(0);
    int timeMatch = 0;
    for (int i = 0; i < columns.size(); i++) {
        Column c = columns.get(i);
        int potentialMatch = 0;
        if (c.header.equals("t"))
            potentialMatch = 1;
        else if (c.header.equals("TIME"))
            potentialMatch = 2;
        else if (c.header.equals("$t"))
            potentialMatch = 3;
        if (potentialMatch > timeMatch) {
            timeMatch = potentialMatch;
            time = c;
            timeFound = true;
            if (columnFile != null) {
                MNode n = columnFile.child(i);
                xmin = (float) n.getOrDefault(xmin, "xmin");
                xmax = (float) n.getOrDefault(xmax, "xmax");
                ymin = (float) n.getOrDefault(ymin, "ymin");
                ymax = (float) n.getOrDefault(ymax, "ymax");
            }
        }
    }
}
Also used : Path(java.nio.file.Path) UnitValue(gov.sandia.n2a.language.UnitValue) IOException(java.io.IOException) MNode(gov.sandia.n2a.db.MNode) MDoc(gov.sandia.n2a.db.MDoc)

Aggregations

UnitValue (gov.sandia.n2a.language.UnitValue)5 MNode (gov.sandia.n2a.db.MNode)2 AccessVariable (gov.sandia.n2a.language.AccessVariable)2 Operator (gov.sandia.n2a.language.Operator)2 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 ArrayList (java.util.ArrayList)2 MDoc (gov.sandia.n2a.db.MDoc)1 EquationEntry (gov.sandia.n2a.eqset.EquationEntry)1 AccountableConnection (gov.sandia.n2a.eqset.EquationSet.AccountableConnection)1 ConnectionBinding (gov.sandia.n2a.eqset.EquationSet.ConnectionBinding)1 Variable (gov.sandia.n2a.eqset.Variable)1 VariableReference (gov.sandia.n2a.eqset.VariableReference)1 Host (gov.sandia.n2a.host.Host)1 Remote (gov.sandia.n2a.host.Remote)1 OperatorLogical (gov.sandia.n2a.language.OperatorLogical)1 Split (gov.sandia.n2a.language.Split)1 Visitor (gov.sandia.n2a.language.Visitor)1 Output (gov.sandia.n2a.language.function.Output)1 Scalar (gov.sandia.n2a.language.type.Scalar)1