Chronicle/TimeLine/0709FirstPlasma/Shot4/rsrc/includes/analysis/Basics/1012HistoricalAnalysis.ON/main.py

#!/usr/bin/python2
# -*- coding: utf-8 -*-


""" CREATED: 7/2012
    AUTHOR: MICHAL ODSTRČIL
"""


import matplotlib
matplotlib.rcParams['backend'] = 'Agg'
matplotlib.rc('font',  size='10')
matplotlib.rc('text', usetex=True)  # FIXME !! nicer but slower !!!

import pygolem_lite

from pygolem_lite import Shot


from numpy import *
from pygolem_lite.config import *
from pygolem_lite.modules import *
from pygolem_lite.sql import *
from matplotlib.pyplot import *
import time
from shutil import copy, move
import os
from scipy.interpolate import interp1d
import re

#element_names = ['H','O','He','C','N','M1','MIV']
#element_signs = ['*','o','D','+','x','.','s']
element_names = ['C','O','N']
element_signs = ['*','o','D']
#element_names = ['H','O','C','N','M1']
#element_signs = ['*','o','+','x','.']
def analysis():
    print "==========analysis" 
    
    shot_num = Shot().shot_num
    N =  500 # 3000#     # !!!!!! number of shots in history !!!!!
    shots = arange(N) + shot_num - N+1

    start_shots = get_session_list(shots)[1]
    save("start_shots", start_shots)
    print "start_shots saved !!!"
    

    save_hist('pressure_initial', 'pressure_all',  shots)
    save_hist('electron_temperature_max', "temp_max_all",  shots)
    save_hist('temperature_mean', 'temp_all', shots)
	
    #try:
    for i in element_names:
	save_hist('spectrometr:mean_relative_density_'+i, 'impur_dens_'+i, shots)
    #except Exception,e:
	#print str(e)
	
    save_hist('spectrometr:mean_temperature', 'impur_temp_all', shots)

    #save_hist('electron_confinement_t98', 'tau_all',shots)
    #save_hist('electron_density_mean', "dens_all", shots)
    save_hist('noise_level', "noise_all",  shots)
    #photo = save_hist('photodiode_mean', "photo_all", shots)
    save_hist('plasma_current_mean', "current_all",  shots)
    #uloop = save_hist('loop_voltage_mean', "uloop_all", shots)
    #save_hist('Komora/Aktual_DoutnavyVyboj', "glow_dis_all", shots)
    #save_hist('Komora/Aktual_VypekaniKomory', "baking_all", shots)
    #save_hist('Komora/Aktual_VypekaniKrizu', "baking_cross_all", shots)
    save_hist('pressure_chamber', "pipes_pressure_all", shots)
    #shots_R, data_R = save_hist('chamber_resistance', "chamber_resistance_all", shots[shots>9500])
    #shots_R0, data_R0 = save_hist('chamber_resistance_old', "chamber_resistance_old_all", shots[shots>9500])
    #shots_P, data_P = save_hist('plasma', "plasma_all", shots)
    #save_hist('chamber_temperature', "ch_temp_all", shots)

    #ind = in1d(shots_R, shots_P[data_P == 1])
    #savetxt('chamber_resistance_all_plasma', array([shots[ind], data_R[ind]]).T,  line_format="%g")
    #savetxt('chamber_resistance_all_noplasma', array([shots[~ind], data_R[~ind]]).T,  line_format="%g")
    #ind = in1d(shots_R0, shots_P[data_P == 1])
    #savetxt('chamber_resistance_old_all_plasma', array([shots[ind], data_R0[ind]]).T,  line_format="%g")
    #savetxt('chamber_resistance_old_all_noplasma', array([shots[~ind], data_R0[~ind]]).T,  line_format="%g")
    save_hist('spectrometr:mean_radiation_power', "rad_power_all", shots)
    save_hist('input_power_plasma_mean', "input_power_all", shots)


def save_hist(diagn, name,  shot_range):
    t = time.time()
    N = len(shot_range)
    
    #print diagn
    
    data = load_data(diagn, shot_range)
    
    #print data.keys()
    
    data_final  = array([data['shot'], data[diagn.lower()]]).T

    savetxt(name, data_final ,  fmt="%g")

    #print "time", time.time()  - t
	
    #return shots, data


