"""VGG D/E shape, receptive-field and parameter accounting; no learned model.
Standard-library reference to the ICLR 2015 paper, arXiv:1409.1556v6.
"""
import argparse
import json

# region: receptive
def stack_comparison(depth,channels=64):
    """Equal channels, stride one, no pooling; kernel weights only."""
    return {'receptive':2*depth+1, 'stack':depth*9*channels**2,
            'wide':(2*depth+1)**2*channels**2}
# endregion: receptive

# region: architecture
CONFIGS={'D':[2,2,3,3,3], 'E':[2,2,4,4,4]}


def architecture(config='D'):
    side,channels,receptive,jump=224,3,1,1
    layers=[]
    for block,count in enumerate(CONFIGS[config]):
        out=[64,128,256,512,512][block]
        for i in range(count):
            receptive+=2*jump
            layers.append({'name':f'conv{block+1}_{i+1}','side':side,'channels':out,
                           'parameters':9*channels*out+out,'receptive':receptive,'jump':jump})
            channels=out
        receptive+=jump; jump*=2; side//=2
        layers.append({'name':f'pool{block+1}','side':side,'channels':channels,
                       'parameters':0,'receptive':receptive,'jump':jump})
    return layers
# endregion: architecture

# region: parameters
def parameter_count(config='D'):
    conv=sum(layer['parameters'] for layer in architecture(config))
    fc1=7*7*512*4096+4096
    fc2=4096*4096+4096
    fc3=4096*1000+1000
    return {'conv':conv,'fc1':fc1,'fc2':fc2,'fc3':fc3,'total':conv+fc1+fc2+fc3}
# endregion: parameters


def main():
    assert parameter_count('D')['total']==138357544
    assert parameter_count('E')['total']==143667240
    assert architecture('D')[-1]['side']==7
    assert architecture('D')[-1]['receptive']==212
    report={'stack':stack_comparison(3),'D':parameter_count('D'),'E':parameter_count('E'),
            'architecture':architecture('D')}
    parser=argparse.ArgumentParser();parser.add_argument('--json',action='store_true');args=parser.parse_args()
    print(json.dumps(report) if args.json else 'VGG geometry self-checks passed. '+str(report))

if __name__=='__main__':
    main()
