Search in sources :

Example 11 with Tuple

use of au.gov.asd.tac.constellation.utilities.datastructure.Tuple in project constellation by constellation-app.

the class InfomapGreedy method consolidateModules.

@Override
protected int consolidateModules(final boolean replaceExistingStructure, final boolean asSubModules) {
    if (DEBUG) {
        final String log = String.format("%s.consolidateModules(%s,%s)%n", getClass().getSimpleName(), replaceExistingStructure, asSubModules);
        LOGGER.log(Level.INFO, log);
    }
    final int numNodes = activeNetwork.size();
    final NodeBase[] modules = new NodeBase[numNodes];
    final boolean activeNetworkAlreadyHaveModuleLevel = activeNetwork.get(0).getParent() != getRoot();
    final boolean activeNetworkIsLeafNetwork = activeNetwork.get(0).isLeaf();
    if (asSubModules) {
        assert activeNetworkAlreadyHaveModuleLevel;
        // Release the pointers from modules to leaf nodes so that the new submodules will be inserted as its only children.
        for (final NodeBase module : getRoot().getChildren()) {
            module.releaseChildren();
        }
    } else {
        // Happens after optimizing fine-tune and when moving leaf nodes to super clusters.
        if (activeNetworkAlreadyHaveModuleLevel) {
            if (DEBUG) {
                final String log = String.format("Replace existing %d modules with its children before consolidating the %d dynamic modules...\n", getNumTopModules(), getNumActiveModules());
                LOGGER.log(Level.INFO, log);
            }
            getRoot().replaceChildrenWithGrandChildren();
            assert activeNetwork.get(0).getParent() == getRoot();
        }
        getRoot().releaseChildren();
    }
    // Create the new module nodes and re-parent the active network from its common parent to the new module level.
    for (int i = 0; i < numNodes; ++i) {
        final NodeBase node = activeNetwork.get(i);
        final int moduleIndex = node.getIndex();
        if (modules[moduleIndex] == null) {
            modules[moduleIndex] = treeData.getNodeFactory().createNode(moduleFlowData[moduleIndex]);
            node.getParent().addChild(modules[moduleIndex]);
            modules[moduleIndex].setIndex(moduleIndex);
        }
        modules[moduleIndex].addChild(node);
    }
    if (asSubModules) {
        if (DEBUG) {
            final String log = String.format("Consolidated %d submodules under %d modules, store module structure before releasing it...\n", getNumActiveModules(), getNumTopModules());
            LOGGER.log(Level.INFO, log);
        }
        // Store the module structure on the submodules.
        int moduleIndex = 0;
        for (final NodeBase module : getRoot().getChildren()) {
            for (final NodeBase subModule : module.getChildren()) {
                subModule.setIndex(moduleIndex);
            }
            moduleIndex++;
        }
        if (replaceExistingStructure) {
            // Remove the module level.
            getRoot().replaceChildrenWithGrandChildren();
        }
    }
    // Aggregate links from lower level to the new modular level
    /*
         typedef std::pair<NodeBase*, NodeBase*> NodePair
         typedef std::map<NodePair, double> EdgeMap
         EdgeMap moduleLinks
         */
    final Map<Tuple<NodeBase, NodeBase>, Double> moduleLinks = new TreeMap<>((lhs, rhs) -> {
        if (lhs.getFirst().getId() < rhs.getFirst().getId()) {
            return -1;
        }
        if (lhs.getFirst().getId() > rhs.getFirst().getId()) {
            return 1;
        }
        if (lhs.getSecond().getId() < rhs.getSecond().getId()) {
            return -1;
        }
        if (lhs.getSecond().getId() > rhs.getSecond().getId()) {
            return 1;
        }
        return 0;
    });
    for (final NodeBase node : activeNetwork) {
        final NodeBase parent = node.getParent();
        for (final Edge<NodeBase> edge : node.getOutEdges()) {
            final NodeBase otherParent = edge.getTarget().getParent();
            if (otherParent != parent) {
                NodeBase m1 = parent;
                NodeBase m2 = otherParent;
                // If undirected, the order may be swapped to aggregate the edge on an opposite one.
                if (config.isUndirected() && m1.getIndex() > m2.getIndex()) {
                    NodeBase t = m1;
                    m1 = m2;
                    m2 = t;
                }
                // Insert the node pair in the edge map.
                // If not inserted, add the flow value to existing node pair.
                final Tuple<NodeBase, NodeBase> key = Tuple.create(m1, m2);
                if (moduleLinks.containsKey(key)) {
                    final double d = moduleLinks.get(key);
                    moduleLinks.put(key, d + edge.getData().flow);
                } else {
                    moduleLinks.put(key, edge.getData().flow);
                }
            }
        }
    }
    // Add the aggregated edge flow structure to the new modules.
    for (final Map.Entry<Tuple<NodeBase, NodeBase>, Double> entry : moduleLinks.entrySet()) {
        final Tuple<NodeBase, NodeBase> nodePair = entry.getKey();
        final double value = entry.getValue();
        nodePair.getFirst().addOutEdge(nodePair.getSecond(), 0, value);
    }
    // Replace active network with its children if not at leaf level.
    if (!activeNetworkIsLeafNetwork && replaceExistingStructure) {
        for (final NodeBase node : activeNetwork) {
            node.replaceWithChildren();
        }
    }
    // Calculate the number of non-trivial modules.
    numNonTrivialTopModules = 0;
    for (final NodeBase module : getRoot().getChildren()) {
        if (module.getChildDegree() != 1) {
            numNonTrivialTopModules++;
        }
    }
    return getNumActiveModules();
}
Also used : TreeMap(java.util.TreeMap) NodeBase(au.gov.asd.tac.constellation.plugins.algorithms.clustering.infomap.NodeBase) MultiMap(au.gov.asd.tac.constellation.plugins.algorithms.clustering.infomap.util.MultiMap) TreeMap(java.util.TreeMap) Map(java.util.Map) Tuple(au.gov.asd.tac.constellation.utilities.datastructure.Tuple)

Example 12 with Tuple

use of au.gov.asd.tac.constellation.utilities.datastructure.Tuple in project constellation by constellation-app.

the class LevenshteinDistancePlugin method edit.

@Override
public void edit(final GraphWriteMethods graph, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException {
    final String compareAttribute = parameters.getStringValue(ATTRIBUTE_PARAMETER_ID);
    final int maxDistance = parameters.getIntegerValue(MAXIMUM_DISTANCE_PARAMETER_ID);
    final boolean caseInsensitive = parameters.getBooleanValue(CASE_INSENSITIVE_PARAMETER_ID);
    final boolean selectedOnly = parameters.getBooleanValue(SELECTED_ONLY_PARAMETER_ID);
    final int vertexSelectedAttributeId = VisualConcept.VertexAttribute.SELECTED.get(graph);
    final int vertexCompareAttributeId = graph.getAttribute(GraphElementType.VERTEX, compareAttribute);
    if (vertexCompareAttributeId == Graph.NOT_FOUND) {
        final NotifyDescriptor nd = new NotifyDescriptor.Message(String.format("The specified attribute %s does not exist on the graph.", compareAttribute), NotifyDescriptor.WARNING_MESSAGE);
        DialogDisplayer.getDefault().notify(nd);
        return;
    }
    final Map<Tuple<Integer, Integer>, Integer> distances = new HashMap<>();
    // compare each pair of vertices
    final int vertexCount = graph.getVertexCount();
    for (int one = 0; one < vertexCount; one++) {
        final int vxOneId = graph.getVertex(one);
        if (selectedOnly && !graph.getBooleanValue(vertexSelectedAttributeId, vxOneId)) {
            continue;
        }
        for (int two = one + 1; two < vertexCount; two++) {
            final int vxTwoId = graph.getVertex(two);
            if (selectedOnly && !graph.getBooleanValue(vertexSelectedAttributeId, vxTwoId)) {
                continue;
            }
            String stringOne = graph.getStringValue(vertexCompareAttributeId, vxOneId);
            String stringTwo = graph.getStringValue(vertexCompareAttributeId, vxTwoId);
            if (StringUtils.isBlank(stringOne) || StringUtils.isBlank(stringTwo) || Math.abs(stringOne.length() - stringTwo.length()) > maxDistance) {
                continue;
            }
            if (caseInsensitive) {
                stringOne = stringOne.toLowerCase();
                stringTwo = stringTwo.toLowerCase();
            }
            if (stringOne.equals(stringTwo)) {
                distances.put(Tuple.create(vxOneId, vxTwoId), 0);
                continue;
            }
            final LevenshteinDistanceFunction ldf = new LevenshteinDistanceFunction(maxDistance);
            final double distance = ldf.getDistance(stringOne, stringTwo);
            if (distance > maxDistance) {
                continue;
            }
            SimilarityUtilities.setGraphAndEnsureAttributes(graph, LEVENSHTEIN_DISTANCE_ATTRIBUTE);
            SimilarityUtilities.addScoreToGraph(vxOneId, vxTwoId, (float) distance);
        }
    }
    // complete with schema
    PluginExecution.withPlugin(VisualSchemaPluginRegistry.COMPLETE_SCHEMA).executeNow(graph);
}
Also used : NotifyDescriptor(org.openide.NotifyDescriptor) HashMap(java.util.HashMap) Tuple(au.gov.asd.tac.constellation.utilities.datastructure.Tuple)

Example 13 with Tuple

use of au.gov.asd.tac.constellation.utilities.datastructure.Tuple in project constellation by constellation-app.

the class TableViewTopComponent method handleNewGraph.

/**
 * Update the current state with the new state pulled from the passed
 * graph's attributes and update the attribute handlers so that the table is
 * only notified for attribute changes that it cares about. Then trigger a
 * table refresh using the new graph as its source of truth.
 *
 * @param graph the new graph
 */
@Override
protected void handleNewGraph(final Graph graph) {
    if (!needsUpdate()) {
        return;
    }
    // Take a copy of the current state that is associated with the current graph
    final TableViewState previousState = currentState;
    // Update the current state by pulling the table state attribute from
    // the new graph
    updateState(graph);
    // Determine the visible column changes
    final Set<Tuple<String, Attribute>> removedColumnAttributes = getRemovedAttributes(previousState, currentState);
    final Set<Tuple<String, Attribute>> addedColumnAttributes = getAddedAttributes(previousState, currentState);
    // with the state associated with the new graph
    if (columnAttributeMonitors != null && !removedColumnAttributes.isEmpty()) {
        final Set<AttributeValueMonitor> removeMonitors = columnAttributeMonitors.stream().filter(monitor -> removedColumnAttributes.stream().anyMatch(columnAttributeTuple -> columnAttributeTuple.getSecond().getElementType() == monitor.getElementType() && columnAttributeTuple.getSecond().getName().equals(monitor.getName()))).collect(Collectors.toSet());
        removeMonitors.forEach(monitor -> {
            removeAttributeValueChangeHandler(monitor);
            columnAttributeMonitors.remove(monitor);
        });
    }
    // Update the table data, columns and selection with the new graph
    pane.updateTable(graph, currentState);
    // the table should have its data refreshed
    if (currentState != null && currentState.getColumnAttributes() != null && !addedColumnAttributes.isEmpty()) {
        addedColumnAttributes.forEach(attributeTuple -> columnAttributeMonitors.add(addAttributeValueChangeHandler(attributeTuple.getSecond().getElementType(), attributeTuple.getSecond().getName(), g -> executorService.submit(new TriggerDataUpdateTask(pane, g, getCurrentState())))));
    }
}
Also used : TopComponent(org.openide.windows.TopComponent) Tuple(au.gov.asd.tac.constellation.utilities.datastructure.Tuple) ActionID(org.openide.awt.ActionID) ReadableGraph(au.gov.asd.tac.constellation.graph.ReadableGraph) ActionReference(org.openide.awt.ActionReference) VisualConcept(au.gov.asd.tac.constellation.graph.schema.visual.concept.VisualConcept) TriggerSelectionUpdateTask(au.gov.asd.tac.constellation.views.tableview.tasks.TriggerSelectionUpdateTask) CollectionUtils(org.apache.commons.collections4.CollectionUtils) Graph(au.gov.asd.tac.constellation.graph.Graph) HashSet(java.util.HashSet) Future(java.util.concurrent.Future) TableViewState(au.gov.asd.tac.constellation.views.tableview.state.TableViewState) TableViewConcept(au.gov.asd.tac.constellation.views.tableview.state.TableViewConcept) SelectionToGraphPlugin(au.gov.asd.tac.constellation.views.tableview.plugins.SelectionToGraphPlugin) Attribute(au.gov.asd.tac.constellation.graph.Attribute) PluginExecution(au.gov.asd.tac.constellation.plugins.PluginExecution) ExecutorService(java.util.concurrent.ExecutorService) GraphManager(au.gov.asd.tac.constellation.graph.manager.GraphManager) AttributeValueMonitor(au.gov.asd.tac.constellation.graph.monitor.AttributeValueMonitor) TablePane(au.gov.asd.tac.constellation.views.tableview.panes.TablePane) TriggerDataUpdateTask(au.gov.asd.tac.constellation.views.tableview.tasks.TriggerDataUpdateTask) GraphElementType(au.gov.asd.tac.constellation.graph.GraphElementType) Set(java.util.Set) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) ExecutionException(java.util.concurrent.ExecutionException) ActionReferences(org.openide.awt.ActionReferences) UpdateStatePlugin(au.gov.asd.tac.constellation.views.tableview.plugins.UpdateStatePlugin) Messages(org.openide.util.NbBundle.Messages) JavaFxTopComponent(au.gov.asd.tac.constellation.views.JavaFxTopComponent) TriggerDataUpdateTask(au.gov.asd.tac.constellation.views.tableview.tasks.TriggerDataUpdateTask) TableViewState(au.gov.asd.tac.constellation.views.tableview.state.TableViewState) AttributeValueMonitor(au.gov.asd.tac.constellation.graph.monitor.AttributeValueMonitor) Tuple(au.gov.asd.tac.constellation.utilities.datastructure.Tuple)

Example 14 with Tuple

use of au.gov.asd.tac.constellation.utilities.datastructure.Tuple in project constellation by constellation-app.

the class ActiveTableReference method updateVisibleColumns.

/**
 * Updates the visible columns in the table's state. Once the new state is
 * determined the it is updated in the graph.
 * <p/>
 * The following are the different ways in which the visible columns can be
 * updated
 * <ul>
 * <li>
 * <b>ADD:</b> the passed columns are added on top of existing visible
 * columns in the current state.
 * </li>
 * <li>
 * <b>REMOVE:</b> the passed columns are removed from the visible columns in
 * the current state.
 * </li>
 * <li>
 * <b>REPLACE:</b> the passed columns become the new visible columns
 * </li>
 * </ul>
 *
 * @param graph the graph to update with the new state
 * @param state the current table state
 * @param columnAttributes the column attributes to update the state with
 * @param updateState the manner in which the state will be updated with the
 * column attributes
 * @return a {@link Future<?>} object of the plugin execution.
 */
public Future<?> updateVisibleColumns(final Graph graph, final TableViewState state, final List<Tuple<String, Attribute>> columnAttributes, final UpdateMethod updateState) {
    if (graph != null && state != null) {
        final TableViewState newState = new TableViewState(state);
        final List<Tuple<String, Attribute>> newColumnAttributes = new ArrayList<>();
        switch(updateState) {
            case ADD:
                if (newState.getColumnAttributes() != null) {
                    newColumnAttributes.addAll(newState.getColumnAttributes());
                }
                newColumnAttributes.addAll(columnAttributes);
                break;
            case REMOVE:
                if (newState.getColumnAttributes() != null) {
                    newColumnAttributes.addAll(newState.getColumnAttributes());
                }
                newColumnAttributes.removeAll(columnAttributes);
                break;
            case REPLACE:
                newColumnAttributes.addAll(columnAttributes);
                break;
        }
        newState.setColumnAttributes(newColumnAttributes);
        return PluginExecution.withPlugin(new UpdateStatePlugin(newState)).executeLater(graph);
    }
    return CompletableFuture.completedFuture(null);
}
Also used : TableViewState(au.gov.asd.tac.constellation.views.tableview.state.TableViewState) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) UpdateStatePlugin(au.gov.asd.tac.constellation.views.tableview.plugins.UpdateStatePlugin) Tuple(au.gov.asd.tac.constellation.utilities.datastructure.Tuple)

Example 15 with Tuple

use of au.gov.asd.tac.constellation.utilities.datastructure.Tuple in project constellation by constellation-app.

the class TableViewStateIoProvider method readObject.

@Override
public void readObject(final int attributeId, final int elementId, final JsonNode jnode, final GraphWriteMethods graph, final Map<Integer, Integer> vertexMap, final Map<Integer, Integer> transactionMap, final GraphByteReader byteReader, final ImmutableObjectCache cache) throws IOException {
    if (!jnode.isNull() && !jnode.isEmpty()) {
        final boolean selectedOnly = jnode.get("selectedOnly").asBoolean();
        final GraphElementType elementType = GraphElementType.valueOf(jnode.get("elementType").asText());
        final List<Tuple<String, Attribute>> transactionColumnAttributes = new ArrayList<>();
        if (jnode.get(TRANSACTION_COLUMN_ATTRIBUTES) != null) {
            final Iterator<JsonNode> attributeIterator = jnode.get(TRANSACTION_COLUMN_ATTRIBUTES).iterator();
            while (attributeIterator.hasNext()) {
                final JsonNode attributeNode = attributeIterator.next();
                final String attributePrefix = attributeNode.get(ATTRIBUTE_PREFIX).asText();
                final Attribute attribute = new GraphAttribute(graph, graph.getAttribute(GraphElementType.valueOf(attributeNode.get(ATTRIBUTE_ELEMENT_TYPE).asText()), attributeNode.get(ATTRIBUTE_NAME).asText()));
                transactionColumnAttributes.add(Tuple.create(attributePrefix, attribute));
            }
        }
        final List<Tuple<String, Attribute>> vertexColumnAttributes = new ArrayList<>();
        if (jnode.get(VERTEX_COLUMN_ATTRIBUTES) != null) {
            final Iterator<JsonNode> attributeIterator = jnode.get(VERTEX_COLUMN_ATTRIBUTES).iterator();
            while (attributeIterator.hasNext()) {
                final JsonNode attributeNode = attributeIterator.next();
                final String attributePrefix = attributeNode.get(ATTRIBUTE_PREFIX).asText();
                final Attribute attribute = new GraphAttribute(graph, graph.getAttribute(GraphElementType.valueOf(attributeNode.get(ATTRIBUTE_ELEMENT_TYPE).asText()), attributeNode.get(ATTRIBUTE_NAME).asText()));
                vertexColumnAttributes.add(Tuple.create(attributePrefix, attribute));
            }
        }
        final TableViewState state = new TableViewState();
        state.setSelectedOnly(selectedOnly);
        state.setElementType(elementType);
        state.setTransactionColumnAttributes(transactionColumnAttributes);
        state.setVertexColumnAttributes(vertexColumnAttributes);
        graph.setObjectValue(attributeId, elementId, state);
    }
}
Also used : GraphAttribute(au.gov.asd.tac.constellation.graph.GraphAttribute) Attribute(au.gov.asd.tac.constellation.graph.Attribute) TableViewState(au.gov.asd.tac.constellation.views.tableview.state.TableViewState) GraphAttribute(au.gov.asd.tac.constellation.graph.GraphAttribute) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) GraphElementType(au.gov.asd.tac.constellation.graph.GraphElementType) Tuple(au.gov.asd.tac.constellation.utilities.datastructure.Tuple)

