Search in sources :

Example 6 with Graph

use of au.gov.asd.tac.constellation.graph.Graph in project constellation by constellation-app.

the class LayerByTimePlugin method read.

@Override
public void read(final GraphReadMethods rg, final PluginInteraction interaction, final PluginParameters parameters) throws PluginException, InterruptedException {
    // We have the dtAttr from the original wg: we should have been passed the label, but never mind.
    // We need to get the label from the original, so we can get the dtAttr for the copy.
    final String dtAttrOrig = parameters.getParameters().get(DATETIME_ATTRIBUTE_PARAMETER_ID).getStringValue();
    if (dtAttrOrig == null) {
        interaction.notify(PluginNotificationLevel.ERROR, "A date-time attribute must be specified.");
        return;
    }
    final int dtAttrOrigId = rg.getAttribute(GraphElementType.TRANSACTION, dtAttrOrig);
    if (dtAttrOrigId == Graph.NOT_FOUND) {
        interaction.notify(PluginNotificationLevel.ERROR, "A valid date-time attribute must be specified.");
        return;
    }
    Graph copy;
    try {
        final Plugin copyGraphPlugin = PluginRegistry.get(InteractiveGraphPluginRegistry.COPY_TO_NEW_GRAPH);
        final PluginParameters copyParams = copyGraphPlugin.createParameters();
        copyParams.getParameters().get(CopyToNewGraphPlugin.NEW_SCHEMA_NAME_PARAMETER_ID).setStringValue(rg.getSchema().getFactory().getName());
        copyParams.getParameters().get(CopyToNewGraphPlugin.COPY_ALL_PARAMETER_ID).setBooleanValue(true);
        copyParams.getParameters().get(CopyToNewGraphPlugin.COPY_KEYS_PARAMETER_ID).setBooleanValue(false);
        PluginExecution.withPlugin(copyGraphPlugin).withParameters(copyParams).executeNow(rg);
        copy = (Graph) copyParams.getParameters().get(CopyToNewGraphPlugin.NEW_GRAPH_OUTPUT_PARAMETER_ID).getObjectValue();
    } catch (final PluginException ex) {
        copy = null;
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    }
    if (copy == null) {
        // The copy failed, drop out now.
        return;
    }
    final Attribute dt = new GraphAttribute(rg, dtAttrOrigId);
    final WritableGraph wgcopy = copy.getWritableGraph("Layer by time", true);
    try {
        final int dtAttr = wgcopy.getAttribute(GraphElementType.TRANSACTION, dt.getName());
        final boolean useIntervals = parameters.getParameters().get(LAYER_BY_PARAMETER_ID).getStringValue().equals(INTERVAL_METHOD);
        final ZonedDateTime[] startEnd = parameters.getParameters().get(DATE_RANGE_PARAMETER_ID).getDateTimeRangeValue().getZonedStartEnd();
        final ZonedDateTime start = startEnd[0];
        final ZonedDateTime end = startEnd[1];
        final boolean isTransactionLayers = parameters.getParameters().get(TRANSACTION_AS_LAYER_PARAMETER_ID).getBooleanValue();
        // Establish new attributes.
        // Create and store graph attributes.
        final LayerName defaultName = new LayerName(Graph.NOT_FOUND, "Default");
        final int timeLayerAttr = wgcopy.addAttribute(GraphElementType.TRANSACTION, LayerNameAttributeDescription.ATTRIBUTE_NAME, LAYER_NAME, "time layer", defaultName, null);
        wgcopy.addAttribute(GraphElementType.GRAPH, IntegerAttributeDescription.ATTRIBUTE_NAME, NLAYERS, "The number of layers to layer by time", 1, null);
        final int txColorAttr = wgcopy.getAttribute(GraphElementType.TRANSACTION, "color");
        final int txGuideline = wgcopy.addAttribute(GraphElementType.TRANSACTION, BooleanAttributeDescription.ATTRIBUTE_NAME, "layer_guideline", "This transaction is a layer guideline", false, null);
        final ConstellationColor guidelineColor = ConstellationColor.getColorValue(0.25F, 0.25F, 0.25F, 1F);
        wgcopy.addAttribute(GraphElementType.VERTEX, IntegerAttributeDescription.ATTRIBUTE_NAME, ORIGINAL_ID_LABEL, "Original Node Id", -1, null);
        final List<Float> values = new ArrayList<>();
        final Map<Integer, List<Float>> remappedLayers = new HashMap<>();
        final Map<Integer, String> displayNames = new HashMap<>();
        if (useIntervals) {
            final int intervalUnit = LAYER_INTERVALS.get(parameters.getParameters().get(UNIT_PARAMETER_ID).getStringValue());
            final int intervalAmount = parameters.getParameters().get(AMOUNT_PARAMETER_ID).getIntegerValue();
            buildIntervals(wgcopy, values, remappedLayers, displayNames, dtAttr, start.toInstant(), end.toInstant(), intervalUnit, intervalAmount);
        } else {
            final int calendarUnit = BIN_CALENDAR_UNITS.get(parameters.getParameters().get(UNIT_PARAMETER_ID).getStringValue());
            final int binAmount = parameters.getParameters().get(AMOUNT_PARAMETER_ID).getIntegerValue();
            buildBins(wgcopy, values, remappedLayers, displayNames, dtAttr, start.toInstant(), end.toInstant(), calendarUnit, binAmount);
        }
        final boolean keepTxColors = parameters.getParameters().get(KEEP_TX_COLORS_PARAMETER_ID).getBooleanValue();
        final boolean drawTxGuides = parameters.getParameters().get(DRAW_TX_GUIDES_PARAMETER_ID).getBooleanValue();
        // Modify the copied graph to show our layers.
        int z = 0;
        float step = getWidth(wgcopy) / values.size();
        for (final Entry<Integer, List<Float>> entry : remappedLayers.entrySet()) {
            for (final Entry<Float, List<Integer>> currentLayer : transactionLayers.entrySet()) {
                if (entry.getValue().contains(currentLayer.getKey())) {
                    for (final int txId : currentLayer.getValue()) {
                        final float origLayer = currentLayer.getKey();
                        int newLayer = 0;
                        if (entry.getValue().contains(origLayer)) {
                            // Overwrite value
                            newLayer = entry.getKey();
                        }
                        final LayerName dn = new LayerName(newLayer, displayNames.get(newLayer));
                        wgcopy.setObjectValue(timeLayerAttr, txId, dn);
                        final float normLayer = newLayer / (remappedLayers.keySet().size() * 1F);
                        if (!keepTxColors) {
                            final Color heatmap = new Color(Color.HSBtoRGB((1 - normLayer) * 2F / 3F, 0.5F, 1));
                            final ConstellationColor color = ConstellationColor.getColorValue(heatmap.getRed() / 255F, heatmap.getGreen() / 255F, heatmap.getBlue() / 255F, 1F);
                            wgcopy.setObjectValue(txColorAttr, txId, color);
                        }
                        if (isTransactionLayers) {
                            transactionsAsLayers(wgcopy, txId, z, step);
                        } else {
                            nodesAsLayers(wgcopy, txId, newLayer);
                        }
                    }
                }
            }
            if (isTransactionLayers) {
                srcVxMap = dstVxMap;
                dstVxMap = new HashMap<>();
                z += step;
            }
        }
        // Remove any outstanding transactions flagged for deletion
        for (int txId = txToDelete.nextSetBit(0); txId >= 0; txId = txToDelete.nextSetBit(txId + 1)) {
            wgcopy.removeTransaction(txId);
        }
        // Get rid of all of the nodes that don't have any transactions.
        // By definition, the duplicates will have transactions between them, including the original layer
        // (because we just deleted transactions that belong in different layers, leaving only the transactions
        // that belong in the original layer).
        final List<Integer> vertices = new ArrayList<>();
        for (int position = 0; position < wgcopy.getVertexCount(); position++) {
            final int vertexId = wgcopy.getVertex(position);
            final int nTx = wgcopy.getVertexTransactionCount(vertexId);
            if (nTx == 0) {
                vertices.add(vertexId);
            }
        }
        vertices.stream().forEach(wgcopy::removeVertex);
        if (drawTxGuides) {
            interaction.setProgress(5, 6, "Draw guide lines", false);
            // We have to do this after the "remove node without transactions" step because we're adding more transactions.
            if (!isTransactionLayers && remappedLayers.keySet().size() > 1) {
                nodeIdToLayers.keySet().stream().forEach(origNodeId -> {
                    int prevNodeId = -1;
                    final BitSet layers = nodeIdToLayers.get(origNodeId);
                    for (int layer = layers.nextSetBit(0); layer >= 0; layer = layers.nextSetBit(layer + 1)) {
                        final int nodeId = layer == 0 ? origNodeId : nodeDups.get(String.format("%s/%s", origNodeId, layer));
                        if (prevNodeId != -1) {
                            final int sTxId = wgcopy.addTransaction(prevNodeId, nodeId, false);
                            wgcopy.setBooleanValue(txGuideline, sTxId, true);
                            wgcopy.setObjectValue(txColorAttr, sTxId, guidelineColor);
                            final LayerName dn = new LayerName(1107, "Guideline");
                            wgcopy.setObjectValue(timeLayerAttr, sTxId, dn);
                        }
                        prevNodeId = nodeId;
                    }
                });
            }
        }
    } finally {
        wgcopy.commit();
    }
}
Also used : Attribute(au.gov.asd.tac.constellation.graph.Attribute) GraphAttribute(au.gov.asd.tac.constellation.graph.GraphAttribute) HashMap(java.util.HashMap) GraphAttribute(au.gov.asd.tac.constellation.graph.GraphAttribute) ArrayList(java.util.ArrayList) ZonedDateTime(java.time.ZonedDateTime) List(java.util.List) ArrayList(java.util.ArrayList) PluginParameters(au.gov.asd.tac.constellation.plugins.parameters.PluginParameters) WritableGraph(au.gov.asd.tac.constellation.graph.WritableGraph) ConstellationColor(au.gov.asd.tac.constellation.utilities.color.ConstellationColor) LayerName(au.gov.asd.tac.constellation.graph.schema.visual.attribute.objects.LayerName) PluginException(au.gov.asd.tac.constellation.plugins.PluginException) Color(java.awt.Color) ConstellationColor(au.gov.asd.tac.constellation.utilities.color.ConstellationColor) BitSet(java.util.BitSet) WritableGraph(au.gov.asd.tac.constellation.graph.WritableGraph) ReadableGraph(au.gov.asd.tac.constellation.graph.ReadableGraph) Graph(au.gov.asd.tac.constellation.graph.Graph) CopyToNewGraphPlugin(au.gov.asd.tac.constellation.graph.interaction.plugins.clipboard.CopyToNewGraphPlugin) SimpleReadPlugin(au.gov.asd.tac.constellation.plugins.templates.SimpleReadPlugin) Plugin(au.gov.asd.tac.constellation.plugins.Plugin)

