"""Three-dimensional random polar-dipole estimator for uniform outlet coverage."""
import argparse
import json
from pathlib import Path

import numpy as np
from scipy.stats import chi, ncx2


def analyze(sigma_nrad, coherent_nrad, budget_nrad, counts):
    """Isotropic Gaussian pointing per tangent axis; equal independent weights."""
    records=[]
    for effective_count in counts:
        component=sigma_nrad*np.sqrt(1.5/effective_count)
        record=dict(effective_count=effective_count,dipole_component_sd_nrad=component,
                    random_dipole_median_nrad=float(chi.ppf(.5,3)*component),
                    random_dipole_central_80_nrad=(chi.ppf([.1,.9],3)*component).tolist(),
                    random_dipole_95_nrad=float(chi.ppf(.95,3)*component))
        distribution=ncx2(3,(coherent_nrad/component)**2)
        record['total_dipole_median_nrad']=float(np.sqrt(distribution.ppf(.5))*component)
        record['total_dipole_central_80_nrad']=(np.sqrt(distribution.ppf([.1,.9]))*component).tolist()
        if budget_nrad is not None:
            record['probability_polar_mode_exceeds_screen']=float(distribution.sf((budget_nrad/component)**2))
        records.append(record)
    return dict(sigma_per_axis_nrad=sigma_nrad,coherent_dipole_nrad=coherent_nrad,
                screen_nrad=budget_nrad,records=records,
                scope='Gaussian independent groups and isotropic angular coverage; 3D polar l=1 projection only. Other modes are not predicted by these probabilities.')


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--sigma',type=float,default=3.)
    parser.add_argument('--coherent',type=float,default=1.)
    parser.add_argument('--screen',type=float)
    parser.add_argument('--out',type=Path,required=True)
    args=parser.parse_args()
    result=analyze(args.sigma,args.coherent,args.screen,[3,10,30,100,1000,100000])
    args.out.write_text(json.dumps(result,indent=2,allow_nan=False)+'\n')
