#!/usr/bin/env python3
"""Frozen QArena rotation-bank generator. Run: python -I solve.py INSTANCE output.json
Requires pygridsynth==2.0.0 and mpmath==1.4.1 (MIT/BSD licenses).
Ross/Selinger, arXiv:1403.2975; shared Hamming weight: Kivlichan et al.,
arXiv:1902.10673 (CC BY 4.0). Four-T relative-AND derived from the CCZ
phase polynomial; arithmetic, joint-error search, and optimizers are original.
No contestant artifact was downloaded or used. Fixed synthesis requests below
were selected by joint-error search and then accepted by QArena's exact local
verifier. Search used seeds 1/22, 32-128 tolerance points and Clifford phase
variants. This file regenerates the chosen words from high-precision requests,
not from a copied accepted file. pygridsynth is copyright Shun Yamamoto and
Nobuyuki Yoshioka, MIT: https://github.com/quantum-programming/pygridsynth
"""
import argparse
import json
from pathlib import Path
import mpmath as mp
from pygridsynth import gridsynth_gates


PHASE = {'T': 1, 'S': 2, 'Z': 4, 'S_DAG': 6, 'T_DAG': 7}

EXP = {0: [], 1: ['T'], 2: ['S'], 3: ['T', 'S'], 4: ['Z'], 5: ['T_DAG', 'S_DAG'], 6: ['S_DAG'], 7: ['T_DAG']}

def commute(a, b):
    if a[0] == 'CX' and b[0] == 'CX':
        return a[2] != b[1] and b[2] != a[1]
    if a[0] == 'CX':
        return b[1] not in a[1:] or (b[0] in PHASE and b[1] == a[1]) or (b[0] == 'X' and b[1] == a[2])
    if b[0] == 'CX':
        return commute(b, a)
    if a[1] != b[1]:
        return True
    if a[0] in PHASE and b[0] in PHASE:
        return True
    return a[0] == 'Z' and b[0] == 'X' or (a[0] == 'X' and b[0] == 'Z')

def optimize(ops):
    out = []
    for op in ops:
        for i in range(len(out) - 1, -1, -1):
            prev = out[i]
            if op[0] in PHASE and prev[0] in PHASE and (op[1] == prev[1]):
                names = EXP[(PHASE[op[0]] + PHASE[prev[0]]) % 8]
                del out[i]
                out.extend([[name, op[1]] for name in names])
                break
            if op == prev and op[0] in ['X', 'Z', 'H', 'CX']:
                del out[i]
                break
            if not commute(op, prev):
                out.append(op)
                break
        else:
            out.append(op)
    return out

INV = {'S': 'S_DAG', 'S_DAG': 'S', 'T': 'T_DAG', 'T_DAG': 'T'}

def inverse(ops):
    return [[INV.get(o[0], o[0]), *o[1:]] for o in reversed(ops)]

def rand_gate(a, b, t):
    return [['H', t], ['T', t], ['CX', a, t], ['T_DAG', t], ['CX', b, t], ['T', t], ['CX', a, t], ['T_DAG', t], ['CX', b, t], ['H', t]]

def weight_compute():
    return [['CX', 1, 2], ['CX', 1, 3]] + rand_gate(2, 3, 4) + [['CX', 1, 4], ['CX', 3, 2], ['CX', 2, 1]]

def full_weight_compute():
    return weight_compute() + rand_gate(0, 1, 5) + [['CX', 1, 0]] + rand_gate(4, 5, 6) + [['CX', 5, 4]]

def ring_compute():
    return [['CX', 2, 0], ['CX', 3, 1], ['X', 0], ['X', 1]] + rand_gate(0, 1, 4) + [['X', 0], ['X', 1], ['CX', 3, 2]] + rand_gate(4, 2, 5)

def build(choices, ring, full=False):
    ar = full_weight_compute() if full else weight_compute()
    ops = ar.copy()
    for c, q in zip(choices[:3], [0, 4, 6] if full else [0, 1, 4]):
        ops += [[o[0], q] for o in c['ops']]
    ops += inverse(ar)
    if ring:
        rr = ring_compute()
        ops += rr
        for c, q in zip(choices[3:], [4, 5]):
            ops += [[o[0], q] for o in c['ops']]
        ops += inverse(rr)
    for _ in range(3):
        ops = optimize(ops)
    return {'ancillas': 3 if full else 2 if ring else 1, 'ops': ops}

CASES = {'rot1-boundary': {'choices': [],
                   'epsilon_scale': '1',
                   'error_den': 5,
                   'error_num': 4,
                   'weight_mode': 'empty'},
 'rot4-repeat-a0': {'choices': [{'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                 'epsilon_factor': '0.89349883100941074410511577439348243304840835931521269210810453994004962495208848',
                                 'seed': 0,
                                 'shift': '-0.000000143051147460937494706044079660622880822984370752237737178802490234375',
                                 'up_to_phase': False,
                                 'variant': 0},
                                {'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                 'epsilon_factor': '0.89349883100941074410511577439348243304840835931521269210810453994004962495208848',
                                 'seed': 0,
                                 'shift': '-0.000000143051147460937494706044079660622880822984370752237737178802490234375',
                                 'up_to_phase': False,
                                 'variant': 0},
                                {'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                 'epsilon_factor': '0.89349883100941074410511577439348243304840835931521269210810453994004962495208848',
                                 'seed': 0,
                                 'shift': '-0.000000143051147460937494706044079660622880822984370752237737178802490234375',
                                 'up_to_phase': False,
                                 'variant': 0},
                                {'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                 'epsilon_factor': '0.89349883100941074410511577439348243304840835931521269210810453994004962495208848',
                                 'seed': 0,
                                 'shift': '-0.000000143051147460937494706044079660622880822984370752237737178802490234375',
                                 'up_to_phase': False,
                                 'variant': 0}],
                    'epsilon_scale': '0.5',
                    'error_den': 1099511627776,
                    'error_num': 1,
                    'weight_mode': 'independent'},
 'rot4-repeat-a3': {'choices': [{'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                 'epsilon_factor': '1.6',
                                 'seed': 0,
                                 'shift': '0.00000028610229492187498941208815932124576164596874150447547435760498046875',
                                 'up_to_phase': True,
                                 'variant': 1},
                                {'angle': '2.5740044351731375472112369148692905521660423644612495314624244748540498992464844',
                                 'epsilon_factor': '0.57719756878325966914368646274030952558679101646484533642646620436683659236719908',
                                 'seed': 0,
                                 'shift': '-0.00000028610229492187498941208815932124576164596874150447547435760498046875',
                                 'up_to_phase': True,
                                 'variant': 1},
                                {'angle': '5.1480088703462750944224738297385811043320847289224990629248489497080997984929687',
                                 'epsilon_factor': '0.49896260063448971169600670824067784199561514614732120021828831341192952216864995',
                                 'seed': 0,
                                 'shift': '-0.00000028610229492187498941208815932124576164596874150447547435760498046875',
                                 'up_to_phase': False,
                                 'variant': 1}],
                    'epsilon_scale': '1',
                    'error_den': 1099511627776,
                    'error_num': 1,
                    'weight_mode': 'full'},
 'rot4-repeat-a3-e10': {'choices': [{'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                     'epsilon_factor': '1.6',
                                     'seed': 0,
                                     'shift': '-0.0002929687499999999891579782751449556599254719913005828857421875',
                                     'up_to_phase': True,
                                     'variant': 0},
                                    {'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                     'epsilon_factor': '1.1956580320539218418286331864842855659137839616811286436974695624060229245582455',
                                     'seed': 0,
                                     'shift': '-0.0002929687499999999891579782751449556599254719913005828857421875',
                                     'up_to_phase': True,
                                     'variant': 1},
                                    {'angle': '2.5740044351731375472112369148692905521660423644612495314624244748540498992464844',
                                     'epsilon_factor': '0.27863906274020751564656455099230558666375216496244405336324985034023630555063984',
                                     'seed': 0,
                                     'shift': '-0.0002929687499999999891579782751449556599254719913005828857421875',
                                     'up_to_phase': False,
                                     'variant': 0}],
                        'epsilon_scale': '1',
                        'error_den': 1048576,
                        'error_num': 1,
                        'weight_mode': 'majority'},
 'rot4-repeat-a3-e30': {'choices': [{'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                     'epsilon_factor': '1.6',
                                     'seed': 0,
                                     'shift': '-0.000000000279396772384643544347742343087154064107391349125464330427348613739013671875',
                                     'up_to_phase': True,
                                     'variant': 1},
                                    {'angle': '2.5740044351731375472112369148692905521660423644612495314624244748540498992464844',
                                     'epsilon_factor': '0.37286790071446306402531949130268636354258881948809064017652460851109568672190026',
                                     'seed': 0,
                                     'shift': '-0.000000000279396772384643544347742343087154064107391349125464330427348613739013671875',
                                     'up_to_phase': False,
                                     'variant': 0},
                                    {'angle': '5.1480088703462750944224738297385811043320847289224990629248489497080997984929687',
                                     'epsilon_factor': '0.18',
                                     'seed': 0,
                                     'shift': '0.0',
                                     'up_to_phase': True,
                                     'variant': 0}],
                        'epsilon_scale': '1',
                        'error_den': 1152921504606846976,
                        'error_num': 1,
                        'weight_mode': 'full'},
 'rot4-ring-a3': {'choices': [{'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                               'epsilon_factor': '1.1956580320539218418286331864842855659137839616811286436974695624060229245582455',
                               'seed': 0,
                               'shift': '-0.00000028610229492187498941208815932124576164596874150447547435760498046875',
                               'up_to_phase': False,
                               'variant': 0},
                              {'angle': '2.5740044351731375472112369148692905521660423644612495314624244748540498992464844',
                               'epsilon_factor': '0.77239150768450380628794622754805353409023158592858599643588148259047894076599423',
                               'seed': 0,
                               'shift': '0.0',
                               'up_to_phase': True,
                               'variant': 3},
                              {'angle': '5.1480088703462750944224738297385811043320847289224990629248489497080997984929687',
                               'epsilon_factor': '0.49896260063448971169600670824067784199561514614732120021828831341192952216864995',
                               'seed': 0,
                               'shift': '-0.00000028610229492187498941208815932124576164596874150447547435760498046875',
                               'up_to_phase': False,
                               'variant': 2},
                              {'angle': '-1.5791644787990460669603981215583223475806808303028168121415115219282717598259503',
                               'epsilon_factor': '0.77239150768450380628794622754805353409023158592858599643588148259047894076599423',
                               'seed': 0,
                               'shift': '-0.00000028610229492187498941208815932124576164596874150447547435760498046875',
                               'up_to_phase': False,
                               'variant': 3},
                              {'angle': '3.1583289575980921339207962431166446951613616606056336242830230438565435196519006',
                               'epsilon_factor': '0.66769940870449482901008526690631696717988664871255443701312690517504008211735418',
                               'seed': 0,
                               'shift': '-0.00000028610229492187498941208815932124576164596874150447547435760498046875',
                               'up_to_phase': True,
                               'variant': 1}],
                  'epsilon_scale': '1',
                  'error_den': 1099511627776,
                  'error_num': 1,
                  'weight_mode': 'full'},
 'rot4-ring-a3-e10': {'choices': [{'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                   'epsilon_factor': '1.6',
                                   'seed': 0,
                                   'shift': '-0.0002929687499999999891579782751449556599254719913005828857421875',
                                   'up_to_phase': True,
                                   'variant': 0},
                                  {'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                   'epsilon_factor': '0.32232834560582279085452802696344702017910157813370600015543863502612961836877481',
                                   'seed': 0,
                                   'shift': '-0.0002929687499999999891579782751449556599254719913005828857421875',
                                   'up_to_phase': True,
                                   'variant': 1},
                                  {'angle': '2.5740044351731375472112369148692905521660423644612495314624244748540498992464844',
                                   'epsilon_factor': '0.49896260063448971169600670824067784199561514614732120021828831341192952216864995',
                                   'seed': 0,
                                   'shift': '-0.0002929687499999999891579782751449556599254719913005828857421875',
                                   'up_to_phase': False,
                                   'variant': 1},
                                  {'angle': '-1.5791644787990460669603981215583223475806808303028168121415115219282717598259503',
                                   'epsilon_factor': '0.49896260063448971169600670824067784199561514614732120021828831341192952216864995',
                                   'seed': 0,
                                   'shift': '0.0',
                                   'up_to_phase': True,
                                   'variant': 0},
                                  {'angle': '3.1583289575980921339207962431166446951613616606056336242830230438565435196519006',
                                   'epsilon_factor': '0.43133181824856277910069614578640833523861971522820747172671970166108305085044121',
                                   'seed': 0,
                                   'shift': '-0.0002929687499999999891579782751449556599254719913005828857421875',
                                   'up_to_phase': False,
                                   'variant': 1}],
                      'epsilon_scale': '1',
                      'error_den': 1048576,
                      'error_num': 1,
                      'weight_mode': 'majority'},
 'rot4-ring-a3-e30': {'choices': [{'angle': '1.2870022175865687736056184574346452760830211822306247657312122374270249496232422',
                                   'epsilon_factor': '1.6',
                                   'seed': 0,
                                   'shift': '0.000000000279396772384643544347742343087154064107391349125464330427348613739013671875',
                                   'up_to_phase': True,
                                   'variant': 0},
                                  {'angle': '2.5740044351731375472112369148692905521660423644612495314624244748540498992464844',
                                   'epsilon_factor': '0.77239150768450380628794622754805353409023158592858599643588148259047894076599423',
                                   'seed': 0,
                                   'shift': '0.0',
                                   'up_to_phase': False,
                                   'variant': 1},
                                  {'angle': '5.1480088703462750944224738297385811043320847289224990629248489497080997984929687',
                                   'epsilon_factor': '0.18',
                                   'seed': 0,
                                   'shift': '0.0',
                                   'up_to_phase': True,
                                   'variant': 0},
                                  {'angle': '-1.5791644787990460669603981215583223475806808303028168121415115219282717598259503',
                                   'epsilon_factor': '1.0335952079645066380836377911641697918350662078202084307333019085079653657063623',
                                   'seed': 0,
                                   'shift': '-0.000000000279396772384643544347742343087154064107391349125464330427348613739013671875',
                                   'up_to_phase': True,
                                   'variant': 1},
                                  {'angle': '3.1583289575980921339207962431166446951613616606056336242830230438565435196519006',
                                   'epsilon_factor': '0.66769940870449482901008526690631696717988664871255443701312690517504008211735418',
                                   'seed': 0,
                                   'shift': '0.0',
                                   'up_to_phase': True,
                                   'variant': 0}],
                      'epsilon_scale': '1',
                      'error_den': 1152921504606846976,
                      'error_num': 1,
                      'weight_mode': 'full'}}


def solve(instance):
    mp.mp.dps=80
    spec=CASES[instance]
    if spec['weight_mode']=='empty':
        return {'ancillas':0,'ops':[]}
    epsilon=mp.sqrt(mp.mpf(spec['error_num'])/spec['error_den'])*mp.mpf(spec['epsilon_scale'])
    choices=[]
    for request in spec['choices']:
        word=gridsynth_gates(mp.mpf(request['angle'])+mp.mpf(request['shift']),
                            epsilon*mp.mpf(request['epsilon_factor']),
                            up_to_phase=request['up_to_phase'],seed=request['seed'],dps=70)
        ops=[[g,0] for g in word[::-1] if g!='W']
        pre=[['S',0]]*request['variant']
        ops=pre+ops+inverse(pre)
        for _ in range(2):ops=optimize(ops)
        choices.append({'ops':ops})
    if spec['weight_mode']=='independent':
        return {'ancillas':0,'ops':[[o[0],q] for q,c in enumerate(choices) for o in c['ops']]}
    return build(choices,'ring' in instance,spec['weight_mode']=='full')


def main():
    p=argparse.ArgumentParser();p.add_argument('instance',choices=sorted(CASES));p.add_argument('output',type=Path);a=p.parse_args()
    artifact=solve(a.instance)
    a.output.write_text(json.dumps(artifact,separators=(',',':')))
    print(json.dumps({'t':sum(o[0] in ['T','T_DAG'] for o in artifact['ops']),'gates':len(artifact['ops']),'ancillas':artifact['ancillas']}))


if __name__=='__main__':main()
