In [1]:
#Basic setup 
from __future__ import print_function
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import numpy as np
from urllib.request import urlopen
import os
from IPython import get_ipython
import string
import sys
from pylab import *
from scipy.signal import argrelextrema
import scipy.optimize as spo
from scipy.optimize import fsolve
from numpy import nan
from numpy import math

def is_interactive_(): # are we in jupyter ??
    import __main__ as main
    return not hasattr(main, '__file__')

def is_interactive(): # are we in jupyter ??
    import __main__ as main
    return 0 


if is_interactive():
    %matplotlib inline

BaseURL = "http://golem.fjfi.cvut.cz/utils/data/" #global

R_BPP=200 # Ohm
R_BPP_LP=23 # Ohm


Date='130717'
MainMission='BPP & BPP_LP $U_{bias}$ scan'
Comment='BPP used to measure $I^{BPP}$ current, BPP_LP used to measure $I^{BPP\_LP}$ current'
OtherKeyParams='BPP probe distance from plasma centre $r_{BPP\_LP}=70$ mm,'+'$R_{BPP}='+str(R_BPP)+' \Omega$'+'$R_{BPP\_LP}='+str(R_BPP_LP)+' \Omega$'
SmoothCoefficient=100
CurrentScale=1000 # so .. mA

#DASsetup: (Ne, osciloskop nejeden na 1 us, musime to obejit)
RecordLength=10000
TektronixDataAnalysisStart=1000
TektronixDataAnalysisEnd=7000
TektronixDataAnalysisStep=500
TimeCalibShift=4000
TimeCalibScale=4

FigSize=10,8
def FigDef():plt.figure(figsize=(10, 8), dpi= 80, facecolor='w', edgecolor='k')


SignalIdents=[\
              ['U@R_bpp','$U@R_{BPP}$'],\
              ['U@R_bpp_lp','$U@R_{BPP\_LP}$'],\
             ]
KeyParameter=['Biasing voltage','$U_{bias}$','V']

Setup=[\
       [24411,0,'o'],\
       [24412,13,'o'],\
       ]




 