Example 7 with Graph

use of au.gov.asd.tac.constellation.graph.Graph in project constellation by constellation-app.

the class ArrangeInBubbleTreeAction method actionPerformed.

@Override
public void actionPerformed(final ActionEvent e) {
    final Graph graph = context.getGraph();
    final ReadableGraph rg = graph.getReadableGraph();
    try {
        NamedSelectionState nsState = null;
        final int namedSelectionId = rg.getAttribute(GraphElementType.VERTEX, "named_selection");
        if (namedSelectionId != Graph.NOT_FOUND) {
            final int namedSelectionStateId = rg.getAttribute(GraphElementType.META, NamedSelectionState.ATTRIBUTE_NAME);
            if (namedSelectionStateId != Graph.NOT_FOUND) {
                nsState = rg.getObjectValue(namedSelectionStateId, 0);
                final SelectNamedSelectionPanel ssp = new SelectNamedSelectionPanel(nsState.getNamedSelections(), "Select a named selection to represent the tree roots.");
                final DialogDescriptor dd = new DialogDescriptor(ssp, Bundle.CTL_ArrangeInBubbleTreeAction());
                dd.setHelpCtx(new HelpCtx(HELP_LOCATION));
                final Object result = DialogDisplayer.getDefault().notify(dd);
                if (result == DialogDescriptor.OK_OPTION) {
                    final long selectionId = ssp.getNamedSelectionId();
                    if (selectionId != -1) {
                        final long mask = 1L << selectionId;
                        final Set<Integer> rootVxIds = new HashSet<>();
                        for (int position = 0; position < rg.getVertexCount(); position++) {
                            final int vxId = rg.getVertex(position);
                            final long selections = rg.getLongValue(namedSelectionId, vxId);
                            if ((selections & mask) != 0) {
                                rootVxIds.add(vxId);
                            }
                        }
                        PluginExecutor.startWith(ArrangementPluginRegistry.BUBBLE_TREE).set(ArrangeInBubbleTreePlugin.ROOTS_PARAMETER_ID, rootVxIds).set(ArrangeInBubbleTreePlugin.IS_MINIMAL_PARAMETER_ID, true).followedBy(InteractiveGraphPluginRegistry.RESET_VIEW).executeWriteLater(context.getGraph(), Bundle.CTL_ArrangeInBubbleTreeAction());
                    }
                }
            }
        }
        if (nsState == null) {
            NotifyDisplayer.display("There must be a named selection to specify the tree roots", NotifyDescriptor.WARNING_MESSAGE);
        }
    } finally {
        rg.release();
    }
}
Also used : ReadableGraph(au.gov.asd.tac.constellation.graph.ReadableGraph) ReadableGraph(au.gov.asd.tac.constellation.graph.ReadableGraph) Graph(au.gov.asd.tac.constellation.graph.Graph) SelectNamedSelectionPanel(au.gov.asd.tac.constellation.views.namedselection.utilities.SelectNamedSelectionPanel) DialogDescriptor(org.openide.DialogDescriptor) HelpCtx(org.openide.util.HelpCtx) NamedSelectionState(au.gov.asd.tac.constellation.views.namedselection.state.NamedSelectionState) HashSet(java.util.HashSet)

Example 8 with Graph

use of au.gov.asd.tac.constellation.graph.Graph in project constellation by constellation-app.

the class ArrangeInSingleTreeAction method edit.

@Override
protected void edit(final PluginGraphs graphs, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException {
    final Graph graph = graphs.getGraph();
    final WritableGraph wg = graph.getWritableGraph(Bundle.CTL_ArrangeInSingleTreeAction(), true);
    try {
        final Worker worker = new Worker(wg);
        worker.run();
        PluginExecution.withPlugin(InteractiveGraphPluginRegistry.RESET_VIEW).executeNow(graphs.getGraph());
    } finally {
        wg.commit();
    }
}
Also used : WritableGraph(au.gov.asd.tac.constellation.graph.WritableGraph) Graph(au.gov.asd.tac.constellation.graph.Graph) WritableGraph(au.gov.asd.tac.constellation.graph.WritableGraph)

Example 9 with Graph

use of au.gov.asd.tac.constellation.graph.Graph in project constellation by constellation-app.

the class NonoverlappingRepulsionAction method actionPerformed.

@Override
public void actionPerformed(final ActionEvent ev) {
    final Graph graph = context.getGraph();
    final Worker worker = new Worker(graph);
    worker.execute();
}
Also used : Graph(au.gov.asd.tac.constellation.graph.Graph) WritableGraph(au.gov.asd.tac.constellation.graph.WritableGraph) SwingWorker(javax.swing.SwingWorker)

Example 10 with Graph

use of au.gov.asd.tac.constellation.graph.Graph in project constellation by constellation-app.

the class ExecuteListener method handle.

/**
 * Handles the click of the execute button in the data access view.
 * <p/>
 * If the execute button was in the "Go" state then it will iterate through
 * all the tabs and run the enabled and valid plugins.
 * <p/>
 * If the execute button was in the "Stop" state then cancel any running plugins.
 *
 * @param event the event triggered by clicking the execute button
 */
@Override
public void handle(final ActionEvent event) {
    // When no graph present, create a new one
    if (DataAccessPaneState.getCurrentGraphId() == null && dataAccessPane.getDataAccessTabPane().hasActiveAndValidPlugins()) {
        // Create new graph
        final NewDefaultSchemaGraphAction graphAction = new NewDefaultSchemaGraphAction();
        graphAction.actionPerformed(null);
        Graph newActiveGraph = null;
        // Wait while graph is getting made
        while (newActiveGraph == null) {
            newActiveGraph = GraphManager.getDefault().getActiveGraph();
        }
        // Set the state's current graph ID to the ID of the new graph
        DataAccessPaneState.setCurrentGraphId(newActiveGraph.getId());
    }
    // Run the selected queries
    final ObservableList<Tab> tabs = dataAccessPane.getDataAccessTabPane().getTabPane().getTabs();
    if (CollectionUtils.isNotEmpty(tabs) && DataAccessPaneState.isExecuteButtonIsGo()) {
        // Change the execute button to "Stop" and do not disable because it is now running
        dataAccessPane.setExecuteButtonToStop(false);
        // Set the state for the current graph state to running queries
        DataAccessPaneState.setQueriesRunning(true);
        // Check to see if an output dir exists. Non exisiting dirs do not prevent the
        // plugins running, just triggers a notification
        final File outputDir = DataAccessPreferenceUtilities.getDataAccessResultsDirEx();
        if (outputDir != null && outputDir.isDirectory()) {
            StatusDisplayer.getDefault().setStatusText(String.format(STATUS_MESSAGE_FORMAT, outputDir.getAbsolutePath()));
        } else if (outputDir != null) {
            NotificationDisplayer.getDefault().notify(RESULTS_DIR_NOT_FOUND_TITLE, ERROR_ICON, String.format(RESULTS_DIR_NOT_FOUND_MSG, outputDir.getAbsolutePath()), null);
        }
        // Save the current data access view state
        PluginExecution.withPlugin(new SimplePlugin(SAVE_STATE_PLUGIN_NAME) {

            @Override
            protected void execute(final PluginGraphs graphs, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException {
                DataAccessUtilities.saveDataAccessState(dataAccessPane.getDataAccessTabPane().getTabPane(), GraphNode.getGraph(DataAccessPaneState.getCurrentGraphId()));
            }
        }).executeLater(null);
        // Run the plugins from each tab. The barrier is the plugin run futures
        // from the previous tab. When the tab is run, it has the option to
        // wait for the previous tab to complete.
        List<Future<?>> barrier = null;
        for (final Tab tab : tabs) {
            LOGGER.log(Level.INFO, String.format("Running tab: %s", tab.getText()));
            barrier = DataAccessTabPane.getQueryPhasePane(tab).runPlugins(barrier);
        }
        // Asynchronously start the task that waits for all the plugins to complete.
        // Once they are complete this task will perform cleanup.
        CompletableFuture.runAsync(new WaitForQueriesToCompleteTask(dataAccessPane, DataAccessPaneState.getCurrentGraphId()), dataAccessPane.getParentComponent().getExecutorService());
        LOGGER.info("Plugins run.");
    } else {
        // The execute button is in a "Stop" state. So cancel any running plugins.
        DataAccessPaneState.getRunningPlugins().keySet().forEach(running -> running.cancel(true));
        // Nothing is running now, so change the execute button to "Go".
        dataAccessPane.setExecuteButtonToGo(false);
    }
    // Disables all plugins in the plugin pane
    if (DataAccessPreferenceUtilities.isDeselectPluginsOnExecuteEnabled()) {
        deselectAllPlugins();
    }
}
Also used : Graph(au.gov.asd.tac.constellation.graph.Graph) WaitForQueriesToCompleteTask(au.gov.asd.tac.constellation.views.dataaccess.tasks.WaitForQueriesToCompleteTask) Tab(javafx.scene.control.Tab) PluginGraphs(au.gov.asd.tac.constellation.plugins.PluginGraphs) PluginInteraction(au.gov.asd.tac.constellation.plugins.PluginInteraction) SimplePlugin(au.gov.asd.tac.constellation.plugins.templates.SimplePlugin) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) NewDefaultSchemaGraphAction(au.gov.asd.tac.constellation.graph.node.create.NewDefaultSchemaGraphAction) PluginParameters(au.gov.asd.tac.constellation.plugins.parameters.PluginParameters) File(java.io.File)

Aggregations

Graph (au.gov.asd.tac.constellation.graph.Graph)211 ReadableGraph (au.gov.asd.tac.constellation.graph.ReadableGraph)86 Test (org.testng.annotations.Test)65 PluginParameters (au.gov.asd.tac.constellation.plugins.parameters.PluginParameters)40 WritableGraph (au.gov.asd.tac.constellation.graph.WritableGraph)36 ArrayList (java.util.ArrayList)32 Plugin (au.gov.asd.tac.constellation.plugins.Plugin)31 PluginException (au.gov.asd.tac.constellation.plugins.PluginException)30 StoreGraph (au.gov.asd.tac.constellation.graph.StoreGraph)26 DualGraph (au.gov.asd.tac.constellation.graph.locking.DualGraph)26 TableViewState (au.gov.asd.tac.constellation.views.tableview.state.TableViewState)21 List (java.util.List)21 ExecutionException (java.util.concurrent.ExecutionException)21 PluginExecution (au.gov.asd.tac.constellation.plugins.PluginExecution)20 PluginInteraction (au.gov.asd.tac.constellation.plugins.PluginInteraction)20 IOException (java.io.IOException)20 Schema (au.gov.asd.tac.constellation.graph.schema.Schema)17 VisualConcept (au.gov.asd.tac.constellation.graph.schema.visual.concept.VisualConcept)17 File (java.io.File)17 GraphElementType (au.gov.asd.tac.constellation.graph.GraphElementType)16