import sys
import os
from os.path import exists
import pandas as pd
import numpy as np
np.set_printoptions(threshold=sys.maxsize)

test = 0 # False # True
#=============================Input begin===============================
if test: print(' %Tst --- sys.argv[0]:', sys.argv[0])
nargs = len(sys.argv)
if test: print(' %Tst --- nargs,', nargs)
pid = str(os.getpid())
if test: print(' %Tst --- pid,', pid)
fname = 'tmp'+pid
if nargs == 2: fname = str(sys.argv[1])
if test: print(' %Tst --- (argv1) File,', fname)
print(' File:   {:>27}    |'.format(fname))
myupfileexists = exists(fname)
upload = (input() == "1")
if test: print("upload : ", upload)
if test: print(' %Tst --- myupfileexists:', myupfileexists)
# csv data (always) to temporary

# if not upload:
#    with open(fname,'r') as data:
#       with open (screen, 'w') as f:
#          for line in data.readlines():
#             if line.rstrip()=='EOD': break
#             if test: print(' $'+line.rstrip()+'$')
#             f.write(line)
            
         
keywei = input()
print(' key_wei,{:>27}    |'.format(keywei))
keynum = input()
print(' key_num,{:>27}    |'.format(keynum))
ntrials = input()
print(' ntrials,{:>27}    |'.format(ntrials))
iseed = input()
print(' iseed,  {:>27}    |'.format(iseed))
confidence = float(input())
print(' confidence,{:24.2f}    |'.format(confidence))
ishow = input()
print(' Show,   {:>27}    |'.format(ishow))
work_dir = input()
out = work_dir + "out.png"
print(''.join([' ', '-'*39, '+', '-'*39]))
#=============================Input end=================================
def printf(fnam):
   with open(fnam, 'r') as f: print(f.read()) # d = f.read(); print(d)
   return

if test:
   print(' %Tst --- fname'); printf(fname)

if upload:
   daf = pd.read_excel(fname, sheet_name='camions', header=0)
else:
   fin = open(fname, 'r'); fout = open(work_dir + pid, 'w+')
   mydict = {',':'.', ';':','}; mydata = fin.read()
   for key, value in mydict.items(): mydata = mydata.replace(key, value)
   fout.write(mydata)
   fout.seek(0)
   daf = pd.read_csv(work_dir + pid) #, sheet_name='camions', index=False, header=0)
   if test:
      print(' %Tst ... REPLACED'); printf(work_dir + pid)

#print(daf) # whole sheet data
if test:
   arr = daf.values; print(' %Tst --- daf.values'); print(arr)
###arr = daf.to_numpy() # Py3 ? ###print(arr)

rows = len(daf); cols = len(daf.columns)
print(' rows, cols,{:>12}{:>12}    |'.format(rows, cols))

wei_v = np.array(daf[keywei], dtype=float)
num_v = np.array(daf[keynum])
sumnum = np.sum(num_v); sumwei = np.sum(wei_v)
print(' sum_Num, _Wei,{:>9}{:12.1f}    |'.format(sumnum, sumwei))
ave = sumwei / sumnum
print(' mu_hat,    {:24.4f}    |'.format(ave))

ave_v = wei_v / num_v
sigma2_hat = np.sum(num_v*((ave_v-ave)**2)) / (rows-1)
sigma_hat = np.sqrt(sigma2_hat)
print(' sig2_h, sig_h,{:9.4f}{:12.4f}    |'.format(sigma2_hat, sigma_hat))

#ntrucks, num_v, wei_v, iseed, ntrials, zmuh_v, varh_v
import modConfintsimul as CI ### print(CI.confintsim.__doc__)

ave_v, var_v = CI.confintsim (num_v, wei_v, iseed, ntrials)
mi, ma = min(ave_v), max(ave_v)
print(' ave_v in   {:12.3f}{:12.3f}    |'.format(mi, ma))

#=================================PLOT==================================
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "serif"
wid = 5.5; h = wid / ((np.sqrt(5.) + 1) / 2) * 2
plt.figure(figsize=(wid, h))
plt.subplot(2, 1, 1)
counts, bins, patches = plt.hist(x=ave_v, bins='auto', color='#0411aa', \
 alpha=0.7, rwidth=0.85, density=True)
###print(' counts,', counts); print(' bins,', bins)
perc = (100 - confidence) / 2
pL, pR = np.percentile(ave_v, perc), np.percentile(ave_v, 100-perc)
print(' Percentiles:  {:>26}'.format('|'))
print('   For mu,     {:9.3f}{:12.3f}    |'.format(pL, pR))

plt.xlabel('ave'); plt.ylabel('pdf')
plt.tick_params(direction="in")

plt.twinx()
counts, bins, patches = plt.hist(x=ave_v, bins='auto', color='#bbbbbb', \
 alpha=0.7, rwidth=0.75, density=True, cumulative=True)
plt.grid(axis='y', alpha=0.75)
plt.ylabel('cdf')
plt.tick_params(direction="in")
plt.title('Average (ave)') #plt.text(23, 45, r'$\mu=15, b=3$')
#maxfreq = n.max()
# Set a clean upper y-axis limit.
#plt.ylim(ymax=np.ceil(maxfreq/20)*20 if maxfreq % 20 else maxfreq+20)
plt.ylim(bottom=0, top=1)

plt.subplot(2, 1, 2)
counts, bins, patches = plt.hist(x=var_v, bins='auto', color='green', \
 alpha=0.7, rwidth=0.85)
pL, pR = np.percentile(var_v, perc), np.percentile(var_v, 100-perc)
pL, pR = np.sqrt(pL), np.sqrt(pR)
#print(' Prc.tiles: sigma,{:6.3f}{:12.3f}    |'.format(pL, pR))
print('   For sigma,  {:9.3f}{:12.3f}    |'.format(pL, pR))
plt.grid(axis='y', alpha=0.75)
plt.xlabel('var'); plt.ylabel('Frequency')
plt.tick_params(direction="in")
plt.title('Variance (var)') #plt.text(23, 45, r'$\mu=15, b=3$')
maxfreq = counts.max()
# Set a clean upper y-axis limit.
plt.ylim(bottom = 0, top=np.ceil(maxfreq/20)*20 if maxfreq % 20 else maxfreq+20)

plt.tight_layout()
#plt.savefig(out)
#plt.show()
fpath = 'tmp/'+pid+'out.png'
if test: print(' %Tst --- fpath: ', fpath)
plt.savefig(fpath)

import base64
with open(fpath, 'rb') as image_file:
   encoded = base64.b64encode(image_file.read())
   encoded = str(encoded)[2:-1]
print ('</pre><center><img src="data:image/png; base64, '+encoded+ \
 '" /></center>')
os.remove(fpath)
