# Program to illustrate how integrating on a source drives down the random noise but not the systematic effects.
# Creates a spectrum with either pure random noise or some systematic baseline structure, with some small signal injected in a small channel
# range. Plots the result of co-adding multiple such spectra, so that the final source is only clearly visible after some integration.

import os
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot
import matplotlib.pyplot as plt
import numpy
import math
from math import *

from matplotlib.ticker import AutoMinorLocator
XminorLocator = AutoMinorLocator()
YminorLocator = AutoMinorLocator(4)

# LaTeX like fonts in the figure
#plt.rc('text', usetex=True)
plt.rc('font', family='serif')
#plt.rc('font', serif='Palatino')
#plt.rc('font', cursive='Zapf Chancery')
#plt.rc('font', monospace='Courier')


# Change to directory where script is located
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)


outfile = 'SinusoidalPlot.png'


x = numpy.arange(0,200,1)

fig=pyplot.figure()
fig.set_size_inches(750.0/100.0,750.0/100.0)


# Create a noisy spectrum with some small signal present in a few channels
def spect():
   spectrum = numpy.zeros(200)
   for i in range(len(spectrum)):
      # Pure random, flat baseline
      #spectrum[i] = (2.0*numpy.random.random()) - 1.0

      # Random noise + sinusoidal baseline
      spectrum[i] = (2.0*numpy.random.random()) - 1.0 + 0.3*math.sin(math.radians(float(i)*4.0))
      if i >= 95 and i <=105:
         spectrum[i] = spectrum[i] + 0.30
	
   return spectrum

spectra = spect()
sumspec = spectra

for i in range(1,100):
   print('Plotting',i)
   sumspec = sumspec+spect()
   stackspec = sumspec/float(i)
   
   # Must set up the figure BEFORE doing the actual plotting. Ensure a square aspect ratio
   fig=pyplot.figure()
   fig.set_size_inches(750.0/100.0,750.0/100.0)

   # Plot the spectrum itself plus the zero line
   pyplot.plot(x,stackspec, color='black')
   pyplot.plot([0,200],[0,0], color='black')

   # Enforce strict limits
   pyplot.xlim((0,200))
   pyplot.ylim((-1.1,1.1))
			
   csfont = {'fontname':'Liberation Serif','fontsize':20}

   pyplot.xlabel('Channel', **csfont)
   pyplot.ylabel('Flux', **csfont)

   plot = fig.add_subplot(111)
   plot.tick_params(axis='both', which='major', labelsize=10)
   plot.tick_params(axis='both', which='minor', labelsize=10)

   axes = plt.gca()
   #axes.xaxis.set_ticklabels([])
   #axes.yaxis.set_ticklabels([])
   axes.xaxis.set_minor_locator(XminorLocator)
   axes.yaxis.set_minor_locator(YminorLocator)

   pyplot.savefig(outfile.split('.png')[0]+'_'+str(i)+'.png',dpi=100,facecolor='white',bbox_inches='tight')
   pyplot.close('all')




