#!/usr/bin/python

import os, sys
import json
import re

from parmap import parmap

def lists_to_tuples(x):
  if isinstance(x, (list, tuple)):
    return tuple( lists_to_tuples(e) for e in x )
  if isinstance(x, dict):
    return { k: lists_to_tuples(v) for k, v in x.items() }
  return x

L = set()

for line in sys.stdin:
  L.add(lists_to_tuples(eval(line))); continue

  j = json.loads(line.rstrip())
  n = int(re.match("Z_([0-9]+)", j["template_group"])[1])

  a = j["assignment"]
  for i in range(len(a)):
    if a[i] >= n//2: a[i] -= n

  s = sum(abs(x) for x in a)

  L.add(lists_to_tuples((2*s, j["template_graph"], a)))

L = list(enumerate(sorted(L)))

nproc = int(os.getenv("P", "0"))

def worker(T):
#  return json.dumps(T)

  from graph_tools.all import EdgeColoring, voltage_graph_zn_to_sequence
  from graph_tools.utils import stabilize_period
  i, (s, t, a) = T
  gs = voltage_graph_zn_to_sequence(t, a)
  v = gs.graph(s).eval(EdgeColoring(3))
  yield "%i G> %i %i" % (i, s, v)
  X = gs.stabilize(EdgeColoring(3))
  yield "%i S>" % (i,)
  p, l = stabilize_period(X, shift=1)
  yield json.dumps({
    "id": i,
    "template": t,
    "assignment": a,
    "repeats_from": p,
    "has_three_coloring": l
  })

for x in parmap(worker, L, nproc or None, multimap=True, in_order=False, out_chunksize=1):
  print(x)