Search in sources :

Example 1 with Visitor

use of gov.sandia.n2a.db.MNode.Visitor in project n2a by frothga.

the class PanelRun method viewJob.

public void viewJob(boolean refresh) {
    if (displayThread != null) {
        synchronized (displayText) {
            displayThread.stop = true;
            displayThread = null;
        }
    }
    StringBuilder contents = new StringBuilder();
    contents.append("Status:");
    NodeJob jobNode = (NodeJob) displayNode;
    if (jobNode.complete < 0)
        contents.append(" Waiting");
    else if (jobNode.complete == 0)
        contents.append(" Started");
    else if (jobNode.complete > 0 && jobNode.complete < 1)
        contents.append(" " + Math.round(jobNode.complete * 100) + "%");
    else if (jobNode.complete == 1)
        contents.append(" Success");
    else if (jobNode.complete == 3)
        contents.append(" Killed (lingering)");
    else if (jobNode.complete == 4)
        contents.append(" Killed");
    else
        // complete==2, or any value not specified above
        contents.append(" Failed");
    contents.append("\n");
    if (jobNode.dateStarted != null)
        contents.append("  started:  " + jobNode.dateStarted + "\n");
    if (jobNode.dateFinished != null)
        contents.append("  finished: " + jobNode.dateFinished + "\n");
    contents.append("\n");
    MNode job = jobNode.getSource();
    if (// job can be null if it is deleted while we are preparing this status text.
    job != null) {
        appendMetadata(job, contents, "backend");
        appendMetadata(job, contents, "duration");
        appendMetadata(job, contents, "host");
        appendMetadata(job, contents, "pid");
        appendMetadata(job, contents, "seed");
        contents.append("\n");
    }
    // Walk the model and display all overridden parameters.
    if (job != null && jobNode.hasSnapshot()) {
        // Obtain top-level model and collated model
        MNode doc;
        MNode model;
        String key = job.get("$inherit");
        Path localJobDir = Host.getJobDir(Host.getLocalResourceDir(), job);
        Path snapshotPath = localJobDir.resolve("snapshot");
        if (Files.exists(snapshotPath)) {
            MNode snapshot = new MDoc(snapshotPath);
            doc = snapshot.child(key);
            model = MPart.fromSnapshot(key, snapshot);
        } else {
            doc = AppData.models.childOrEmpty(key);
            model = new MDoc(localJobDir.resolve("model"), key);
        }
        doc.visit(new Visitor() {

            public boolean visit(MNode node) {
                List<String> keyList = Arrays.asList(node.keyPath(doc));
                List<String> paramPath = new ArrayList<String>(keyList);
                paramPath.add("$metadata");
                paramPath.add("param");
                Object[] paramArray = paramPath.toArray();
                // node is not a parameter
                if (!model.getFlag(paramArray))
                    return true;
                // watchable items aren't of interest for this summary
                if (model.get(paramArray).equals("watch"))
                    return true;
                String[] keyPath = keyList.toArray(new String[keyList.size()]);
                String key = keyPath[0];
                for (int i = 1; i < keyPath.length; i++) key += "." + keyPath[i];
                ParsedValue pv = new ParsedValue(model.get(keyPath));
                contents.append(key + " =" + pv.combiner + " " + pv.expression + "\n");
                if (// Could be multi-valued
                pv.expression.isEmpty()) {
                    for (MNode v : model.childOrEmpty(keyPath)) {
                        key = v.key();
                        if (key.contains("@"))
                            contents.append("\t" + v.get() + "\t" + key + "\n");
                    }
                }
                return true;
            }
        });
    }
    synchronized (displayText) {
        if (refresh) {
            Caret c = displayText.getCaret();
            int dot = c.getDot();
            int mark = c.getMark();
            Point magic = c.getMagicCaretPosition();
            if (magic == null)
                magic = new Point();
            Rectangle visible = displayPane.getViewport().getViewRect();
            if (// User has scrolled away from caret.
            !visible.contains(magic)) {
                // Scroll takes precedence over caret, so move caret back into visible area.
                Font f = displayText.getFont();
                FontMetrics fm = displayText.getFontMetrics(f);
                int h = fm.getHeight();
                int w = fm.getMaxAdvance();
                if (w < 0)
                    w = h / 2;
                h += h / 2;
                w += w / 2;
                magic.x = Math.max(magic.x, visible.x == 0 ? 0 : visible.x + w);
                magic.x = Math.min(magic.x, visible.x + visible.width - w);
                magic.y = Math.max(magic.y, visible.y == 0 ? 0 : visible.y + h);
                magic.y = Math.min(magic.y, visible.y + visible.height - h);
                dot = mark = displayText.viewToModel2D(magic);
            }
            displayText.setText(contents.toString());
            c.setDot(mark);
            if (dot != mark)
                c.moveDot(dot);
        } else {
            displayText.setText(contents.toString());
            displayText.setCaretPosition(0);
        }
    }
    displayChart.buttonBar.setVisible(false);
    if (displayPane.getViewport().getView() != displayText)
        displayPane.setViewportView(displayText);
    displayPane.repaint();
}
Also used : Path(java.nio.file.Path) TreePath(javax.swing.tree.TreePath) Visitor(gov.sandia.n2a.db.MNode.Visitor) Rectangle(java.awt.Rectangle) Point(java.awt.Point) MNode(gov.sandia.n2a.db.MNode) Point(java.awt.Point) Font(java.awt.Font) MDoc(gov.sandia.n2a.db.MDoc) ParsedValue(gov.sandia.n2a.eqset.Variable.ParsedValue) FontMetrics(java.awt.FontMetrics) List(java.util.List) ArrayList(java.util.ArrayList) Caret(javax.swing.text.Caret)

Example 2 with Visitor

use of gov.sandia.n2a.db.MNode.Visitor in project n2a by frothga.

the class ExportBibliography method export.

@Override
public void export(MNode document, Path destination) throws Exception {
    MNode references = new MVolatile();
    if (// document is a reference.
    document.child("$metadata") == null && document.child("form") != null) {
        references.set(document, document.key());
    } else // document is a model
    {
        // Iterate over model, collecting all references and their contexts.
        document.visit(new Visitor() {

            public boolean visit(MNode node) {
                if (!node.key().equals("$reference"))
                    return true;
                String[] keyPath = node.parent().keyPath();
                String location = keyPath[0];
                for (int i = 1; i < keyPath.length; i++) location += "." + keyPath[i];
                for (MNode r : node) {
                    MNode n = references.childOrCreate(r.key(), "note");
                    String note = n.get();
                    if (!note.isEmpty())
                        note += "\n";
                    note += location + " -- " + r.get();
                    n.set(note);
                }
                return false;
            }
        });
        // Fill in reference records
        for (MNode r : references) {
            MNode doc = AppData.references.child(r.key());
            if (doc == null)
                continue;
            r.mergeUnder(doc);
            String docNote = doc.get("note");
            if (docNote.isEmpty())
                continue;
            String note = r.get("note");
            if (note.isEmpty())
                continue;
            docNote += "\n" + note;
            r.set(note, "note");
        }
    }
    try (Writer writer = Files.newBufferedWriter(destination)) {
        export(references, writer);
    }
}
Also used : Visitor(gov.sandia.n2a.db.MNode.Visitor) MNode(gov.sandia.n2a.db.MNode) Writer(java.io.Writer) MVolatile(gov.sandia.n2a.db.MVolatile)

Example 3 with Visitor

use of gov.sandia.n2a.db.MNode.Visitor in project n2a by frothga.

the class Study method buildIterator.

