from __future__ import division
import os
import gridcorner
import numpy as np
import sys

label = "example_cw"

Alpha = 2.2
Delta = 1.2
Freq = 10
f1dot = -1e-9
f2dot = 1e-20

startTime = 1200000000
duration = 200 * 86400
refTime = int(startTime + .5*duration)

n = 100
FreqBand = 50/duration
f1dotBand = 50/duration**2
f2dotBand = 50/duration**3

if 'data' in sys.argv:
    cmd = (
        "lalapps_Makefakedata_v4 --outSingleSFT=True --outSFTbname='{}.sft' \
        --IFO='H1' --noiseSqrtSh=1e-20 --h0=1e-20 --startTime={} --duration={}\
        --fmin=8 --Band=4 --Alpha={} --Delta={} --Freq={} --f1dot={}\
        --f2dot={} --refTime={} --cosi=0.5".format(
            label, startTime, duration, Alpha, Delta, Freq, f1dot,
            f2dot, refTime))
    print(cmd)
    os.system(cmd)

    cmd = (
        "lalapps_ComputeFstatistic_v2\
        --Alpha={} \
        --Delta={} \
        --Freq={} --FreqBand={} --dFreq={} \
        --f1dot={} --f1dotBand={} --df1dot={} \
        --f2dot={} --f2dotBand={} --df2dot={} \
        --DataFiles='{}.sft'\
        --outputFstat='./{}.txt' --refTime={}".format(
            Alpha, Delta,
            Freq-FreqBand/2, FreqBand, FreqBand/n,
            f1dot-f1dotBand/2, f1dotBand, f1dotBand/n,
            f2dot-f2dotBand/2, f2dotBand, f2dotBand/n,
            label, label, refTime))

    print(cmd)
    os.system(cmd)

data = np.loadtxt("{}.txt".format(label), comments='%')

sFreq = np.unique(data[:, 0])
sf1dot = np.unique(data[:, 3])
sf2dot = np.unique(data[:, 4])
sAlpha = np.unique(data[:, 1])
sDelta = np.unique(data[:, 2])

stwoF = data[:, -1].reshape(len(sFreq), len(sf1dot), len(sf2dot))
print stwoF.shape

fig, axes = gridcorner.gridcorner(
    stwoF, xyz=[sFreq, sf1dot, sf2dot], projection='log_mean',
    labels=['Freq', 'f1dot', 'f2dot', '$2\mathcal{F}$'])
fig.savefig(label)