scala: directed and undirected edges of Graphs - scala

If a directed Edge is implemented something like:
class EdgeImpl(origin: Node, dest: Node) {
def from = origin
def to = dest
}
then which is the difference for implementing an undirected Edge while when we create a new Edge we also have to say in both cases: new EdgeImpl(node1, node2)? I do not get the difference in implementation :(
Edit
I was analyzing, more concretely, this example

There is no real difference in the implementation of an Edge, in both cases just the two connected nodes need to be specified.
The difference would pop-up when you wanted to implement something else where the meaning of an edge needs interpretation. For instance, if you had a method areConnected(a: Node, b: Node): Boolean, then its implementation would traverse the list of edges and, if in a directed graph would return true if from == a && to == b. The undirected version would evaluate (from == a && to == b) || from == b && to == a) instead.
That example is kind of convoluted and does not make clear why the features described are really needed, but consider for instance how you would go creating a WeightedDirectedGraph, where each edge also contains a weight or distance between the connected nodes.

Related

ortools: best practice for partial assignments

I would like to constrain my VRP with partial assignments. Given a list of stops assigned_stops and a vehicle id I would like to find solutions such that all stops in the list are serviced by the given vehicle and in the given order.
For example, if I want to assign all stops in a list assigned_stops to the vehicle with index 5 I use the following code (Python):
vehicle_ix = 5
for stop1, stop2 in zipper(assigned_stops):
ix1 = stops.index(stop1)
ix2 = stops.index(stop2)
cpsolver.Add(routing_model.VehicleVar(ix1) == vehicle_ix)
cpsolver.Add(routing_model.VehicleVar(ix2) == vehicle_ix)
cpsolver.Add(stop_sequence_dimension.CumulVar(ix1) < stop_sequence_dimension.CumulVar(ix2))
It works. But I am only enforcing pair-wise inequalities for successive ix1, ix2. Would it help the solver if I added all possible inequality constraints?

Ullman’s Subgraph Isomorphism Algorithm

Could somebody give me a working Ullman's graph isomorphism problem implementation in MATLAB, or link to it. Or if you have at least in C so I would try to implement it in MATLAB.
Thanks
i'm lookign for it too. I've been loking in the web but with no luck so far, but i've found this:
Algorithm, where the algorithm is explained.
On another hand, i found this:
def search(graph,subgraph,assignments,possible_assignments):
update_possible_assignments(graph,subgraph,possible_assignments)
i=len(assignments)
# Make sure that every edge between assigned vertices in the subgraph is also an
# edge in the graph.
for edge in subgraph.edges:
if edge.first<i and edge.second<i:
if not graph.has_edge(assignments[edge.first],assignments[edge.second]):
return False
# If all the vertices in the subgraph are assigned, then we are done.
if i==subgraph.n_vertices:
return True
for j in possible_assignments[i]:
if j not in assignments:
assignments.append(j)
# Create a new set of possible assignments, where graph node j is the only
# possibility for the assignment of subgraph node i.
new_possible_assignments = deep_copy(possible_assignments)
new_possible_assignments[i] = [j]
if search(graph,subgraph,assignments,new_possible_assignments):
return True
assignments.pop()
possible_assignments[i].remove(j)
update_possible_assignments(graph,subgraph,possible_assignments)
def find_isomporhism(graph,subgraph):
assignments=[]
possible_assignments = [[True]*graph.n_vertices for i in range(subgraph.n_vertices)]
if search(graph,subgraph,asignments,possible_assignments):
return assignments
return None
here: implementation. I do not have the skills to transform this into Matlab, if you have them , i would really appreciate if you could share your code when you're done.

Scala - Vector.tabulate and structural sharing

Suppose I have a value representing a chess board
val board: Vector[Vector[Option[Piece]]] = ...
and in some function to apply moves I construct a new board from this one using tabulate
Vector.tabulate(8,8)(
(x,y) =>
if (x,y) == (start_x,start_y)
None
else if (x,y) == (end_x,end_y)
board(start_x)(start_y)
else
board(x)(y)
)
Would the memory usage of this snippet be constant, since only two cells are changed? In other words, is the data reused?
No, there will be no structural sharing between the new board and the old board. If you throw the old board way after this snippet, memory will be constant, but it would be more efficient to use as much of the old board as possible. Try:
val piece = board(start_x)(start_y)
val board2 = board.updated(start_x, board(start_x).updated(start_y, None))
val newboard = board2.updated(end_x, board2(end_x).updated(end_y, piece))

What is wrong with my understanding of Scala Sets?