In [2]:
def running_mean(l, N):
    # Also works for the(strictly invalid) cases when N is even.
    if (N//2)*2 == N:
        N = N - 1
    front = np.zeros(N//2)
    back = np.zeros(N//2)
    for i in range(1, (N//2)*2, 2):
        front[i//2] = np.convolve(l[:i], np.ones((i,))/i, mode = 'valid')
    for i in range(1, (N//2)*2, 2):
        back[i//2] = np.convolve(l[-i:], np.ones((i,))/i, mode = 'valid')
    return np.concatenate([front, np.convolve(l, np.ones((N,))/N, mode = 'valid'), back[::-1]])


def running_means(data, odkud, kam, krok):
    
    Means = [None] * int((kam-odkud)/krok)
    for i in range(0,kam-odkud,krok):
        Suma=0
        for j in range(0,krok):
            Suma=Suma+data[i+j]
        Means[int(i/krok)] = [odkud+i+krok/2,Suma/(krok)]
    return(Means)
    

def mkdir(dir):  
    try:os.makedirs(dir) 
    except OSError:pass
    


def GetData(ShotNo):
    ShotNoStr=str(ShotNo)
    if os.path.isdir(ShotNoStr+'/Basics'): return
    print('Getting ..'+ShotNoStr+'/Basics')
    mkdir(ShotNoStr)
    mkdir(ShotNoStr+'/Basics')
    
    os.system('wget http://golem.fjfi.cvut.cz/shots/' + ShotNoStr + '/basicdiagn/Btoroidal.npz -O '+ShotNoStr+'/Basics/Btoroidal.npz');
    os.system('wget http://golem.fjfi.cvut.cz/shots/' + ShotNoStr + '/basicdiagn/Iplasma.npz -O '+ShotNoStr+'/Basics/Iplasma.npz');
    os.system('wget http://golem.fjfi.cvut.cz/shots/' + ShotNoStr + '/basicdiagn/Uloop.npz -O '+ShotNoStr+'/Basics/Uloop.npz');
    os.system('wget http://golem.fjfi.cvut.cz/shots/' + ShotNoStr + '/basicdiagn/graphpres.png -O '+ShotNoStr+'/Basics/graphres.png');
    #Plasma parameters 
    PlasmaStart=int(float(np.loadtxt(urlopen(BaseURL+ShotNoStr+'/plasma_start')))*1e6) # in us
    PlasmaEnd=int(float(np.loadtxt(urlopen(BaseURL+ShotNoStr+'/plasma_end')))*1e6) # in us
    np.savetxt(ShotNoStr+'/Basics/PlasmaStart',[PlasmaStart], delimiter=" ", fmt="%s")
    np.savetxt(ShotNoStr+'/Basics/PlasmaEnd',[PlasmaEnd], delimiter=" ", fmt="%s")
    np.savetxt(ShotNoStr+'/Basics/TektronixDataAnalysisStart',[TektronixDataAnalysisStart], delimiter=" ", fmt="%s")
    np.savetxt(ShotNoStr+'/Basics/TektronixDataAnalysisEnd',[TektronixDataAnalysisEnd], delimiter=" ", fmt="%s")


    for signal in SignalIdents:
        os.system('wget '+BaseURL + ShotNoStr + '/' + signal[0] + ' -O '+ShotNoStr+'/Basics/'+signal[0]+'4WholeTime.txt');
    

        
    
def DischargeBasics(ShotNo):
    
    PlasmaParameters=PlasmaParametersDef(ShotNo)
    PlasmaStart=PlasmaParameters[0]
    PlasmaEnd=PlasmaParameters[1]
    ShotNoStr=str(ShotNo)

    
    Time = np.linspace(PlasmaStart,PlasmaEnd,(PlasmaEnd-PlasmaStart))
    TimeTektronix = np.linspace(TektronixDataAnalysisStart,TektronixDataAnalysisEnd,(TektronixDataAnalysisEnd-TektronixDataAnalysisStart))

    #rint(Time);print(TimeTektronix)
        
    Btoroidal=np.load(ShotNoStr+'/Basics/Btoroidal.npz');
    Iplasma=np.load(ShotNoStr+'/Basics/Iplasma.npz');
    Uloop=np.load(ShotNoStr+'/Basics/Uloop.npz');
    
    f = plt.figure(figsize=(20.0, 5.0))
    f,ax = plt.subplots(5,sharex=True);plt.subplots_adjust(hspace=0.001)
    f.set_size_inches(FigSize)
    ax[0].set_title('#' + str(ShotNo))
    ax[0].plot(Time/1000,Uloop['data'][PlasmaStart:PlasmaEnd],label='Loop voltage');ax[0].set_ylabel('$U_l$ [V]');ax[0].set_ylim(0,);ax[0].legend(loc=0)
    ax[1].plot(Time/1000,Btoroidal['data'][PlasmaStart:PlasmaEnd],label='Toroidal magnetic field');ax[1].set_ylabel('$B_t$ [T]');ax[1].set_ylim(0,);ax[1].legend(loc=0)
    ax[2].plot(Time/1000,Iplasma['data'][PlasmaStart:PlasmaEnd]/1000,label='Plasma current');ax[2].set_ylabel('$I_p$ [kA]');ax[2].set_ylim(0,);ax[2].legend(loc=0)
    graphindx=3
    for signal in SignalIdents:
        PlasmaSignal=np.loadtxt(ShotNoStr+'/Basics/'+signal[0]+'4WholeTime.txt')[TektronixDataAnalysisStart:TektronixDataAnalysisEnd]
        ax[graphindx].plot((TimeTektronix*TimeCalibScale+TimeCalibShift)/1000,PlasmaSignal[0:,1],label=signal[1],color='blue');ax[graphindx].legend(loc=0)
        PlasmaSignalSmoothed=np.loadtxt(ShotNoStr+'/Basics/'+signal[0]+'@plasma_smoothed.txt')
        ax[graphindx].plot((TimeTektronix*TimeCalibScale+TimeCalibShift)/1000,PlasmaSignalSmoothed*0,label='0',color='green')
        ax[graphindx].plot((TimeTektronix*TimeCalibScale+TimeCalibShift)/1000,PlasmaSignalSmoothed,label='smoothed',color='red')
        PlasmaSignalMeans=np.loadtxt(ShotNoStr+'/Basics/'+signal[0]+'@plasma_mean.txt')
        ax[graphindx].plot((PlasmaSignalMeans[:,0]*TimeCalibScale+TimeCalibShift)/1000,PlasmaSignalMeans[:,1],label='discrete',color='y',marker='*',linestyle='');ax[graphindx].set_ylabel(signal[1]);ax[graphindx].legend(loc=1)
        graphindx=graphindx+1
    ax[graphindx-1].set_xlabel('$t$ [ms]');#ax[6].set_ylim(-200,200)
    ax[graphindx-1].set_xlim(PlasmaStart/1000,PlasmaEnd/1000)
    plt.savefig(str(ShotNo)+'/Basics/BasicDiagWithSignals.jpg', bbox_inches='tight')
    if is_interactive():plt.show();
    plt.close();
    
    

    
def htmlgeneration(ShotNo,UBt,PlasmaStart, PlasmaEnd, Time):
    print("html generation ...")
    ShotNoStr=str(ShotNo)

    os.system('rm '+str(ShotNo)+'/index.html');
    fileid = open(str(ShotNo)+'/index.html','a+')
    fileid.write('<html><head><title>VA char @ GOLEM</title>\
    <style>\
    div.grafy30 {display:inline-block;width: 30%;}\
    div.grafy20 {display:inline-block;width: 20%;}\
    .grafy20 img {width: 100%;}\
    .grafy30 img {width: 100%;}\
    </style>\
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\
    <style></style>\
    <script type="text/x-mathjax-config">MathJax.Hub.Config({tex2jax: {inlineMath: [[\'$\',\'$\'], [\'\\(\',\'\\)\']]}});</script>\
    <script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>\
    </head><body><center>')
    fileid.write('<h2><a href="../index.html">Home</a></h2>')
    fileid.write('<h1>BPP experiments @ the tokamak GOLEM</h1>')
    fileid.write('<h3>Essential parameters:</h3><table><tr><td><ul>\
    <li>Voltage divider: 1:'+str(HWNapetovyDelic)+'</li>\
    <li>The shot: <a href="http://golem.fjfi.cvut.cz/shots/'+ShotNoStr+'">'+ShotNoStr+'</a></li>\
    <li>The DAS used: <a href="http://golem.fjfi.cvut.cz/shots/'+ShotNoStr+'/DAS/1011Papouch_St.ON/">Papouch_St</a></li>\
    </ul></td></tr></table>')
    fileid.write('<div class="grafy30"><h2>Experimental setup</h2>')
    fileid.write('<h3>Ball pen probe @ North-East port</h3>')
    fileid.write('<center>\
    <a href="http://golem.fjfi.cvut.cz/wikiraw/Experiments/EdgePlasmaPhysics/ParticleFlux/BallPenProbe/Experiments/BottomPosition/setup/vI/ExpSetup-BPP.png">\
    <img src="../setup/ExpSetup-BPP.png" width="100%"></a><br>\
    <a href="/wikiraw/Experiments/EdgePlasmaPhysics/ParticleFlux/BallPenProbe/Experiments/BottomPosition/setup/">setup</a></div>')
    fileid.write('<div class="grafy30"><h2>The discharge #'+ShotNoStr+'</h2>')
    fileid.write('<h3>Basic diagnostics</h3>\
    <a href="http://golem.fjfi.cvut.cz/shots/'+ShotNoStr+'/"><img src="Basics/graphres.png" width="100%"></a><br/>\
    Plasma start:<a href="ShotNo/PlasmaStart">'+str(PlasmaStart)+'</a> us\
    Plasma end:<a href="ShotNo/PlasmaEnd">'+str(PlasmaEnd)+'</a> us</div>\
    <h3>The BPP data vs diagnostics</h3>\
    <a href="Basics/BasicDiagWithBPP.jpg"><img src="Basics/BasicDiagWithBPP.jpg" width="30%"></a><br/>\
    <a href="ShotNo/">Reference shot data</a><br/></div>')
    
    fileid.write('</body></html>')
    fileid.close()
    

    
def Initials(ShotNo):
    ShotNoStr=str(ShotNo)
    
    
def PlasmaParametersDef(ShotNo):
    return [\
    int(np.loadtxt(str(ShotNo)+'/Basics/PlasmaStart')),\
    int(np.loadtxt(str(ShotNo)+'/Basics/PlasmaEnd'))\
            ]
    

    
    
def IndividualShot(IndvSetup):
    ShotNo=IndvSetup[0];print( 'Doing', ShotNo)
    ShotNoStr=str(ShotNo)
    Initials(ShotNo)
    PlasmaParameters=PlasmaParametersDef(ShotNo)
    PlasmaStart=PlasmaParameters[0]
    PlasmaEnd=PlasmaParameters[1]
    
    
    for signal in SignalIdents:
        PlasmaSignal=np.loadtxt(ShotNoStr+'/Basics/'+signal[0]+'4WholeTime.txt')[TektronixDataAnalysisStart:TektronixDataAnalysisEnd]
        np.savetxt(ShotNoStr+'/Basics/'+signal[0]+'@plasma.txt',PlasmaSignal, delimiter=" ", fmt="%s")
        PlasmaSignalSmoothed=running_mean(PlasmaSignal[:,1],SmoothCoefficient)
        np.savetxt(ShotNoStr+'/Basics/'+signal[0]+'@plasma_smoothed.txt',PlasmaSignalSmoothed, delimiter=" ", fmt="%s")
        PlasmaSignalMean=running_means(PlasmaSignal[:,1],TektronixDataAnalysisStart,TektronixDataAnalysisEnd, TektronixDataAnalysisStep)
        np.savetxt(ShotNoStr+'/Basics/'+signal[0]+'@plasma_mean.txt',PlasmaSignalMean, delimiter=" ", fmt="%s")
    

       
    DischargeBasics(ShotNo)
    #htmlgeneration(ShotNo,1300,PlasmaStart, PlasmaEnd, Time)
    


def GlobalFigs():
    mkdir('GlobalFigs')
    Time = np.linspace(0,40000,40000)
    

    for graph in GraphSetup:
        FigDef()
        for shot in LoopSetup:
            data=np.load(str(shot[0])+'/Basics/'+graph[0]+'.npz')
            plt.plot(Time/1000,data['data'],label='#'+str(shot[0])+' ('+ KeyParameter[1]+'='+str(shot[1])+ KeyParameter[2]+')');
            plt.legend(loc=0)
        plt.title('Reproducibility for: '+graph[2])
        plt.xlabel('$t$ [ms]')
        plt.ylabel(graph[1])
        plt.savefig('GlobalFigs/Reproducibility_'+graph[0]+'.jpg', bbox_inches='tight')
        if is_interactive():plt.show();
        plt.close();   
    
    

     
In [3]:
# HTML generation
def HtmlGeneration():
    print("Global html generation ...")

    os.system('rm index.html');
    fileid = open('index.html','a+')
    fileid.write('<html><head><title>VA char @ GOLEM</title>\
    <style>\
    div.grafy30 {display:inline-block;width: 30%;}\
    div.grafy20 {display:inline-block;width: 20%;}\
    .grafy20 img {width: 100%;}\
    .grafy30 img {width: 100%;}\
    </style>\
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\
    <style></style>\
    <script type="text/x-mathjax-config">MathJax.Hub.Config({tex2jax: {inlineMath: [[\'$\',\'$\'], [\'\\(\',\'\\)\']]}});</script>\
    <script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>\
    </head><body><center>')
    fileid.write('<h2>BPP experiments @ the tokamak GOLEM 2016,2017</h2>')
    fileid.write('<h3>Essential parameters:</h3><table><tr><td><ul>\
    <li>Main mission:'+MainMission+'</li>\
    <li>Date:'+Date+'</li>\
    <li>'+Comment+'</li>\
    <li>'+OtherKeyParams+'</li>\
    </ul></td></tr></table>')
    fileid.write('<div class="grafy30"><h2>Experimental setup</h2>')
    fileid.write('<h3>Ball pen probe @ North-East port</h3>')
    fileid.write('<center>\
    <a href="ExpSetup/ExpSetup.svg">\
    <img src="ExpSetup/ExpSetup.png" width="100%"></a><br>\
    <a href="'+'ExpSetup/">Experimental setup</a></div>\
    <h2>Discharges involved</h2>\
    <table border="1"><tr>\
    <th>Discharge #</th>\
    <th>'+KeyParameter[1]+'['+ KeyParameter[2]+']</th>\
    <th>Data</th></tr>')
    for shot in LoopSetup: 
        fileid.write('<tr>\
        <td><a href="http://golem.fjfi.cvut.cz/shots/'+str(shot[0])+'">#'+str(shot[0])+'</td>\
        <td>'+str(shot[1])+'</td>\
        <td><a href="'+str(shot[0])+'/Basics/">link</a></td>\
        </tr>')
    for shot in LoopSetup: 
        fileid.write('</table><div class="grafy30"><h2>#'+str(shot[0])+','+ KeyParameter[1] +'='+str(shot[1])+ KeyParameter[2]+'</h2>\
        <a href="'+str(shot[0])+'/index.html">\
        <img src="'+str(shot[0])+'/Basics/BasicDiagWithBPP.jpg" width="100%"></a></div>')    
    fileid.write('<h2>Reproducibility</h2>')
    for graph in GraphSetup:
        fileid.write('<div class="grafy30"><h2>'+graph[0]+':</h2>\
        <a href="GlobalFigs/Reproducibility_'+graph[0]+'.jpg">\
        <img src="GlobalFigs/Reproducibility_'+graph[0]+'.jpg" width="100%"></a></div>')
    fileid.write('<h2>Experimental photo</h2>')
    fileid.write('<img src="ExpSetup/expphoto_s.jpg" width="75%"/>')
    fileid.write('<h2>Experiment specific data</h2>\
    <table border="1"><tr>\
    <th>Discharge #</th>\
    <th>'+KeyParameter[1]+'['+ KeyParameter[2]+']</th>\
    <th>Data directory</th>\
    <th>Raw BPP_LP data</th>\
    <th>Smoothed BPP_LP data</th>\
    <th>Raw BPP data</th>\
    <th>Smoothed BPP data</th>\
    </tr>')
    for shot in LoopSetup: 
        fileid.write('<tr>\
        <td><a href="http://golem.fjfi.cvut.cz/shots/'+str(shot[0])+'">#'+str(shot[0])+'</td>\
        <td>'+str(shot[1])+'</td>\
        <td><a href="'+str(shot[0])+'/Basics/">link</a></td>\
        <td><a href="'+str(shot[0])+'/Basics/U@R_bpp_lp4WholeTime.txt">link</a></td>\
        <td><a href="'+str(shot[0])+'/Basics/U@R_bpp_lp@plasma_smoothed.txt">link</a></td>\
        <td><a href="'+str(shot[0])+'/Basics/U@R_bpp4WholeTime.txt">link</a></td>\
        <td><a href="'+str(shot[0])+'/Basics/U@R_bpp@plasma_smoothed.txt">link</a></td>\
        </tr>')
    fileid.write('</body></html>')
    fileid.close()
    
    
    
    
    
    
    
In [4]:
GraphSetup=[['Iplasma','$I_{pl}$ [kA]','$I_p$'],['Uloop',"$U_{l}$ [V]",'$U_l$'],['Btoroidal','$B_t$ [T]','$B_t$']]


#LoopSetup=Setup[0:1]
LoopSetup=Setup[0:2]

for shot in LoopSetup:
    print(shot);
    GetData(shot[0])
    IndividualShot(shot) 

#GlobalFigs() 
HtmlGeneration()
print('Hotovo')

    
[24411, 0, 'o']
Getting ..24411/Basics
Doing 24411
[24412, 13, 'o']
Getting ..24412/Basics
Doing 24412
Global html generation ...
Hotovo
In [5]:
 
Global html generation ...
In [6]:
 
In [ ]: