#
# Given a directed graph G with vertex set X, autgroup(G,X) returns a
#  list of generators for the automorphism group of G. Each generator
#  is encoded by a set of equations of the form {x1=y1,x2=y2,...},
#  where X={x1,x2,...}={y1,y2,...}.
# autgroup(G,n) does the same, using X={1,...,n}.
# autgroup(G) does the same, assuming G has no isolated points.
#
# Undocumented: we also allow G to be a vertex-colored digraph, in which
# case the return value is a list of generators for the group of color-
# preserving automorphisms of G. In this case, args[2] should be the
# partition of X into color classes (a list of sets).
#
# If the final argument is 'permgroup', return a permgroup(...) data
#  structure as in Maple's group package (vertex set must be {1,...,n}).
# If the final argument is 'gap', printf a sequence of statements
#  that can be pasted into a gap session.
#
`posets/autgroup`:=proc(P) local mu,X,pg,n;
  n:=nargs; if type(args[n],'name') then n:=n-1 fi; 
  if n=1 then mu:=[map(op,P)]
    elif type(args[2],'list(set)') then mu:=args[2]
    elif type(args[2],'integer') then mu:=[{$1..args[2]}]
    else mu:=[args[2]] fi;
  pg:=`posets/autgroup/main`(P,mu); X:=map(op,mu);
  if nargs=n then pg
    elif {op(X)}<>{$1..nops(X)} then
      ERROR(`cannot export unless vertex set is {1,...,n} for some n`)
    elif args[nargs]='permgroup' then
      permgroup(nops(X),map(`posets/autgroup/cyc`,{op(pg)}))
    elif args[nargs]='gap' then `posets/autgroup/gap`(pg)
    else ERROR(`invalid arguments`)
  fi
end:
#
# The main work is done here, recursively.
#
`posets/autgroup/main`:=proc(G) local mu,i,k,pg,B;
  mu:=`posets/fastdisc`(args);
  for k to nops(mu) while nops(mu[k])=1 do od;
  if k>nops(mu) then RETURN([]) fi;
  i:=mu[k][1]; B:=subsop(1=NULL,mu[k]);
  mu:=subsop(k=({i},B),mu);
  pg:=procname(G,mu);
  `posets/buildgrp`(pg,G,mu,k);
end:
#
# decompose pi into disjoint cycles
#
`posets/autgroup/cyc`:=proc(pi) local alive,mu,i,c;
  alive:=map(x->op(1,x),pi); mu:=NULL;
  while nops(alive)>0 do
    i:=alive[1]; c:=i; i:=subs(pi,i);
    while i<>alive[1] do c:=c,i; i:=subs(pi,i) od;
    mu:=mu,[c]; alive:=alive minus {c};
  od; [mu]
end:
#
# export a pg to gap
#
`posets/autgroup/gap`:=proc(pg) local pi,i,n;
  printf(`\n`); n:=nops(pg);
  for i to n do
    pi:=`posets/autgroup/cyc`(pg[i]);
    pi:=map(convert,pi,'string');
    pi:=map(y->cat(`(`,substring(y,2..length(y)-1),`)`),pi);
    printf(`g%d:=%s;\n`,i,cat(op(pi)));
  od;
  if n=0 then printf(`G:=Group(());\n`) else
    printf(`G:=Group(g1%s);\n`,cat(seq(op([`,g`,i]),i=2..n))) fi;
  printf(`\n`); # V.3 cannot handle consecutive newlines
end:
#
save `posets/autgroup`, `posets/autgroup/main`, `posets/autgroup/cyc`,
  `posets/autgroup/gap`, cat(HomeLib,`/posets/autgroup.m`);
read cat(HomeLib,`/help/posets/autgroup`);
quit;

