## dharr

Dr. David Harrington

## 4776 Reputation

19 years, 25 days
University of Victoria
Professor or university staff

## Social Networks and Content at Maplesoft.com I am a professor of chemistry at the University of Victoria, BC, Canada, where my research areas are electrochemistry and surface science. I have been a user of Maple since about 1990.

## MaplePrimes Activity

### These are replies submitted by dharr

@Carl Love Thanks. Just to clarify, although I developed both algorithms, the idea of the labeled adjacency matrix giving the walks is not new, for example it is found here.

## another version...

@Carl Love Thanks for the comments. The makesets code with the expand is only used for one entry of the matrix (for the vertex of interest), so if you wanted to calculate for all vertices it certainly wouldn't be good. Here's another version that has less explosive storage requirements because it condenses the entries to sums of vertex sets at each stage. The basic idea was to use LinearAlgebra:-Generic for Matrix multiplication with `*` defined as set union, but there was code creep to deal with multiples of sets (2*{1,4,5}), so it has less storage but is probably too inefficient. Could perhaps use something like f(1,2,3)*f(2,3,4)=f(1,2,3,4) instead.

```WalkLength:=proc(G::Graph,v)
uses GraphTheory;
local x,y,u,vv,A,B,F,n,vertset,i,omega;
if not member(v,Vertices(G),'vv') then error "vertex not in graph" end if;
if not IsConnected(G) then return infinity end if;
F[`0`]:=0:F[`1`]:=1:F[`=`]:=(x,y)->evalb(x=y):F[`/`]:=`/`:
F[`+`]:=()->map(u->if type(u,`*`) then op(2,u) else u end if,`+`(args));
F[`*`]:=proc(x,y) local i,j,q,u;
if x=0 or y=0 then return 0
elif x::set and y::set then
return x union y
elif x::set and type(y,`+`) then
q:=map(`union`,y,x);
return map(u->if type(u,`*`) then op(2,u) else u end if,q)
elif y::set and type(x,`+`) then
q:=map(`union`,x,y);
return map(u->if type(u,`*`) then op(2,u) else u end if,q)
elif type(x,`+`) and type(y,`+`) then
return map(u->if type(u,`*`) then op(2,u) else u end if,q)
else error "unexpected error"
end if
end proc;
n:=NumberOfVertices(G);
vertset:={\$(1..n)};
B:=copy(A);
for i from 2 do
B:=LinearAlgebra:-Generic:-MatrixMatrixMultiply[F](B,A);
until has(B[vv,vv],[vertset]);
i;
end proc:```

## disjoint cycles...

@mmcdara I meant only that you find other cycles in this way. It is well known in graph theory that the ringsum of cycles gives other cycles or disjoint unions of cycles, but the disjoint unions can be easily detected. So then you get the algorithm that I think you now have (this is similar to the "cut" case I did earlier in a blog here.) You can also represent the cycles as vectors with addition mod 2, just as in the cuts case.

## combining cycles...

 > restart:
 > with(GraphTheory):
 > C1 := {seq({i, i+1}, i=1..6), {7, 1}}: C2 := {{1, 8}, {8, 3}, {8, 6}}: G := Graph(C1 union C2): DrawGraph(G, style=planar); cb:=CycleBasis(G);  How to find [3, 4, 5, 6, 8]? Considered as sets of edges, the symmetric difference (or "ringsum") operation combines cycles into other cycles  - it kills common edges.

Actually finding cycles or counting all of them is nontrivial. Here combining all three cycles works.

 > cycles:=map(x->Edges(InducedSubgraph(G,x)),cb); > symmdiff(cycles,cycles,cycles); > ## vote up...

@Carl Love The last one in particular is nice. This operation is one I need to do fairly often and am always frustrated there isn't some simpler (to the average user) way. The help page for solve,details has an example using eval(r, op(indets(r)) = 3) but you have to know it's the third op. My answer has the same problem. Yours allow _Z11 etc, so again you have to know what possibililities might occur. This is compounded by the fact that extra solve commands lead to higher numbers, so the first one isn't always _Z1. To really to do it properly probably some slicing and dicing of the name is necessary.

