Draw a JUNG graph having more than two vertices between a pair of nodes - jung

Ok so here is a clearer explanation :
I have now understood that I need to use sparse ou SparseMultigraph type to be able to have bidirectional edges so I have changed my GraphML class as such :
class GraphML
{
public GraphML(String filename) throws ParserConfigurationException, SAXException, IOException
{
//Step 1 we make a new GraphML Reader. We want a directed Graph of type node and edge.
GraphMLReader<SparseMultigraph<node, edge>, node, edge> gmlr =
new GraphMLReader<SparseMultigraph<node, edge>, node, edge>(new VertexFactory(), new EdgeFactory());
//Next we need a Graph to store the data that we are reading in from GraphML. This is also a directed Graph
// because it needs to match to the type of graph we are reading in.
final SparseMultigraph<node, edge> graph = new SparseMultigraph<node, edge>();
gmlr.load(filename, graph);
// gmlr.load(filename, graph); //Here we read in our graph. filename is our .graphml file, and graph is where we
// will store our graph.
BidiMap<node, String> vertex_ids = gmlr.getVertexIDs(); //The vertexIDs are stored in a BidiMap.
Map<String, GraphMLMetadata<node>> vertex_color = gmlr.getVertexMetadata(); //Our vertex Metadata is stored in a map.
Map<String, GraphMLMetadata<edge>> edge_meta = gmlr.getEdgeMetadata(); // Our edge Metadata is stored in a map.
// Here we iterate through our vertices, n, and we set the value and the color of our nodes from the data we have
// in the vertex_ids map and vertex_color map.
for (node n : graph.getVertices())
{
n.setValue(vertex_ids.get(n)); //Set the value of the node to the vertex_id which was read in from the GraphML Reader.
n.setColor(vertex_color.get("d0").transformer.transform(n)); // Set the color, which we get from the Map, vertex_color.
//Let's print out the data so we can get a good understanding of what we've got going on.
System.out.println("ID: "+n.getID()+", Value: "+n.getValue()+", Color: "+n.getColor());
}
// Just as we added the vertices to the graph, we add the edges as well.
for (edge e : graph.getEdges())
{
e.setValue(edge_meta.get("d1").transformer.transform(e)); //Set the edge's value.
System.out.println("Edge ID: "+e.getID());
}
TreeBuilder treeBuilder = new TreeBuilder(graph);
// create a simple graph for the demo:
//First we make a VisualizationViewer, of type node, edge. We give it our Layout, and the Layout takes a graph in it's constructor.
//VisualizationViewer<node, edge> vv = new VisualizationViewer<node, edge>(new FRLayout<node, edge>(graph));
VisualizationViewer<node, edge> vv = new VisualizationViewer<node, edge>(new TreeLayout<node, edge>(treeBuilder.getTree()));
//Next we set some rendering properties. First we want to color the vertices, so we provide our own vertexPainter.
vv.getRenderContext().setVertexFillPaintTransformer(new vertexPainter());
//Then we want to provide labels to our nodes, Jung provides a nice function which makes the graph use a vertex's ToString function
//as it's way of labelling. We do the same for the edge. Look at the edge and node classes for their ToString function.
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<node>());
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller<edge>());
// Next we do some Java stuff, we create a frame to hold the graph
final JFrame frame = new JFrame();
frame.setTitle("GraphMLReader for Trees - Reading in Attributes"); //Set the title of our window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Give a close operation.
//Here we get the contentPane of our frame and add our a VisualizationViewer, vv.
frame.getContentPane().add(vv);
//Finally, we pack it to make sure it is pretty, and set the frame visible. Voila.
frame.pack();
frame.setVisible(true);
}
}
And then changed my tree builder class constructor to SparseMultigraph :
public class TreeBuilder
{
DelegateForest<node,edge> mTree;
TreeBuilder(SparseMultigraph<node, edge> graph)
{
mTree = new DelegateForest<node, edge>();
for (node n : graph.getVertices())
{
mTree.addVertex(n);
}
for (edge e : graph.getEdges())
{
mTree.addEdge(e, graph.getSource(e),graph.getDest(e));
}
}
public DelegateForest<node, edge> getTree()
{
return mTree;
}
}
when I run my Main class :
public class Main
{
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException
{
String filename = "attributes.graphml";
if(args.length > 0)
filename = args[0];
new GraphML(filename);
}
}
I don't get an error but edges are not present (node are their in the graph but not properly displayed).
Thanks
Zied

Related

Accord.NET Comparing two images to determine similarity

I would like your advice as to why the code might be becoming unresponsive and how to fix it.
I am using Accord.NET to compare images. The first stage of my project is to compare two images, an observed image and a model image, and determine how similar they are; the second, is to compare an observed image against my whole database to determine what the observed image most likely is based on how the models have been categorized. Right now I am focusing on the first. I initially tried using ExhaustiveTemplateMatching.ProcessImage() but it didn't fit my need. Now, I am using SURF. Here is my code as is:
public class ProcessImage
{
public static void Similarity(System.IO.Stream model, System.IO.Stream observed,
out float similPercent)
{
Bitmap bitModel = new Bitmap(model);
Bitmap bitObserved = new Bitmap(observed);
// For method Difference, see http://www.aforgenet.com/framework/docs/html/673023f7-799a-2ef6-7933-31ef09974dde.htm
// Inspiration for this process: https://www.youtube.com/watch?v=YHT46f2244E
// Greyscale class http://www.aforgenet.com/framework/docs/html/d7196dc6-8176-4344-a505-e7ade35c1741.htm
// Convert model and observed to greyscale
Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
// apply the filter to the model
Bitmap greyModel = filter.Apply(bitModel);
// Apply the filter to the observed image
Bitmap greyObserved = filter.Apply(bitObserved);
int modelPoints = 0, matchingPoints = 0;
/*
* This doesn't work. Images can have different sizes
// For an example, https://thecsharper.com/?p=94
// Match
var tm = new ExhaustiveTemplateMatching(similarityThreshold);
// Process the images
var results = tm.ProcessImage(greyModel, greyObserved);
*/
using (SpeededUpRobustFeaturesDetector detector = new SpeededUpRobustFeaturesDetector())
{
List<SpeededUpRobustFeaturePoint> surfModel = detector.ProcessImage(greyModel);
modelPoints = surfModel.Count();
List<SpeededUpRobustFeaturePoint> surfObserved = detector.ProcessImage(greyObserved);
KNearestNeighborMatching matcher = new KNearestNeighborMatching(5);
var results = matcher.Match(surfModel, surfObserved);
matchingPoints = results.Length;
}
// Determine if they represent the same points
// Obtain the pairs of associated points, we determine the homography matching all these pairs
// Compare the results, 0 indicates no match so return false
if (matchingPoints <= 0)
{
similPercent = 0.0f;
}
similPercent = (matchingPoints * 100) / modelPoints;
}
}
So far I get to obtain the list of points but then when matching the code seems to become unresponsive.
I am calling the above code from an ASP.NET web page after the user posts a bitmap. Here is the code if it may help:
public ActionResult Compare(int id)
{
ViewData["SampleID"] = id;
return View();
}
[HttpPost]
public ActionResult Compare(int id, HttpPostedFileBase uploadFile)
{
Sample model = _db.Sample_Read(id);
System.IO.Stream modelStream = null;
float result = 0;
_db.Sample_Stream(model.FileId, out modelStream);
ImgProc.ProcessImage.Similarity(modelStream, uploadFile.InputStream,
out result);
ViewData["SampleID"] = id;
ViewData["match"] = result;
return View();
}
The page itself is rather simple, a hidden field, an file type input and a submit.
Problem was my PC. After some time processing the calculation finishes.
Thanks,
For KNearestNeighborMatching to decide, it is necessary to put
Accord.Imaging and Accord.Vision.

How do I make View's asList() sortable in Google Dataflow SDK?

