How can I map edgeweights from a matrix onto edges along the paths generated by another matrix
Update: "give different color to source (red) and sink (green) vertices"
ClearAll[map3]
map3[matrixA_?MatrixQ, matrixB_?MatrixQ, t1_Real, t2_Real] :=
Module[{indices = Union @@ (Partition[#, 2, 1] & /@
FindPath[AdjacencyGraph[Map[Boole[t1 <= # <= t2] &, matrixA, {-1}]],
#[[1]], #2[[1]], ∞, All])},
HighlightGraph[Graph[DirectedEdge @@@ indices,
EdgeWeight -> Extract[matrixB, indices],
EdgeLabels -> "EdgeWeight", ##3], {#, #2}]] &;
Examples:
map3[matA, matB, .2, .3][{4}, {6}, VertexLabels -> "Name"]
map3[matA, matB, .2, .3][Style[4, Red], Style[6, Green],
VertexLabels -> "Name", VertexSize -> {4 | 6 -> Large},
PerformanceGoal -> "Quality", ImagePadding -> 20]
Original answer:
Maybe something like:
ClearAll[map2]
map2[matrixA_?MatrixQ, matrixB_?MatrixQ, t1_Real, t2_Real] := Module[{indices =
Union @@ (Partition[#, 2, 1] & /@ FindPath[AdjacencyGraph[
Map[Boole[t1 <= # <= t2] &, matrixA, {-1}]], #, #2, ∞, All])},
HighlightGraph[Graph[DirectedEdge @@@ indices,
EdgeWeight -> Extract[matrixB, indices], EdgeLabels -> "EdgeWeight", ##3],
{#, #2}]] &;
Examples:
SeedRandom[4];
n = 10;
matA = RandomReal[{0.1, 0.5}, {n, n}];
matB = RandomReal[{0.1, 0.4}, {n, n}];
map2[matA, matB, .2, .3][4, 6, VertexLabels -> "Name"]
vLabels = {1 -> AGF, 2 -> CO12, 3 -> MA1, 4 -> MA2, 5 -> EGW,
6 -> CST, 7 -> WHS, 8 -> HOT, 9 -> TSC, 10 -> FIN};
map2[matA, matB, .2, .3][4, 6,
VertexLabels -> {v_ :> Placed[v /. vLabels, Center]}, VertexSize -> Large]
Row[map2[matA, matB, .2, .3][##, ImageSize -> Medium,
VertexLabels -> Placed["Name", Center], VertexSize -> Large] & @@@
{{4, 6}, {1, 4}}, Spacer[10]]
Here is what I could do to answer my own question:
ClearAll[n, matA, matB, map];
<< IGraphM`;
<< BoolEval`;
SeedRandom[4];
n = 10;
matA = RandomReal[{0.1, 0.5}, {n, n}];
matB = RandomReal[{0.1, 0.5}, {n, n}];
map[matrixA_?MatrixQ, matrixB_?MatrixQ, lb_Real, ub_Real] :=
Module[{matA = matrixA, matB = matrixB, t1 = lb, t2 = ub,
subgraphBetween, pindex, prule, paths},
subgraphBetween[t1, t2] :=
AdjacencyGraph[BoolEval[t1 <= matA < t2], VertexLabels -> "Name"];
pindex = FindPath[subgraphBetween[t1, t2], 4, 6, Infinity, All];
prule = DeleteDuplicates[
Flatten@Table[
Rule @@@ Partition[pindex[[i]], 2, 1], {i, Length[pindex]} ]];
paths = Graph[prule, EdgeWeight -> Take[Flatten@matB, Length[prule]],
VertexLabels -> "Name", EdgeLabels -> "EdgeWeight"]
]
map[matA, matB, 0.2, 0.3]
Although this partially answers my question, it is not so elegant. Partial because the respective elements from matB
are not selected. I just selected an equal number of edge weights to have a working code
. The correct selection of cells from matB
should match with the edges in prule
.