Aggregations

Tuple (au.gov.asd.tac.constellation.utilities.datastructure.Tuple)18 ArrayList (java.util.ArrayList)7 Attribute (au.gov.asd.tac.constellation.graph.Attribute)6 Graph (au.gov.asd.tac.constellation.graph.Graph)6 PluginExecution (au.gov.asd.tac.constellation.plugins.PluginExecution)5 TableViewState (au.gov.asd.tac.constellation.views.tableview.state.TableViewState)5 ReadableGraph (au.gov.asd.tac.constellation.graph.ReadableGraph)4 Plugin (au.gov.asd.tac.constellation.plugins.Plugin)4 UpdateStatePlugin (au.gov.asd.tac.constellation.views.tableview.plugins.UpdateStatePlugin)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 AttributeValueMonitor (au.gov.asd.tac.constellation.graph.monitor.AttributeValueMonitor)3 GraphElement (au.gov.asd.tac.constellation.views.mapview.utilities.GraphElement)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 GraphElementType (au.gov.asd.tac.constellation.graph.GraphElementType)2 GraphManager (au.gov.asd.tac.constellation.graph.manager.GraphManager)2 AttributeCountMonitor (au.gov.asd.tac.constellation.graph.monitor.AttributeCountMonitor)2 GlobalMonitor (au.gov.asd.tac.constellation.graph.monitor.GlobalMonitor)2 StructureMonitor (au.gov.asd.tac.constellation.graph.monitor.StructureMonitor)2