We have a problem making asList() method sortable.
We thought we could do this by just extending the View class and override the asList method but realized that View class has a private constructor so we could not do this.
Our other attempt was to fork the Google Dataflow code on github and modify the PCollectionViews class to return a sorted list be using the Collections.sort method as shown in the code snippet below
#Override
protected List<T> fromElements(Iterable<WindowedValue<T>> contents) {
Iterable<T> itr = Iterables.transform(
contents,
new Function<WindowedValue<T>, T>() {
#SuppressWarnings("unchecked")
#Override
public T apply(WindowedValue<T> input){
return input.getValue();
}
});
LOG.info("#### About to start sorting the list !");
List<T> tempList = new ArrayList<T>();
for (T element : itr) {
tempList.add(element);
};
Collections.sort((List<? extends Comparable>) tempList);
LOG.info("##### List should now be sorted !");
return ImmutableList.copyOf(tempList);
}
Note that we are now sorting the list.
This seemed to work, when run with the DirectPipelineRunner but when we tried the BlockingDataflowPipelineRunner, it didn't seem like the code change was being executed.
Note: We actually recompiled the dataflow used it in our project but this did not work.
How can we be able to achieve this (as sorted list from the asList method call)?
The classes in PCollectionViews are not intended for extension. Only the primitive view types provided by View.asSingleton, View.asSingleton View.asIterable, View.asMap, and View.asMultimap are supported.
To obtain a sorted list from a PCollectionView, you'll need to sort it after you have read it. The following code demonstrates the pattern.
// Assume you have some PCollection
PCollection<MyComparable> myPC = ...;
// Prepare it for side input as a list
final PCollectionView<List<MyComparable> myView = myPC.apply(View.asList());
// Side input the list and sort it
someOtherValue.apply(
ParDo.withSideInputs(myView).of(
new DoFn<A, B>() {
#Override
public void processElement(ProcessContext ctx) {
List<MyComparable> tempList =
Lists.newArrayList(ctx.sideInput(myView));
Collections.sort(tempList);
// do whatever you want with sorted list
}
}));
Of course, you may not want to sort it repeatedly, depending on the cost of sorting vs the cost of materializing it as a new PCollection, so you can output this value and read it as a new side input without difficulty:
// Side input the list, sort it, and put it in a PCollection
PCollection<List<MyComparable>> sortedSingleton = Create.<Void>of(null).apply(
ParDo.withSideInputs(myView).of(
new DoFn<Void, B>() {
#Override
public void processElement(ProcessContext ctx) {
List<MyComparable> tempList =
Lists.newArrayList(ctx.sideInput(myView));
Collections.sort(tempList);
ctx.output(tempList);
}
}));
// Prepare it for side input as a list
final PCollectionView<List<MyComparable>> sortedView =
sortedSingleton.apply(View.asSingleton());
someOtherValue.apply(
ParDo.withSideInputs(sortedView).of(
new DoFn<A, B>() {
#Override
public void processElement(ProcessContext ctx) {
... ctx.sideInput(sortedView) ...
// do whatever you want with sorted list
}
}));
You may also be interested in the unsupported sorter contrib module for doing larger sorts using both memory and local disk.
We tried to do it the way Ken Knowles suggested. There's a problem for large datasets. If the tempList is large (so sort takes some measurable time as it's proportion to O(n * log n)) and if there are millions of elements in the "someOtherValue" PCollection, then we are unecessarily re-sorting the same list millions of times. We should be able to sort ONCE and FIRST, before passing the list to the someOtherValue.apply's DoFn.

How to get List & Hierarchy of Linked and sub-linked Revit files