## resize...

@Samir Khan Thanks. Most other software I have, the corner handle resizes keeping the aspect ratio the same and handles on the vertical and horizontal edges change one dimension and therefore the aspect ratio.

## total replacement...

@Carl Love But this replaces _Z4 as well, which is not what the OP wanted.

## numeric...

@rasmusgs At least for integrals the answer is simple; just add the option numeric, e.g.

`int(sin(x), x = 0 .. Pi, numeric)`

gives 2.0000

(But sometimes, as here the exact value is nice, so maybe you want to try without numeric first.)

## some changes...

@vs140580 Here some minimal changes. I made it a row Vector rather than 1x15 Matrix. To see more entries of a Vector or Matrix use for example interface(rtablesize=20) at the beginning of your worksheet.

The last line of the procedure would normally be the return value. (I could have used A rather than return A.) Then you would print outside the procedure; normally print is not used within procedures to provide results.

To convert entries to floats use evalf(A).

To work with all edges in a single line of code use map or map2. For an example see my other answer here.

## finding other roots...

@jud If I understand your question, then this isn't possible in general. GaloisGroup only gives the permutations between the roots, which is not enough to reconstruct the roots. Here is a simpler example that is my take on it.

 > > Polynomial and its first root alpha

 >   The splitting field has only one algebraic number (alpha), the extension field is Q(alpha), and so all the roots can be written directly in terms of alpha.

 >   So now the permutations in the Galois group take one root to another. Transitive means for any pair from 1,2,3,4 there is a group operation (permutation) that takes the first of the pair to the second - easily seen to be true.

 >    So first of all we do not know which of 1,2,3,4 is alpha. We are lucky in this case that rotating through the numbers gives the same result, so it doesn't matter.

 >  So taking 1 as alpha then the permutation (14)(23) takes alpha to the 4th root. But this doesn't help me find that root.

Only after I calculate the roots and look at them do I see that automorphism (14)(23) is complex conjugation.

Specifically, it takes a+b*alpha = a+b*(sqrt(3)+I)/2 to a + b*(sqrt(3)-I)/2, which leaves a unchanged (a,b in Q).

(Roots 1,2,3 and 4 are in quadrants 1,2,3, and 4).

 >   Compare with this example

 >   Different relationship between the roots

 >   But the same Galois group.

 >   (1,4)(2,3) still exchanges roots (1 and 4) and (2 and 3), but it is no longer complex conjugation as an automorphism. (It is not even a reflection in the complex plane.)

 >   > ## one way...

@Sphericalmoments A general method would be

1. Find all cycles in the corresponding undirected graph.
2. Find the 0, 1 or 2 directed cycles corresponding to each cycle.
3. Count them.
The DirectedCycles routine I gave earlier does step 2. Step 1 is the difficult step. It is possible to find all cycles from the cycle basis, but the algorithm is nontrivial. So here I give a very inefficient way of doing it, which is probably OK for small graphs.

[Edit: Updated routine works by finding all potential directed cycles on n vertices (rotationally distinct permutations on 1..n (with smallest integer first)) and then sees if the graph contains these edges. Still very inefficient]

 > > Finds all directed k-cycles in a directed graph.

 > DirectedCycles:=proc(G1::GRAPHLN,k::posint)    local i,j,m,s,perm,perms,c,cedges,n,edges,G;    uses GraphTheory;    if not IsDirected(G1) then error "graph not directed" end if;    n:=NumberOfVertices(G1);    if k<2 or k>n then error "need number of vertices  >= k > 1" end if;    G:=RelabelVertices(G1,[\$(1..n)]);    edges:=Edges(G);    # Find all rotationally unique lists of k vertices    # out of a total of n (smallest integer first).    j:=0;    s:=table();    for i to n-k+1 do # first (smallest)      perms:=Iterator:-Permute(i+1..n,k-1); # the rest      for perm in perms do        c:=[i,seq(perm[m],m=1..k-1),i];        cedges:={seq([c[m],c[m+1]],m=1..k)};        # check if this is a directed cycle in the graph        if cedges subset edges then          j:=j+1;          s[j]:=c[1..k];        end if;      end do;    end do;    convert(s,set);      end proc:
 >  >  Find all directed 2-cycles, 3-cycles and 4-cycles

 >       >  Number of directed 3-cycles

 >   Number of directed 4-cycles

 >   > ## Maple generated...

