
# Search narrow posets of type T=[[m_1,n_1],[m_2,n_2],...]

# Note that we do not attempt to prune out isomorphic copies--a given
# poset will be generated <= 2^k times, where k = the number of terms
# in the type vector having the form [m,m] for m>=2.

narrow:=proc(T,iv,f) local Rank,Cstack,Q,N,Edges,st,cc,res;
  Rank:=0; Cstack:=table();
  st:=time(); res:=iv;
  N:=convert(map(op,T),`+`);
  Q:=`narrow/root`(T,'Edges');
  do
    res:=f(res,Q[1],Q[3],N,args[4..nargs]);
    cc:=map(`narrow/prefer`,[op(1..Q[2],Edges)],Q[1],Q[3],N);
    if nops(cc)>0 then Rank:=Rank+1 else
      do cc:=Cstack[Rank];
        if nops(cc)=0 then Rank:=Rank-1 else break fi;
      od;
      if Rank=0 then break fi
    fi;
    Cstack[Rank]:=subsop(1=NULL,cc); Q:=cc[1]
  od;
  userinfo(2,'narrow',`Running Time:`,time()-st);
  res;
end;

# Generate the root poset of type T and its transitive closure,
# and assign to args[2] the list of potential extra relations.

`narrow/root`:=proc(T) local P,Edges,down,M,N,a,i,j,maxs,mins;
  P:=NULL; Edges:=NULL; down:=NULL; N:=0; maxs:={};
  for a in T do
    if a[1]<a[2] then ERROR(`not in standard form`) fi;
    M:=N; N:=N+a[1]+a[2];
    if a[2]=0 then mins:={M+1} else mins:={M+1,M+a[1]+1} fi;
    P:=P,seq(seq([i,j],i=maxs),j=mins); maxs:={N-a[2],N};
    P:=P,seq([i-1,i],i=M+2..M+a[1]),seq([i-1,i],i=M+a[1]+2..N);
    Edges:=Edges,seq(seq([i,j],j=M+a[1]+2..N),i=M+1..M+a[1]-1),
      seq(seq([i,j],j=M+2..M+a[1]),i=M+a[1]+1..N-1);
    down:=down,seq({$1..i},i=M+1..M+a[1]),
      seq({$1..M,$M+a[1]+1..i},i=M+a[1]+1..N);
  od;
  Edges:=[Edges]; Edges:=[seq([op(Edges[i]),i],i=1..nops(Edges))];
  assign(args[2],Edges);
  [{P},nops(Edges),[down]]
end;

# Given an edge e that is earlier than all other edges of P,
# check to see if the endpoints of e are incomparable in P.
# If so, check to see if this edge can be added without destroying
# any existing covering relations. If so, check to see if the new
# poset is sum-irreducible. If so, return the new covering
# relation, together with the new closure table.

`narrow/prefer`:=proc(e,P,down,N) local f,new;
  if member(e[1],down[e[2]]) or member(e[2],down[e[1]]) then RETURN() fi;
  if member([e[2]-1,e[1]+1],P) then RETURN() fi;
  for f in P do
    if member(f[1],down[e[1]]) and member(e[2],down[f[2]]) then RETURN() fi
  od;
  new:=map(proc(x,A,U,y) if member(y,A[x]) then {op(A[x]),op(U)}
    else A[x] fi end,[$1..N],down,down[e[1]],e[2]);
  [{op(P),[e[1],e[2]]},e[3]-1,new];
end:

