"""Reproduce ideal binary stacking symmetry and translational closure.
Requirements: Python 3, numpy, spglib. Run: python verify_stacking.py
All lengths are arbitrary units; X and Y are distinct species.
"""
import itertools,json,math
from pathlib import Path
import numpy as np
import spglib

def canonical(s):
    return min(t[i:]+t[:i] for t in (s,s[::-1]) for i in range(len(s)))

def check(hc):
    n=len(hc);steps=[1]
    for mark in hc[1:]:steps.append(steps[-1]*(-1 if mark=='h' else 1))
    sign_closed=steps[0]==steps[-1]*(-1 if hc[0]=='h' else 1)
    position_closed=sum(steps)%3==0
    result={'hc':hc,'Nh':hc.count('h'),'Nc':hc.count('c'),'sign_closed':sign_closed,'step_sum':sum(steps),'ABC_closed':position_closed}
    if not(sign_closed and position_closed):return result
    abc=[0]
    for step in steps[:-1]:abc.append((abc[-1]+step)%3)
    result['ABC']=''.join('ABC'[i] for i in abc)
    xy=[(0,0),(1/3,2/3),(2/3,1/3)]
    lattice=[[1,0,0],[-.5,math.sqrt(3)/2,0],[0,0,n*math.sqrt(2/3)]]
    xpos=[[*xy[a],i/n] for i,a in enumerate(abc)]
    ypos=[[*xy[a],((i+.75)/n)%1] for i,a in enumerate(abc)]
    for key,pos,types in [('X_only',xpos,[1]*n),('XY',xpos+ypos,[1]*n+[2]*n)]:
        ds=spglib.get_symmetry_dataset((lattice,pos,types),symprec=1e-5)
        result[key]={'spacegroup':ds.international,'number':int(ds.number),'standard_cell_atoms':len(ds.std_types)}
    return result

sequences=['hcchcc','hhhchc','hhcchhcchhcc','hhcchcch','hchcchch','hhhcchcc','hhchcchc','hccchccc','hhhchhhc','hcccccch','hhhhhchc','hhhhhhcc']
results={'model':'X z=i/n, Y z=(i+3/4)/n; A=(0,0),B=(1/3,2/3),C=(2/3,1/3)','spglib_version':spglib.__version__,'checks':[check(hc) for hc in sequences],'strict_hexagonal':{}}
for n in [6,8]:
    accepted=[]
    for hc in map(''.join,itertools.product('hc',repeat=n)):
        if hc!=canonical(hc):continue
        result=check(hc)
        # For this polar binary model the strict hexagonal polytypes are P63mc.
        if result.get('XY',{}).get('number')==186 and result['XY']['standard_cell_atoms']==2*n:
            accepted.append(result)
    results['strict_hexagonal'][str(n)]=accepted
assert canonical('hhhcchcc')==canonical('hhcchcch')
assert canonical('hhchcchc')==canonical('hchcchch')
assert not check('hhhhhhcc')['ABC_closed']
assert check('hcchcc')['XY']['number']==186
assert check('hhhchc')['XY']['number']==156
assert check('hhcchcch')['XY']['number']==156
assert check('hchcchch')['XY']['number']==156
Path(__file__).with_name('stacking-results.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8')
print(json.dumps({'spglib':spglib.__version__,'checks':len(sequences),'strict_hexagonal':{n:[r['hc'] for r in v] for n,v in results['strict_hexagonal'].items()}},ensure_ascii=False))