public void buildIterator() {
    // Assumes iterator is null
    MNode variables = source.childOrEmpty("variables");
    class VariableVisitor implements Visitor {

        MNode goal;

        List<MNode> optimize = new ArrayList<MNode>();

        public boolean visit(MNode n) {
            // This is merely an intermediate node, not a study variable.
            if (!n.data())
                return true;
            String[] keys = n.keyPath(variables);
            String value = n.get().trim();
            StudyIterator it = null;
            if (// Identifies a variable to be optimized
            n.child("optimize") != null) {
                // The optimizer may use value as a hint about range to work within.
                optimize.add(n);
            } else if (// Identifies the variable whose error value we wish to minimize.
            n.child("goal") != null) {
                goal = n;
            } else if (value.startsWith("[")) {
                value = value.substring(1);
                value = value.split("]", 2)[0];
                it = new IteratorRange(keys, value);
            } else if (value.startsWith("uniform") || value.startsWith("gaussian")) {
                it = new IteratorRandom(keys, value, n);
                usesRandom = true;
            } else if (value.contains(",")) {
                it = new IteratorList(keys, value);
            } else
                // Ignore unrecognized study type. TODO: should we throw an error instead?
                return false;
            if (iterator != null) {
                // Move to first item in sequence. At least one must exist.
                iterator.next();
                it.inner = iterator;
            }
            iterator = it;
            return false;
        }
    }
    VariableVisitor visitor = new VariableVisitor();
    variables.visit(visitor);
    // This must always be last, so that it forms the inner loop. Combinatorial iteration takes place around it.
    if (visitor.goal == null)
        return;
    StudyIterator it = new OptimizerLM(visitor.goal.keyPath(variables), visitor.optimize, this);
    iterator.next();
    it.inner = it;
}
Also used : Visitor(gov.sandia.n2a.db.MNode.Visitor) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) MNode(gov.sandia.n2a.db.MNode)

Example 4 with Visitor

use of gov.sandia.n2a.db.MNode.Visitor in project n2a by frothga.

the class PanelEquations method createStudy.

public static MDoc createStudy(MNode collated) {
    String key = new SimpleDateFormat("yyyy-MM-dd-HHmmss", Locale.ROOT).format(new Date());
    MDoc study = (MDoc) AppData.studies.childOrCreate(key);
    study.set(collated.key(), "$inherit");
    // Copy top-level study tag (general parameters controlling study).
    study.set(collated.childOrEmpty("$metadata", "study"), "config");
    // Collect study tags
    MNode variables = study.childOrCreate("variables");
    collated.visit(new Visitor() {

        public boolean visit(MNode n) {
            // Filter on "study" first.
            if (!n.key().equals("study"))
                return true;
            String[] keyPath = n.keyPath();
            // Search backwards for "$metadata", because it is most likely to be immediate parent of "study".
            int i = keyPath.length - 1;
            for (; i >= 0; i--) if (keyPath[i].equals("$metadata"))
                break;
            // move along, nothing to see here
            if (i < 0)
                return true;
            if (// immediate parent
            i == keyPath.length - 2) {
                // This is the top-level metadata block, so ignore study. It contains general parameters, rather than tagging a variable.
                if (keyPath.length < 3)
                    return true;
                // skip up to the parent of $metadata, which should be a variable
                keyPath = Arrays.copyOfRange(keyPath, 0, keyPath.length - 2);
            } else // more distant parent, so a metadata key is the item to be iterated, rather than a variable
            {
                keyPath = Arrays.copyOfRange(keyPath, 0, keyPath.length - 1);
            }
            // Save entire subtree under n, if it exists.
            variables.set(n, keyPath);
            // ensure node is defined so it can indicate the study variable
            if (!variables.data(keyPath))
                variables.set("", keyPath);
            // Don't descend after finding a study tag.
            return false;
        }
    });
    // force directory to exist
    study.save();
    return study;
}
Also used : Visitor(gov.sandia.n2a.db.MNode.Visitor) SimpleDateFormat(java.text.SimpleDateFormat) MNode(gov.sandia.n2a.db.MNode) Date(java.util.Date) MDoc(gov.sandia.n2a.db.MDoc)

Aggregations

MNode (gov.sandia.n2a.db.MNode)4 Visitor (gov.sandia.n2a.db.MNode.Visitor)4 MDoc (gov.sandia.n2a.db.MDoc)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 MVolatile (gov.sandia.n2a.db.MVolatile)1 ParsedValue (gov.sandia.n2a.eqset.Variable.ParsedValue)1 Font (java.awt.Font)1 FontMetrics (java.awt.FontMetrics)1 Point (java.awt.Point)1 Rectangle (java.awt.Rectangle)1 Writer (java.io.Writer)1 Path (java.nio.file.Path)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 LinkedList (java.util.LinkedList)1 Caret (javax.swing.text.Caret)1 TreePath (javax.swing.tree.TreePath)1