@Christian Wolinski I've just starting using the Logic package, and saw that in a long expression that I'd Imported and assumed it was an extra variable that was always true, added to put the expression in some sort of standard form. But here is a smaller example, showing it is a bug. I'll submit an SCR.

 > restart;
 > with(Logic):
 > q:=(x+x+x)*x:
 > q2 := Import(q, form = MOD2); > ## Cuts and cutsets...

@lcz I agree, my code actually tests for a cutset, which is a minimal cut, but not all cuts are minimal. Apologies; I sorted all this out before, but forgot about this distinction.

"A cutset S of a connected graph G is a minimal set of edges of G such that removal of S [dis]connects G into exactly two components", p.43, K. Thulasiraman and M.N.S. Swamy, "Graphs, Theory and Algorithms", Wiley 1992. doi:10.1002/9781118033104.

The stackexchange algorithm involving contraction detecting extra edges with loops is not easy to implement in Maple with its Contract or ContractSubgraph commands because it doesn't keep track of where loops came from. But one can just check for extra edges that are in one component before contracting. Here it is:

 > restart;

IsCut returns true if the edges are a cut

 > IsCut:=proc(G1::GRAPHLN,edges::set)        local G,partition,subgraphs,alledges;        uses GraphTheory;        if not IsConnected(G1) then error "Graph must be connected" end if;        G:=UnderlyingGraph(G1); # make undirected, unweighted, without loops        alledges:=Edges(G);        partition:=ConnectedComponents(DeleteEdge(G,edges,'inplace'=false));        if nops(partition) <= 1 then return false end if;        # check for edges that have both ends in one component        subgraphs:=map2(InducedSubgraph,G,partition);        if not (alledges minus `union`(map(Edges,subgraphs)[]) = edges) then return false end if;        # contract the components and see if the graph is bipartite        IsBipartite(foldl(ContractSubgraph,G,subgraphs[])); end proc:
 > with(GraphTheory): with(combinat): G:=CompleteGraph(3,3): edge:=choose(Edges(G), 7): `and`(seq(IsCutSet(G,s),s in edge)); # any 7 edges cuts the graph into 2 or more components > `or`(seq(IsCut(G,s),s in edge)); # no set of 7 edges is a cut > DrawGraph(G,size=[250,250]); > edges:={{1,4},{1,5},{1,6},{3,6}}; # {3,6} edge is extra IsCut(G,edges);  > edges:={{1,4},{1,5},{1,6}}; IsCut(G,edges);  > edges:={{1,4},{1,5},{1,6},{3,6},{3,5},{3,4}}; #3 components after cut; contracted graph is bipartite IsCut(G,edges);  > G2:=CycleGraph(3): #3 components, but contracted graph (same as original) is not bipartite IsCut(G2,Edges(G2)); > ## sometimes tests...

@vv @Christian Wolinski Thanks! Interestingly, I was using a more complicated expression earlier, and I got an error message:

```with(Logic):
q:=&or((&not x) &and (&not x),(&not x) &and (&not x[true]),&and(x,x
,&not x[true]),&and(&not x,&not x,&not x[true]),&and(x,x,x,x)
,&and(x,x,&not x,&not x),&and(x,x[true],&not x,&not x),
&and(x,x[true],&not x,&not x)):
SymmetryGroup(q);```

gives: Error, (in Logic:-SymmetryGroup) not in conjunctive normal form

so it can test. So then I didn't think about the form, which was a mistake. I'll submit an SCR about this (and Normalize)

﻿