Full disclosure: I am (was?) taking Coursera's Scala course but was stumped by the second assignment on Sets. I'm not looking for just the answers (which are easily obtainable) and would receive marginal credit anyway. But I would really like to understand what is happening.
Okay, so here is the first question: "Define a function which creates a singleton set from one integer value: the set represents the set of the one given element." So my first attempt was this:
def singletonSet(elem: Int): Set = Set(elem)
So this function, singletonSet, just returns a newly created Set. It could be invoked thusly:
val why = singletonSet(3)
// now why is a singleton set with a single integer, 3
This implementation seemed trivial, so I Googled for the answer, which seems to be this:
def singletonSet(elem: Int): Set = (x => x == elem)
Now my understanding is that (x => x == elem) is an anonymous function which takes an integer x and returns a boolean. But... what? So as a JavaScript developer, I decided to translate it:
function singletonSet(elem) {
return function(x) {
return x === elem;
};
};
So then I can write (am I currying?):
singletonSet(3)(4)
// singletonSet(3) => returns an anonymous function, function(x) { x === 3; };
// function(4) { return 4 === 3; }
// false
If this is even close to what is happening in Scala, it seems like I am not creating a singleton set. Rather, I am just checking if two numbers are the same.
What am I missing here? I feel like it must be something very basic.
Thanks in advance.
Remember this implementation of a set is a function. In particular its a boolean function, so the function can just be seen as asking the question: "Is this number in the set? - true or false." The function can be called as many times as you want, in effect asking the question multiple times:
"is this number in the set? Is that number in the set?" etc, etc.
As the set is a singleton set, there is only one number in the set. So you use the set by calling the function, asking the question, in effect, "is this number the one and only number that is in the set?" So you are correct this set, the singleton set is just asking are these two numbers the same.
It should be emphasised that this example is from the course Functional Programming Principles in Scala. The course is not meant as an easy introduction to Scala. In fact the course is deliberately making things difficult, in order to enable a deep understanding of functional programming. Normally one would just use the in scope immutable Set class.
If you wanted to work with say the even numbers between -1000 and 1000, you'd probably use an iterator like:
(-1000 to 1000).withFilter(_ %2 == 0)
or:
(-1000 to 1000 by 2)

networkx: efficiently find absolute longest path in digraph

I want networkx to find the absolute longest path in my directed,
acyclic graph.
I know about Bellman-Ford, so I negated my graph lengths. The problem:
networkx's bellman_ford() requires a source node. I want to find the
absolute longest path (or the shortest path after negation), not the
longest path from a given node.
Of course, I could run bellman_ford() on each node in the graph and
sort, but is there a more efficient method?
From what I've read (eg,
http://en.wikipedia.org/wiki/Longest_path_problem) I realize there
actually may not be a more efficient method, but was wondering if
anyone had any ideas (and/or had proved P=NP (grin)).
EDIT: all the edge lengths in my graph are +1 (or -1 after negation), so a method that simply visits the most nodes would also work. In general, it won't be possible to visit ALL nodes of course.
EDIT: OK, I just realized I could add an additional node that simply connects to every other node in the graph, and then run bellman_ford from that node. Any other suggestions?
There is a linear-time algorithm mentioned at http://en.wikipedia.org/wiki/Longest_path_problem
Here is a (very lightly tested) implementation
EDIT, this is clearly wrong, see below. +1 for future testing more than lightly before posting
import networkx as nx
def longest_path(G):
dist = {} # stores [node, distance] pair
for node in nx.topological_sort(G):
pairs = [[dist[v][0]+1,v] for v in G.pred[node]] # incoming pairs
if pairs:
dist[node] = max(pairs)
else:
dist[node] = (0, node)
node, max_dist = max(dist.items())
path = [node]
while node in dist:
node, length = dist[node]
path.append(node)
return list(reversed(path))
if __name__=='__main__':
G = nx.DiGraph()
G.add_path([1,2,3,4])
print longest_path(G)
EDIT: Corrected version (use at your own risk and please report bugs)
def longest_path(G):
dist = {} # stores [node, distance] pair
for node in nx.topological_sort(G):
# pairs of dist,node for all incoming edges
pairs = [(dist[v][0]+1,v) for v in G.pred[node]]
if pairs:
dist[node] = max(pairs)
else:
dist[node] = (0, node)
node,(length,_) = max(dist.items(), key=lambda x:x[1])
path = []
while length > 0:
path.append(node)
length,node = dist[node]
return list(reversed(path))
if __name__=='__main__':
G = nx.DiGraph()
G.add_path([1,2,3,4])
G.add_path([1,20,30,31,32,4])
# G.add_path([20,2,200,31])
print longest_path(G)
Aric's revised answer is a good one and I found it had been adopted by the networkx library link
However, I found a little flaw in this method.
if pairs:
dist[node] = max(pairs)
else:
dist[node] = (0, node)
because pairs is a list of tuples of (int,nodetype). When comparing tuples, python compares the first element and if they are the same, will process to compare the second element, which is nodetype. However, in my case the nodetype is a custom class whos comparing method is not defined. Python therefore throw out an error like 'TypeError: unorderable types: xxx() > xxx()'
For a possible improving, I say the line
dist[node] = max(pairs)
can be replaced by
dist[node] = max(pairs,key=lambda x:x[0])
Sorry about the formatting since it's my first time posting. I wish I could just post below Aric's answer as a comment but the website forbids me to do so stating I don't have enough reputation (fine...)