I want to define a custom edge
public class Connection extends DefaultWeightedEdge
But when I try to use the super()
is that possible? What should I use for EdgeFactory when creating a graph?
new SimpleWeightedGraph<Sensor, Connection>(EdgeFactory.class);
Would this be sufficient? Or should I create a new class who extends EdgeFactory
as well?
You do not require to subclass DefaultWeightedEdge
to create your custom edge, the following works also. I'm currently using version 0.9.0 of JGraphT.
Class definition :
public class Connection {
// class implementation
// define all constructors and methods you need
}
Graph creation :
SimpleWeightedGraph<Sensor, Connection> graph;
graph = new SimpleWeightedGraph<Sensor, Connection>(Connection.class);
Adding custom edge and setting weight :
Sensor v1 = // sensor instance
Sensor v2 = // another sensor instance
graph.addVertex(v1);
graph.addVertex(v2);
Connection connection = new Connection(/* ... */);
graph.addEdge(v1, v2, connection);
graph.setEdgeWeight(connection, 10.0);
Also consider to implement equals
and hashCode
methods of your Connection
class, as JGraphT relies on those methods since version 0.8.4, see EqualsAndHashCode article. This article also provides an example where DefaultWeightedEdge
is subclassed.
Does this help you in creating custom edges ?
This particular example is drawn from the JGrapht internal documentation . Search for StoerWagnerMinimumCut algorithm inside the code base .
Here we go .
The idea here is to give some weights to the edges of the graph hence the need to manipulate the default weights.
final WeightedGraph<Set<V>, DefaultWeightedEdge> workingGraph;
....
workingGraph =
new SimpleWeightedGraph<Set<V>, DefaultWeightedEdge>(
DefaultWeightedEdge.class);
list = ....
workingGraph.addVertex(list);
....
// Lets manipulate the edge weights now
DefaultWeightedEdge eNew = workingGraph.getEdge(someSourcEdge, someTargetEdge);
if (eNew == null) {
eNew = workingGraph.addEdge(someSourcEdge, someTargetEdge);
workingGraph.setEdgeWeight(eNew, graph.getEdgeWeight(e));
} else {
workingGraph.setEdgeWeight(
eNew,
workingGraph.getEdgeWeight(eNew) + graph.getEdgeWeight(e));
I hope you can play around with the example and use it to create customized edges .
PS :
My answer my not be 100% correct but the idea is to point you to the correct direction in the docmentation :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With