def plot_data(file_type):
    print "=============plot data " 
    
    start_shots = load("start_shots.npy")
    vl = [ start_shots[i][0] for i in range(len(start_shots)) ]
    an = [ {'text':start_shots[i][1]  , 'pos':[start_shots[i][0], None], 'angle':270, 'fontsize':"small" }  for i in range(len(start_shots)) ]
    #print "vlines", vl
    #print "annotate", an
    ylim = [0,None]
    plot_size = 12# max(12, (int(start_shots[-1][0]) - int(start_shots[0][0]))/50);   # width of the plots
    params = dict(xlabel="Shot number", tvec_rescale= 1, plot_limits= False, vlines = vl, annotate = an, ygrid = True, markersize=5)
    print_params = dict( figsize=(plot_size,4), dpi=100, file_type=file_type,  legend_loc = 'upper left' )
    
    #print "plot_size", plot_size, int(start_shots[-1][0]) , int(start_shots[0][0])
    
    #d = get_data('temp_all', 'Mean temperature', 'T [eV]' , ylim = [0,75] , tvec_rescale= 1, plot_limits= False, line_format='.', 
    #xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, markersize=5)
    #paralel_multiplot(d, 'Temperature evolution', 'temp', **print_params)

    ###get_data('temp_max_all', 'Max temperature', 'T [eV]' , ylim = [0,75] , tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, markersize=5)
    ###get_data('impur_temp_all', 'Specrometr temperature', 'T [eV]', tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, ylim = [0,75], markersize=5 )
    #exit()

    try:
      data1 = [[get_data('temp_all', 'Mean temperature', 'T [eV]' , ylim = [0,70] , line_format='.',  **params),
	  get_data('temp_max_all', 'Max temperature', 'T [eV]' , ylim = [0,70] ,  line_format='.', **params),
	  get_data('impur_temp_all', 'Specrometr temperature', 'T [eV]',   ylim = [0,70], line_format='.',**params) ]]
      paralel_multiplot(data1, 'Temperature evolution', 'temp', **print_params)
    except Exception, e:
      print str(e)
      
    #exit()
    

  
    try:
	 #  
      data2 = [[get_data('pressure_all', 'Init pressure', 'P [mPa]' , ylim = [0.1,20] ,  yscale="log",line_format='g.', **params),
      get_data('pipes_pressure_all', 'Pipes pressure', 'P [mPa]' , ylim = [0.1,20] , yscale="log", data_rescale = 1e-3 , line_format='b.', **params)]]
      paralel_multiplot(data2, 'Pressure evolution', 'pressure', **print_params)
    except Exception, e:
      print str(e)
      
    #print "data1", data1

    #exit()
    
    #try:
      #data9 = [[get_data('glow_dis_all', 'Glow discharge', 'ON/OFF' , ylim = [0,1.1] , tvec_rescale= 1, plot_limits= False, line_format='r-', xlabel="Shot number", vlines = vl, annotate = an, markersize=5),
      #get_data('baking_all', 'Chamber baking', 'ON/OFF' , ylim = [0,1.1] , tvec_rescale= 1, plot_limits= False, line_format='g-', xlabel="Shot number", vlines = vl, annotate = an, markersize=5),
      #get_data('baking_cross_all', 'Cross baking', 'ON/OFF' , ylim = [0,1.1] , tvec_rescale= 1, plot_limits= False, line_format='b-', xlabel="Shot number", vlines = vl, annotate = an, markersize=5)]]
      
      #paralel_multiplot(data9, 'Chamber conditioning', 'vacuum', **print_params)
    #except Exception, e:
      #print str(e)
    
    
    #try:
      #data3 = get_data('tau_all', 'Confinement', 'tau [s]' , ylim = ylim , tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, markersize=5) 
      #paralel_multiplot(data3, 'Confinement evolution', 'tau', **print_params)
    #except Exception, e:
      #print str(e)
    
    #try:
      #data4 = get_data('dens_all', 'Density', 'n$_{e}$' , ylim = ylim , tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, markersize=5) 
      #paralel_multiplot(data4, 'Density evolution', 'dens', **print_params)
    #except Exception, e:
      #print str(e)
    
    #try:
      #data5 = get_data('photo_all', 'Mean emiss', 'U [V]' , ylim = ylim , tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True) 
      #paralel_multiplot(data5, 'Photodiode evolution', 'emiss', **print_params)
    #except:
      #pass
      

    #try:
      #data7 = get_data('uloop_all', 'Loop voltage', 'U [V]' , ylim = ylim , tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True) 
      #paralel_multiplot(data7, 'Loop voltage evolution', 'uloop', **print_params)
    #except:
      #pass
    try:
      data8 = get_data('noise_all', 'Noise', 'U [V]' , ylim = ylim ,   yscale="log", line_format='.', **params ) 
      multiplot(data8, 'Noise evolution', 'noise', **print_params)
    except Exception, e:
      print str(e)


    #try:
      #data11 = [[get_data('chamber_resistance_all_plasma', 'New-plasma', 'R [Ohm]' ,  tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, yscale='log', markersize=5), get_data('chamber_resistance_all_noplasma', 'New-noplasma', 'R [Ohm]' ,  tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, yscale='log', markersize=5)   ], 
      #[get_data('chamber_resistance_old_all_plasma', 'Old-plasma', 'R [Ohm]' , tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, yscale='log', markersize=5), get_data('chamber_resistance_old_all_noplasma', 'Old-noplasma', 'R [Ohm]' , tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, yscale='log', markersize=5) ]]
      #paralel_multiplot(data11, 'Chamber resistance', 'resistance', (plot_size,6), 100, 'vertical', file_type)
    #except Exception, e:
      #print str(e)
    
    
    #try:
      #data8 = get_data('ch_temp_all', 'Chamber temperature', 'T [C]' , ylim = ylim , tvec_rescale= 1, plot_limits= False, line_format='xr', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, markersize=5) 
      #paralel_multiplot(data8, 'Chamber temperature', 'ch_temp', **print_params)
    #except Exception, e:
      #print str(e)
    
    try:
      data8 = get_data('current_all', '', 'I [kA]' , ylim = ylim ,  data_rescale=1e-3,line_format='.', **params) 
      multiplot(data8, 'Plasma Current' , 'current', **print_params)
    except Exception, e:
      print str(e)

    
    try:
      data9 = [[ get_data('impur_dens_'+element_names[i], 'n '+element_names[i], 'n [a.u.]' ,  tvec_rescale= 1, plot_limits= False, xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, yscale = 'log', ylim=[1e-3, 5], line_format=element_signs[i], markersize=4 ) for  i in range(len(element_names)) ]]
      paralel_multiplot(data9, 'Relative impurity density', 'impurity', **print_params)
    except Exception, e:
      print str(e)

    try:
        
      data9 = [[ get_data('rad_power_all', 'Output power spectrometer', 'P [kW]' , data_rescale=1e-3, ylim=[0, 20],line_format='g.', **params), 
      get_data('input_power_all', 'Input ohmic power', 'P [kW]' , data_rescale=1e-3, ylim=[0, 20 ], line_format='r+', **params )   ]]
      paralel_multiplot(data9, 'Mean power balance', 'rad_power', **print_params)
    except Exception, e:
      print str(e)

    #try:
      #data10 = get_data('impur_temp_all', 'Specrometr temperature', 'T [eV]', tvec_rescale= 1, plot_limits= False, line_format='.', xlabel="Shot number", vlines = vl, annotate = an, ygrid = True, ylim=ylim ) 
      #paralel_multiplot(data10, 'Specrometr temperature', 'impur_temp', **print_params)
    #except:
      #print str(e)
    
    
    #os.system('convert -resize 150x120\! total_plot.png icon.png')

    #print "===== plotting done ===== "
    #data = data_1 + data_2 +data_3 + data_4
    
    paralel_multiplot((data1 if 'data1' in locals() else []) + (data2 if 'data2' in locals() else []), "" , 'icon', (4,3), 40)


    

def main():
    #if sys.argv[1] ==  "analysis":
	
    #exit()
    if sys.argv[1] ==  "plots":
	analysis()
	plot_data('png')
	saveconst('status', 0)
	print "==================== saveconst('status', 0) ="

	print "==="*20, "generate svgz !!!"
	plot_data('svgz')
	saveconst('status', 0)



if __name__ == "__main__":
    main()