We're trying to get the list and hierarchy of all linked external files. Right now we tried the following code:
FilteredElementCollector collectorI = new FilteredElementCollector(DocChild);
IList<Element> elemsI = collectorI.OfCategory(BuiltInCategory.OST_RvtLinks).OfClass(typeof(RevitLinkInstance)).ToElements();
foreach (Element eI in elemsI)
{
if (eI is RevitLinkInstance)
{
RevitLinkInstance InstanceType = eI as RevitLinkInstance;
RevitLinkType type = DocChild.GetElement(InstanceType.GetTypeId()) as RevitLinkType;
TaskDialog.Show("Debug", "IsNestedLink=" + type.IsNestedLink.ToString() + " IsLinked=" + DocChild.IsLinked.ToString());
if (!type.IsNestedLink)
{
TaskDialog.Show("Debug", "Children=" + InstanceType.GetLinkDocument().PathName.ToString());
}
}
}
We succeed to get the list of all linked files but there's no hierarchy. We don't know which file is a children of which parent.
This is the Link structure we're trying to get:
enter image description here
You need to play with GetParentId and GetChilds methods to read the hierarchy. Here is a code:
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
// get active document
Document mainDoc = commandData.Application.ActiveUIDocument.Document;
// prepare to show the results...
TreeNode mainNode = new TreeNode();
mainNode.Text = mainDoc.PathName;
// start by the root links (no parent node)
FilteredElementCollector coll = new FilteredElementCollector(mainDoc);
coll.OfClass(typeof(RevitLinkInstance));
foreach (RevitLinkInstance inst in coll)
{
RevitLinkType type = mainDoc.GetElement(inst.GetTypeId()) as RevitLinkType;
if (type.GetParentId() == ElementId.InvalidElementId)
{
TreeNode parentNode = new TreeNode(inst.Name);
mainNode.Nodes.Add(parentNode);
GetChilds(mainDoc, type.GetChildIds(), parentNode);
}
}
// show the results in a form
System.Windows.Forms.Form resultForm = new System.Windows.Forms.Form();
TreeView treeView = new TreeView();
treeView.Size = resultForm.Size;
treeView.Anchor |= AnchorStyles.Bottom | AnchorStyles.Top;
treeView.Nodes.Add(mainNode);
resultForm.Controls.Add(treeView);
resultForm.ShowDialog();
return Result.Succeeded;
}
private void GetChilds(Document mainDoc, ICollection<ElementId> ids,
TreeNode parentNode)
{
foreach (ElementId id in ids)
{
// get the child information
RevitLinkType type = mainDoc.GetElement(id) as RevitLinkType;
TreeNode subNode = new TreeNode(type.Name);
parentNode.Nodes.Add(subNode);
// then go to the next level
GetChilds(mainDoc, type.GetChildIds(), subNode);
}
}
And the result should look like:
Original source blog post.
Thank you for the great answer. It helped foxing a big part of my problem but I just have a remaining issue which is: how to get the full path name of all instances. In some cases the same file is re-used two time in the Revit Link Hierarchy.
Regards

How do you add nodes to a linear linked list? [java]

So basically, while I'm not new to this, I've somewhat forgotten the set up for adding nodes to a linear linked list. Basically, I have a cap for the number of nodes that I can add, and currently, I have:
"storage" is a binary tree with ONLY next nodes.
private void addToStorage(Node node){
if(storage.size() <= maxSize) // Current Size of storage
{
node.data = null;
node.prev = null;
node.next = storage;
storage = node;
}
}
Is this the correct way to implement this function? If not, how should I go about doing it using a similar method?
Considering that you are able to retrieve the last node stored somewhere inside that storage object or from somewere else:
add(Node node) {
if(prevNode != null)
prevNode.next = node;
node.prev = prevNode;
node.next = null;
}
Also, there's no point of nulling the data since it's usually set before calling add.

Return JSONObject from server plugin in neo4j

I am attempting to create a server plugin in neo4j to make a specific query and wish to return, not one iterable, but two iterables of Node.
I saw that this is not possible according to the neo4j docs, so I tried to create an array of JSONObject from these arrays and then return it as server plugin result. But it seems that this does not work.
So I am asking if someone has already done such thing?
I have been told on neo4j google group to use Gremlin, but have never use it before and think it is a bit complicated.
Any help would be very appreciated.
Thanks
i eventually got around the problem by merging the two lists i wanted to return before returning a unique list. Hence i could separate them in my python code, since i know where starts each one.
public class Ond extends ServerPlugin {
#PluginTarget(GraphDatabaseService.class)
public static Iterable<Node> getOnd(
#Source GraphDatabaseService graphDb,
#Description("the airline's node ID") #Parameter(name = "id") int id) {
List<Node> results= new ArrayList<Node>();
String n4jQuery= "START al= node("+id+") match ond-[:operatedBy]->al, ond-[:origin]->orig, ond-[:destination]->dest RETURN orig, dest ;";
ExecutionEngine engine= new ExecutionEngine(graphDb);
ExecutionResult result= engine.execute(n4jQuery);
List<Node> orig= new ArrayList<Node>();
List<Node> dest= new ArrayList<Node>();
//creating the lists i want to return
//an outter loop over tables rows
for (Map<String, Object> row : result) {
//an inner loop over the two columns : orig and dest
for (Map.Entry<String, Object> column : row.entrySet()) {
String key = column.getKey();
Node n = (Node) column.getValue();
if(key.equals("dest")){
dest.add(n);
}else{
orig.add(n);
}
}
}
//merging the two lists
results.addAll(orig);
results.addAll(dest);
// orig elements are between indices 0 and size(results)/2 -1
//and dest element are between size(results)/2 and size(results)-1
return results;
}
}
Hope it helps !!

Resources