Exemplo n.º 1
0
    bphi = np.asarray(B.get_data(d, 'bphi'))

    return bphi.max()


input_dir = '../MAST-U_output/temp/'

pattern = 'track_?????.data'

files = G.glob(input_dir + pattern)
nf = len(files)
print('found ', nf, ' files')
Bf = []
for f in files:
    print('working on : ', f)
    d = B.get_file(f)
    #    Bf.append(Bcheck(d))
    x = B.get_data(d, 'x')
    y = B.get_data(d, 'y')
    z = B.get_data(d, 'z')

    fo = dest + os.path.splitext(os.path.basename(f))[0] + ".dat"
    #    os.path.splitext(f)[0]+'.dat'
    o = open(fo, 'w+')
    for i, xx in enumerate(x):
        yy = y[i]
        zz = z[i]
        o.write('{}  {}  {}\n'.format(xx * conv, yy * conv, zz * conv))
    o.close()
# all done
Exemplo n.º 2
0
def main(control_file):

    # open control file and read parameters
    c_file = control_file
    cd = PF.pfile(c_file)

    nml_dir = cd.get_value('input_dir')
    nml_filename = cd.get_value('input_file')

    make_new_nml = cd.get_value('make_new_nml', var_type=cd.Bool)

    static_dir = cd.get_value('static_dir')
    stat_file = cd.get_value('static_file')

    dynamic_dir = cd.get_value('dynamic_dir')
    dyn_file = cd.get_value('dynamic_file')

    orbit_command = cd.get_value('orbit_command') + ' ' + c_file
    #    plot_command = cd.get_value('plot_command') + ' ' + c_file

    ##########################Obtaining Parameters and Data########################

    # Grabbing dynamic data file
    dd = B.get_file(dynamic_dir + dyn_file)
    dpar = dd.par

    # which detectors are used in the calculations
    try:
        det_use = np.array(dpar.get_value('detector_to_use').split(','),
                           dtype=int)
    except:
        det_use = np.array([int(dpar.get_value('detector_to_use'))])

    # total number of detectors to be used in calculations
    detectors = len(det_use)

    # get the assigned detectors ids
    detector_id = B.get_data(dd, 'detector_id')

    # total number of detectors in dynamic file
    N_det = len(detector_id)

    # get the assigned channel numbers
    channel_number = B.get_data(dd, 'ch')

    # Port angle of each detector when the Reciprocating probe arm is at a rotation angle of 0, convert to rads
    ppb = B.get_data(dd, 'phi_port_base') * dtr

    # Theta angle of each detector when the Reciprocating
    # probe arm is at a rotation angle of 0
    # Port angle was input in degrees
    tpb = B.get_data(dd, 'theta_port_base') * dtr

    # Horizontal offset, from the center of the diagnostic, of each detector
    # Horizontal offset was input in mm
    dyo = B.get_data(dd, 'detector_horizontal_offset') * mm2m

    # Radial offset of each detector (measured from the base)
    # Radial offset was input in mm
    dro = B.get_data(dd, 'detector_radial_axis_offset') * mm2m

    # Height offset of each detector (measured from the center)
    # Height offset was input in mm
    dzo = B.get_data(dd, 'detector_height_offest') * mm2m

    # detector type (Probe or Fixed)
    det_type = B.get_data(dd, 'det_type')

    # Alpha is the rotational angle of the RP arm
    # converted to radians
    alpha = dpar.get_value('RP_rotation') * dtr

    ##################################Making Calculations##########################
    # indexes of fixed detectors
    fixed_dets = np.where(det_type == 'Fixed')

    # calculation of positions change for each Probe detector due to rotation
    dyor = np.sqrt(dyo**2 + dzo**2) * np.cos(alpha + pol_angle(dyo, dzo))
    dzor = np.sqrt(dyo**2 + dzo**2) * np.sin(alpha + pol_angle(dyo, dzo))

    # RDist is the distance from the center of the tokamak to each detector (m)
    RDist = np.sqrt((dpar.get_value('RDist') + dro +
                     dpar.get_value('RDist_offset'))**2 + dyor**2)
    RDist[fixed_dets] = dro[fixed_dets]

    # ZDist here is the height of each detector relative to the centr of the
    # tokamak, in dynamic file ZDist is RP position hight
    ZDist = dpar.get_value('ZDist') + dzor
    ZDist[fixed_dets] = dzor[fixed_dets]

    #RP phd angle
    RP_phd = dpar.get_value('PHDangle')

    # PHD angle shift for each detector relative to RP_phd
    dphd = np.arcsin(dyor / RDist) / dtr

    # phdangle is the toroidal angle of each detector in radians
    phdangle = RP_phd + dphd
    phdangle[fixed_dets] = dyo[fixed_dets] / mm2m

    # The following are the calculations for the change in phi and theta angles
    phi_port, theta_port = rotate_det(ppb, tpb, alpha, dphd * dtr)
    phi_port /= dtr
    theta_port /= dtr

    phi_port[fixed_dets] = ppb[fixed_dets] / dtr
    theta_port[fixed_dets] = tpb[fixed_dets] / dtr

    #######################Detector orientation vectors for SolidWorks##############
    #    output_folder = '../MAST-U_output/g29975_TRANSP/DetectorsVectors/'
    #    vlen = 0.1 #vector lenght in meters
    #    for k in range(N_det):
    #        geom = open(output_folder + 'track' + str(k)+ '.dat', 'w+')
    #
    #        xx=RDist[k]*np.cos(phdangle[k]*dtr)
    #        yy=RDist[k]*np.sin(phdangle[k]*dtr)
    #        zz=ZDist[k]
    #
    #        geom.write('{}  {}  {}\n'.format(xx,yy,zz))
    #
    #        print xx, yy, zz
    #
    #        vx =  -vlen*np.cos(phi_port[k]*dtr)*np.sin(theta_port[k]*dtr)
    #        vy =  -vlen*np.sin(phi_port[k]*dtr)
    #        vz =   vlen*np.cos(phi_port[k]*dtr)*np.cos(theta_port[k]*dtr)
    #
    #        #print "V", vx, vy, vz
    #
    #        v1 = vx*np.cos(phdangle[k]*dtr) - vy*np.sin(phdangle[k]*dtr)
    #        v2 = vx*np.sin(phdangle[k]*dtr) + vy*np.cos(phdangle[k]*dtr)
    #        v3 = vz
    #
    #        #print "Vr", v1,v2,v3
    #        xx = xx + v1
    #        yy = yy + v2
    #        zz = zz + v3
    #
    #        print xx, yy, zz
    #        geom.write('{}  {}  {}\n'.format(xx,yy,zz))
    #        geom.close()

    #########################Creating New Dictionary###############################

    # Physical Parameter Dictionary
    PA = {
        'PHDangle': phdangle,
        'RDist': RDist,
        'phi_port': phi_port,
        'theta_port': theta_port,
        'channel_number': channel_number,
        'detector_id': detector_id,
        'ZDist': ZDist,
        'detector_number': det_use,
        'detectors': detectors
    }

    PAK = list(PA.keys())
    PAG = PA.get

    #   ######################Make a new NML file#########################
    if make_new_nml is True:

        staticf = open(static_dir + stat_file, 'r').readlines()
        # opens and reads static file

        staticf = [s.replace('\r\n', '\n') for s in staticf]
        #this is for linux compatibility

        bothf = open(nml_dir + nml_filename, 'w+')
        # creates nml writable file

        # Writing New nml file
        bothf.writelines(staticf[:staticf.index(' &orbit_par\n') + 1])
        # writes the static file into the new nml file

        # Selecting the inputs under orbitpar

        orbit_par = [
            'detectors', 'detector_number', 'detector_id', 'channel_number',
            'theta_port', 'phi_port'
        ]
        # Writing Parameters into orbit_par in nml file
        for i in orbit_par:
            for k in range(N_det):
                try:
                    bothf.write('    ' + i + '({0:1})'.format(k + 1) +
                                '= {0:1}\n'.format(PAG(i)[k]))
                except:
                    if i == 'detector_number': break
                    bothf.write('    ' + i + '= {0:1}\n'.format(PAG(i)))
                    break
            bothf.write('\n')

        bothf.writelines(staticf[staticf.index(' &orbit_par\n') +
                                 1:staticf.index(' &detection\n') + 1])

        # Choosing keys for detection nml section
        detection = []
        for i in PAK:
            if i not in orbit_par:
                detection.append(i)

        # Writing Parameters into detection in nml file

        for i in detection:
            for k in range(N_det):
                try:
                    bothf.write('    ' + i + '({0:1})'.format(k + 1) +
                                '= {0:1}\n'.format(PAG(i)[k]))
                except:
                    bothf.write('    ' + i + '= {0:1}\n'.format(PAG(i)))
                    break
            bothf.write('\n')
        bothf.writelines(staticf[staticf.index(' &detection\n') + 1:])
        bothf.close()

    os.system(orbit_command)
Exemplo n.º 3
0
        dynamic_parameters[k]=float(dynamic_parameters[k])
    except:
        print "\n Cannot make a float  out of this : ", dynamic_parameters[k], k,'\n'
        
detectors = 4 # Total number of detectors in the system

try:        
	dynamic_parameters['detector_number']=np.array(dynamic_parameters['detector_number'].split(','), dtype = int)
except:
	dynamic_parameters['detector_number'] = [int(dynamic_parameters['detector_number'])]

dn = dynamic_parameters['detector_number']

# location of the base

phi_port_base = B.get_data(dynamic_data, 'phi_port_base')

# position offsets for the individual detectors relative to the base

detector_horizontal_offset = B.get_data(dynamic_data, 'detector_horizontal_offset')

detector_radial_axis_offset = B.get_data(dynamic_data, 'detector_radial_axis_offset')

detector_height_offset = B.get_data(dynamic_data, 'detector_height_offest')

# Making Calculations

dynamic_parameters['ZDist'] = dynamic_parameters['ZDist'] + detector_height_offset*1.e-3

# With respect to the radial position of the RP
import LT.box as B
import numpy as np
import matplotlib as mpl

#get data
datafile = B.get_file('gauss_laguerre_modified.data')
nodes = B.get_data(datafile, 'node')
xvalues = B.get_data(datafile, 'x')
weights = B.get_data(datafile, 'weight')

#put data into useable form
node_lookup = {} #creates an empty dictionary
for node, xvalues, weight in zip(nodes, xvalues, weights): #loops through each node, zip creates list of tuples
    node_pairs = node_lookup.setdefault(node, [])
    node_pairs.append((xvalues, weight))

for node, node_pairs in node_lookup.items(): # "items" must modify a dictionary
    for pair in node_pairs:
        print('{} {} {}'.format(node, *pair))
from LT import box as B

f = B.get_file('gauss_laguerre_modified.data')
nodes = B.get_data(f, 'node')
xs = B.get_data(f, 'x')
weights = B.get_data(f, 'weight')

node_lookup = {}
for node, x, weight in zip(nodes, xs, weights):
    import pdb
    pdb.set_trace()
    node_pairs = node_lookup.setdefault(node, [])
    node_pairs.append((x, weight))

for node, node_pairs in node_lookup.items():
    for pair in node_pairs:
        print('{} {} {}'.format(node, *pair))
import LT.box as B
#import numpy as np
#import matplotlib as mpl
#import mathplotlib.pyplot as plt


# get file
data_file = B.get_file('estimatepi.data')

# get data
no_dimension = B.get_data(data_file, 'dimension')
pi_estimate = B.get_data(data_file, 'piestimate')
error = B.get_data(data_file, 'error')

# make a plot
B.plot_exp(no_dimension, pi_estimate, error)

# add the labels
B.pl.xlabel('Number of dimensions')
B.pl.ylabel('Estimator for pi')
B.pl.title('Pi estimated')

# save the plot
B.pl.savefig('pi_plot.png')
Exemplo n.º 7
0
    'large_R_4.data',\
    'large_R_5.data',\
    'large_R_6.data']

cd = pfile(h_file)

rl = []
zl = []
phil = []
comments = []

# large R data
for fn in files:
    f = data_dir + fn
    d = B.get_file(f)
    rl.append(B.get_data(d, 'r'))
    zl.append(B.get_data(d, 'z'))
    phil.append(d.par.get_value('phi'))
    comments.append(d.par.get_value('comment'))
rl = np.array(rl)
zl = np.array(zl)

# small R data
sd = B.get_file(s_file)
ri = sd.get_data('r')
zi = sd.get_data('z')

# ready to make the new limiter file

# o = open("NSTXLIM16.DAT",'w')
Exemplo n.º 8
0
from scipy import interpolate
from scipy.interpolate import interp1d
import LT.box as B
sys.path.insert(0, '../../Macros')  #Add path to search for modules
from MagInterpolate import GetP

#User Command Line Input
spec = sys.argv[1]  #user cmd-line input 'hms', 'shms', or 'coin'
#Usage: python make_kinFile.py`` hms

#Script to produce a kinematics file and data file with useful kinematics variables run-by-run
f = B.get_file('epics_data/%s_epics.data' % (spec))

if (spec == 'hms'):
    #Read in the run setting into an array
    run = B.get_data(f, 'Run')
    hQ1_set = B.get_data(f, 'hQ1_set')
    hQ2_set = B.get_data(f, 'hQ2_set')
    hQ3_set = B.get_data(f, 'hQ3_set')
    NMR_true = B.get_data(f, 'NMR_true')
    hPol = B.get_data(f, 'Polarity')
    angle = B.get_data(f, 'Angle')
    coll = B.get_data(f, 'Collimator')
    targ = B.get_data(f, 'Target')
    raster = B.get_data(f, 'Raster')
    TFE = B.get_data(f, 'TFE')

elif (spec == 'shms'):
    #Read in the run setting into an array
    run = B.get_data(f, 'Run')
    sHB_set = B.get_data(f, 'sHB_set')
Exemplo n.º 9
0
# script to try out histogramming
import LT.box as B

# get the file
mcf = B.get_file("counts.data")

# see what is in there
mcf.show_keys()

# get some data
ne = B.get_data(mcf, "n")
counts = B.get_data(mcf, "counts")

# make a hisrogram of the values
hh = B.histo(counts, range=(120.0, 180.0), bins=60)

# set the initial values for fitting
hh.A.set(2)
hh.mean.set(140)
hh.sigma.set(10)

# fit the peak
hh.fit()

# plot the histogram
hh.plot()
B.pl.show()

# plot the fit
hh.plot_fit()
B.pl.show()
Exemplo n.º 10
0
import numpy as np
import LT.box as B
import matplotlib.ticker as tk
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

f = B.get_file('d2_580_total_report.dat')
run = B.get_data(f, 'Run')
current = B.get_data(f, 'BCM4A_Current')
charge = B.get_data(f, 'BCM4A_Charge')
h3of4_rate = B.get_data(f, 'h3of4_rate')
p3of4_rate = B.get_data(f, 'p3of4_rate')
coin_rate = B.get_data(f, 'coin_rate')
htrk_eff = B.get_data(f, 'htrk_eff')
htrk_eff_err = B.get_data(f, 'htrk_eff_err')
ptrk_eff = B.get_data(f, 'ptrk_eff')
ptrk_eff_err = B.get_data(f, 'ptrk_eff_err')
cpuLT = B.get_data(f, 'cpuLT')
tLT = B.get_data(f, 'tLT')
x_bpm = B.get_data(f, 'x_bpm')
y_bpm = B.get_data(f, 'y_bpm')

ptrig6_acc = B.get_data(f, 'ptrig6_accepted')
ptrig6_acc_err = np.sqrt(ptrig6_acc) 

norm_cnts = ptrig6_acc / charge
norm_cnts_err = ptrig6_acc_err / charge



#with error
Exemplo n.º 11
0
import LT.box as B
import matplotlib.pyplot as plt
from numpy import sin, cos


# retrieve the data
system_data = B.get_file('comet.data')

# put the data into arrays
time = B.get_data(system_data,'row')
radius = B.get_data(system_data,'r')
#velocity_r = B.get_data(system_data,'rdot')
#phi = B.get_data(system_data,'phi')
#velocity_phi = B.get_data(system_data,'phidot')

# make and save plots
orbit_plot = plt.plot(time, radius, '-', label='theta')
#orbit_plot = plt.plot(time, phi, '-', label='theta')
#orbit_plot = plt.plot(time, velocity_phi, '-', label='theta')

#plt.title('Comet Orbit in the Polar Plane')
#plt.xlabel('time (seconds)')
#plt.ylabel('')
#plt.legend() # shows legned
#plt.legend(loc=0) # shows legned, loc is location code

plt.savefig('Orbit.pdf')
Exemplo n.º 12
0
    idet = int(f.split('/')[-1].split('_')[-1].split('.')[0])/10000
    new_detector = (idet != idet_open)    
    if new_detector:
        print('new detector : ', idet)
        idet_open = idet
        if not first:
            groups.append(names)
        else:
            first = False
        names = []
    names.append(f)
groups.append(names)

# create a dxf file for each detector
for i,g in enumerate(groups):
    idet = i
    drawing = ezdxf.new(dxfversion='AC1024')
    modelspace = drawing.modelspace()
    fo = 'detector_{}'.format(idet)+'.dxf'
    for f in g:
        d = B.get_file(f)
        x = B.get_data(d, 'x')*100./inch
        y = B.get_data(d, 'y')*100./inch
        z = B.get_data(d, 'z')*100./inch
        
        r = B.np.array([x,y,z]).T
        modelspace.add_polyline3d(r, dxfattribs={'color': 7})
    # save file
    drawing.saveas(fo)
# all done
Exemplo n.º 13
0
import LT.box as B
import numpy as np
from numpy import ndarray
f = B.get_file('hms_heep_summary_FINAL.data')

#Define masses
Mp = 0.938272   #proton mass GeV
me = 0.00051099 #electron mass GeV

#converion factor from deg to radians
dtr = np.pi / 180.


#Get the data from datafile
run = B.get_data(f, 'Run')
nmr_true = B.get_data(f, 'nmr_true')
kf = B.get_data(f, 'nmr_P')                   #central electron momentum
theta_e = B.get_data(f, 'hms_Angle')          #e- arm central angle
Pf = B.get_data(f, 'shms_P')                  #central proton arm momentum
theta_p = B.get_data(f, 'shms_Angle')         #p arm central angle
Eb = B.get_data(f, 'beam_e')                  #beam energy          
data_W_mean = B.get_data(f, 'data_W_mean')
data_W_mean_err = B.get_data(f, 'data_W_mean_err')
data_W_sigma = B.get_data(f, 'data_W_sigma')
simc_W_mean = B.get_data(f, 'simc_W_mean')
simc_W_mean_err = B.get_data(f, 'simc_W_mean_err')
simc_W_sigma = B.get_data(f, 'simc_W_sigma')

#Declare arrays
dW_mean = ndarray(22)                #W_simc_fit - W_data_fit
Exemplo n.º 14
0
    def populate(self):
        # clear the tables and unselect checkboxes
        self.posTable.clearContents()
        for i in self.chb:
            i.setChecked(False)
        
        # open dynamic file and load parameters to fill in tables and controls
        dfile = self.dFile
        try:
            dd = B.get_file(dfile)
        except:
            print("Couldn't open dynamic file to load parameters inputs")
            return
        dpar = dd.par

        # Which detectors are used in the calculations
        try:
            det_use = np.array(dpar.get_value('detector_to_use').split(','),
                          dtype=int)
        except:
            det_use = np.array(int(dpar.get_value('detector_to_use')))

        # get the assigned channel numbers
        detector_id = B.get_data(dd, 'detector_id')
        
        # total number of detectors in dynamic file
        N_det = len(detector_id)
        
        # get the assigned channel numbers
        channel_number = B.get_data(dd, 'ch')
        
        # Port angle of each detector in RP ref. frame
        ppb = B.get_data(dd, 'phi_port_base')

        # Theta angle of each detector in RP ref. frame
        tpb = B.get_data(dd, 'theta_port_base')

        # Horizontal offset of each detector (in mm)
        dyo = B.get_data(dd, 'detector_horizontal_offset')

        # Radial offset of each detector (measured from the base in mm)
        dro = B.get_data(dd, 'detector_radial_axis_offset')

        # Height offset of each detector (measured from the center in mm)
        dzo = B.get_data(dd, 'detector_height_offest')
        
        # detector type (Probe or Fixed)
        det_type = B.get_data(dd, 'det_type')

        # Alpha is the rotational angle of the RP arm (in degrees)
        alpha = dpar.get_value('RP_rotation')

        # Radial position of the probe (in m)
        Rdist = dpar.get_value('RDist')

        # Radial position of the probe (in m)
        Zdist = dpar.get_value('ZDist')

        # Toroidal angle of the port
        PHDangle = dpar.get_value('PHDangle')

        

        # open static file to read some data (below is a list of possible static file locations)
        sfile=[os.path.dirname(dfile) + '/static_file.nml',
               '../MAST-U_input/g' + self.efitFile.rsplit('.')[0] + '/static_file.nml',
               '../MAST-U_input/temp/static_file.nml',
               '../MAST-U_input/sample_input_files/static_file.nml']
        for sfile in sfile:
            try:
                staticf = open(sfile).readlines()
                self.static_file = sfile
                print('Using %s for new input files preparation' %sfile)
                break
            except:
                print("No static file in %s" %os.path.dirname(sfile))
        
        for line in staticf:
            if 'bfield_scale' in line:
                bfield_scale = float(line[line.find('=') + 1: line.find('!')])
            if 'IPOLDIR' in line:
                ipoldir = int(line[line.find('=') + 1: line.find('!')])
                self.poldir.setChecked(bool(ipoldir))
            if 'SSTP' in line:
                sstp = float(line[line.find('=') + 1: line.find('!')])
            if ' S =' in line:
                s = float(line[line.find('=') + 1: line.find('!')])



        # push values to their indicators on GUI
        self.Rdist.setValue(Rdist)
        self.Zdist.setValue(Zdist)
        self.RProt.setValue(alpha)
        self.PHD.setValue(PHDangle)
        self.bfs.setValue(bfield_scale)
        self.trajl.setValue(sstp)
        self.trajs.setValue(s)
        

        for i in range(N_det):
            self.posTable.setItem(i, 0, QtWidgets.QTableWidgetItem())
            self.posTable.item(i, 0).setBackground(QtGui.QColor(colors[detector_id[i]-1]))
            
            self.posTable.setItem(i, 1, QtWidgets.QTableWidgetItem(
                                          str(detector_id[i])))
            self.posTable.setItem(i, 2,
                                  QtWidgets.QTableWidgetItem(str(channel_number[i])))
            self.posTable.setItem(i, 3,
                                  QtWidgets.QTableWidgetItem(str(ppb[i])))
            self.posTable.setItem(i, 4,
                                  QtWidgets.QTableWidgetItem(str(tpb[i])))
            self.posTable.setItem(i, 5,
                                  QtWidgets.QTableWidgetItem(str(dyo[i])))
            self.posTable.setItem(i, 6,
                                  QtWidgets.QTableWidgetItem(str(dro[i])))
            self.posTable.setItem(i, 7,
                                  QtWidgets.QTableWidgetItem(str(dzo[i])))
            self.posTable.setItem(i, 8,
                                  QtWidgets.QTableWidgetItem(det_type[i]))
            if detector_id[i] in det_use:
                self.chb[i].setChecked(True)
Exemplo n.º 15
0
def Bcheck(d):
    bphi = np.asarray(B.get_data(d, 'bphi'))

    return bphi.max()
Exemplo n.º 16
0
#orbit_dir = './nml_orb_MAST_p0/'
orbit_dir = './' + machine + '_output' + orbit_dir

NC_data_dir = '../Neutron_Camera/'

NC_views = ['view_0.data',\
        'view_1.data',\
        'view_2.data',\
        'view_3.data']

# get the orbits data
NC_tracks = []
for f in NC_views:
    ncf = NC_data_dir + f
    ncd = B.get_file(ncf)
    nc_r = B.get_data(ncd, 'r')
    nc_x = B.get_data(ncd, 'x')
    nc_y = B.get_data(ncd, 'y')
    nc_z = B.get_data(ncd, 'z')
    NC_tracks.append([nc_r, nc_x, nc_y, nc_z])

#orbit_output = open(orbit_dir + 'orbit_output').readlines()
orbit_output = open(orbit_dir + 'orbit_output').readlines()

# find the EQ file used:
eq_file = 'generic'
for d in orbit_output:
    if (d.find('--> EQ File unit, name') >= 0.):
        eq_file = d.split()[-1:][0]

# flux
Exemplo n.º 17
0
import LT.box as B
import matplotlib.pyplot as plt


# retrieve the data
energy_data = B.get_file('data/energy.data')

# put the data into arrays
sweep = B.get_data(energy_data,'sweep')
total_energy = B.get_data(energy_data,'total_energy')
kinetic_energy = B.get_data(energy_data,'kinetic_energy')
potential_energy = B.get_data(energy_data,'potential_energy')

# make and save plots
total_energy_plot = plt.plot(sweep,total_energy, '-', label='Total Energy')
kinetic_energy_plot = plt.plot(sweep,kinetic_energy, '-', label='Kinetic Energy')
potential_energy_plot = plt.plot(sweep,potential_energy, '-', label='Potential Energy')

plt.title('Equilibrium Energy for Noninteracting Gas, N=100')
plt.xlabel('Number of Sweeps in Markov Chain')
plt.ylabel('Energy')
plt.legend() # shows legned
plt.legend(loc=4) # shows legned, loc is location code

plt.savefig('PlotEnergy.pdf')
Exemplo n.º 18
0
data_file_Cu65 = B.get_file('data/ResultsConstantsCopper65.data')
data_file_Cu65RMS = B.get_file('data/ResultsRadiusCopper65.data')

data_file_Au = B.get_file('data/ResultsConstantsGold.data')
data_file_AuRMS = B.get_file('data/ResultsRadiusGold.data')

data_file_Pb = B.get_file('data/ResultsConstantsLead.data')
data_file_PbRMS = B.get_file('data/ResultsRadiusLead.data')

data_file_U = B.get_file('data/ResultsConstantsUranium.data')
data_file_URMS = B.get_file('data/ResultsRadiusUranium.data')

# put the data into arrays
node = range(1,17)

Constants_Ca = B.get_data(data_file_Ca,'C')
RMS_Ca = B.get_data(data_file_CaRMS,'rms')

Constants_Fe = B.get_data(data_file_Fe,'C')
RMS_Fe = B.get_data(data_file_FeRMS,'rms')

Constants_Cu63 = B.get_data(data_file_Cu63,'C')
RMS_Cu63 = B.get_data(data_file_Cu63RMS,'rms')

Constants_Cu65 = B.get_data(data_file_Cu65,'C')
RMS_Cu65 = B.get_data(data_file_Cu65RMS,'rms')

Constants_Au = B.get_data(data_file_Au,'C')
RMS_Au = B.get_data(data_file_AuRMS,'rms')

Constants_Pb = B.get_data(data_file_Pb,'C')
Exemplo n.º 19
0
def main(control_file, output_folder, vlen):
    global plot_command

    # open control file and read parameters
    c_file = control_file 
    cd = PF.pfile(c_file)

    dynamic_dir = cd.get_value('dynamic_dir')
    dyn_file = cd.get_value('dynamic_file')
    
    plot_command = cd.get_value('plot_command') + ' ' + c_file

##########################Obtaining Parameters and Data########################

    # Grabbing dynamic data file
    dd = B.get_file(dynamic_dir + dyn_file)
    dpar = dd.par



    
    # get the assigned detectors ids
    detector_id = B.get_data(dd, 'detector_id')
    
    # total number of detectors in dynamic file
    N_det = len(detector_id)

    # Port angle of each detector when the Reciprocating probe arm is at a rotation angle of 0, convert to rads
    ppb = B.get_data(dd, 'phi_port_base')*dtr
    
    # Theta angle of each detector when the Reciprocating
    # probe arm is at a rotation angle of 0
    # Port angle was input in degrees
    tpb = B.get_data(dd, 'theta_port_base')*dtr

    # Horizontal offset, from the center of the diagnostic, of each detector
    # Horizontal offset was input in mm
    dyo = B.get_data(dd, 'detector_horizontal_offset')*mm2m

    # Radial offset of each detector (measured from the base)
    # Radial offset was input in mm
    dro = B.get_data(dd, 'detector_radial_axis_offset')*mm2m

    # Height offset of each detector (measured from the center)
    # Height offset was input in mm
    dzo = B.get_data(dd, 'detector_height_offest')*mm2m

    # detector type (Probe or Fixed)
    det_type = B.get_data(dd, 'det_type')
    
    # Alpha is the rotational angle of the RP arm
    # converted to radians
    alpha = dpar.get_value('RP_rotation')*dtr

    
    
    ##############################Making Calculations##########################
    # indexes of fixed detectors
    fixed_dets = np.where(det_type == 'Fixed')
    
    # calculation of positions change for each Probe detector due to rotation
    dyor = np.sqrt(dyo**2 + dzo**2)*np.cos(alpha + pol_angle(dyo, dzo))
    dzor = np.sqrt(dyo**2 + dzo**2)*np.sin(alpha + pol_angle(dyo, dzo))
    
    # RDist is the distance from the center of the tokamak to each detector (m)
    RDist = np.sqrt((dpar.get_value('RDist') + dro + dpar.get_value('RDist_offset'))**2 + dyor**2)
    RDist[fixed_dets] = dro[fixed_dets]
    
    # ZDist here is the height of each detector relative to the centr of the
    # tokamak, in dynamic file ZDist is RP position hight
    ZDist = dpar.get_value('ZDist') + dzor
    ZDist[fixed_dets] = dzor[fixed_dets]
    
    #RP phd angle
    RP_phd = dpar.get_value('PHDangle')
    
    # PHD angle shift for each detector relative to RP_phd
    dphd= np.arcsin(dyor/RDist)/dtr
    
    # phdangle is the toroidal angle of each detector in radians
    phdangle = RP_phd + dphd
    phdangle[fixed_dets] = dyo[fixed_dets]

    # The following are the calculations for the change in phi and theta angles
    phi_port, theta_port = rotate_det(ppb, tpb, alpha, dphd*dtr)
    phi_port /= dtr
    theta_port /= dtr
    
    phi_port[fixed_dets] = ppb[fixed_dets]/dtr
    theta_port[fixed_dets] = tpb[fixed_dets]/dtr
    
    
    for k in range(N_det):
        geom = open(output_folder + 'track' + str(k)+ '.dat', 'w')
        xx=RDist[k]*np.cos(phdangle[k])
        yy=RDist[k]*np.sin(phdangle[k])
        zz=ZDist[k]
        
        geom.write('{}  {}  {}\n'.format(xx,yy,zz))

        print(xx, yy, zz)
        
        vx =  -vlen*np.cos(phi_port[k]*dtr)*np.sin(theta_port[k]*dtr)
        vy =  -vlen*np.sin(phi_port[k]*dtr)
        vz =   vlen*np.cos(phi_port[k]*dtr)*np.cos(theta_port[k]*dtr)

        print("V", vx, vy, vz)
        
        v1 = vx*np.cos(phdangle[k]*dtr) - vy*np.sin(phdangle[k]*dtr)
        v2 = vx*np.sin(phdangle[k]*dtr) + vy*np.cos(phdangle[k]*dtr)
        v3 = vz
        
        print("Vr", v1,v2,v3)
        xx = xx + v1
        yy = yy + v2
        zz = zz + v3
        
        print(xx, yy, zz)
        geom.write('{}  {}  {}\n'.format(xx,yy,zz))
        geom.close()
Exemplo n.º 20
0
import LT.box as B
import matplotlib.pyplot as plt


# retrieve the data
system_data = B.get_file('system.data')

# put the data into arrays
time = B.get_data(system_data,'time')
angle = B.get_data(system_data,'angle')
angular_velocity = B.get_data(system_data,'velocity')

# make and save plots
angle_plot = plt.plot(time, angle, '-', label='theta')
angular_velocity_plot = plt.plot(time, angular_velocity, '-', label='d theta / d t')

plt.title('Pendulum System: driving amplitude=0.1, freqeuncy=5')
plt.xlabel('time (seconds)')
plt.ylabel('')
plt.legend() # shows legned
plt.legend(loc=0) # shows legned, loc is location code

plt.savefig('Angle_And_Velocity_Plot.pdf')

# make second plot
plt.clf() # clears current figure
plt.cla() # clears current axis settings

phase_plot = plt.plot(angle, angular_velocity, '-')
plt.title('Theta dot vs theta: driving amplitude=0.1, freqeuncy=5')
plt.xlabel('theta')
Exemplo n.º 21
0
dpar = dd.par        
                        
# Number of detectors used in the analysis

detectors = dd.par.get_value('detectors',var_type = int)

# Which detectors are used in the calculations

dn = np.array(dpar.get_value('detector_number').split(','), dtype = int)

# Port angle of each detector when the Reciprocating probe arm is at a rotation angle of 0

# Port angle was input in degrees

ppb = B.get_data(dd, 'phi_port_base')*dtr
if reverse:
    # to change direction of particle add 180 degrees
    ppb += np.pi

# Theta angle of each detector when the Reciprocating probe arm is at a rotation angle of 0

# Port angle was input in degrees

tpb = B.get_data(dd,'theta_port_base')*dtr

# Horizontal offset, from the center of the diagnostic, of each detector 

# Horizontal offset was input in mm

dxo = B.get_data(dd, 'detector_horizontal_offset')*mm2m
# import  the toolbox and call it B
import LT.box as B
import numpy as np

# read the data
mf = B.get_file('my_exp_1.data')

# get the data into arrays
t = B.get_data(mf, 'time')
dexp = B.get_data(mf,'dist')
derr = B.get_data(mf, 'd_err')

# print the values in a for loop
for i, D in enumerate(dexp):
    # indentation is important
    print 'time = ', t[i], 'distance = ', D, 'error = ', derr[i]
# end of the loop = end of indentation
# plot the data
B.plot_exp(t, dexp, derr)

# fit a line
fit = B.linefit(t, dexp, derr)

# draw the fit result
B.plot_line(fit.xpl, fit.ypl)

# add the labels
B.pl.xlabel('t (sec)')
B.pl.ylabel('Distance (m)')
B.pl.title('Distance vs time exp.')
Exemplo n.º 23
0
#rate_names,r_det =
rate_names, r_det = get_names_ch(
    'step_1_29975/2/3, step_2_29975/2/3')  # cd.get_value('rate_data'))

# assemble the PD information
# orbit view data and rate data MUST match
for i, v_d in enumerate(view_names):
    # loop over directories
    v_f = view_dir + '/' + v_d + '/'
    # get the magneti axis data
    f_magnetic_axis = v_f + 'orbit_output'
    rm, zm = get_magnetic_axis(f_magnetic_axis)
    # get the data and combine them
    f_rate_data = rate_dir + '/' + rate_names[i] + '.data'
    r_d = B.get_file(f_rate_data)
    det = B.get_data(r_d, 'det')
    det_l = list(det)
    chan = B.get_data(r_d, 'ch')
    if use_before:
        R = B.get_data(r_d, 'Rb')
        dR = B.get_data(r_d, 'dRb')
        n_r = r_d.par.get_value('n_r_b')
    else:
        R = B.get_data(r_d, 'Ra')
        dR = B.get_data(r_d, 'dRa')
        n_r = r_d.par.get_value('n_r_a')

    for j, n in enumerate(v_chan[i]):
        # loop over detectors in views
        view_f = v_f + 'track_{0:1d}1111.data'.format(n)
        view_data = B.get_file(view_f)
Exemplo n.º 24
0
def main(c_file):
    control_file = c_file

    # contpour plotting controle
    cont_scale = 1.0
    ncont = 25

    #colormap = pl.get_cmap('CMRmap')
    #colormap = pl.get_cmap('gnuplot')
    #colormap = pl.get_cmap('gnuplot2')
    colormap = pl.get_cmap('gist_heat')
    #colormap = pl.get_cmap('jet')
    #colormap = pl.get_cmap('hot')

    # open control file
    p_file = control_file
    pf = PF.pfile(p_file)

    output_dir = pf.get_value('output_dir')
    # ???
    plot_em = pf.get_value('plot_em', var_type=pf.Bool)
    # ??
    em_filled = pf.get_value('em_filled', var_type=pf.Bool)
    # ??
    plot_psirel = pf.get_value('plot_psirel', var_type=pf.Bool)
    # ??
    psirel_filled = pf.get_value('psirel_filled', var_type=pf.Bool)
    ##
    all_yellow = pf.get_value('all_yellow', var_type=pf.Bool)

    # color array
    if all_yellow:
        colors = ['y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y',
                  'y']  # make everything yellow
    else:
        colors = [
            'red', 'green', 'blue', 'yellow', 'magenta', 'cyan', 'orange',
            'lavenderblush', 'maroon', 'plum'
        ]

    # dynamic input file for detector/channels assignment
    di_dir = pf.get_value('dynamic_dir')
    di_file = pf.get_value('dynamic_file')

    dynamic_file = di_dir + di_file
    df = B.get_file(dynamic_file)
    dfd = df.par

    # get channel/detector assignement
    try:
        dn = np.array(dfd.get_value('detector_to_use').split(','), dtype=int)
    except:
        dn = np.array([int(dfd.get_value('detector_to_use'))])

    channel_number = B.get_data(df, 'ch')
    detector_id = B.get_data(df, 'detector_id')
    ch_touse = channel_number[np.in1d(detector_id, dn)]

    # flux grid
    try:
        flux_data_file = pf.get_value('flux_data_file')
    except:
        flux_data_file = 'flux.data'
    print('using : ', flux_data_file, ' for flux and Em data')

    # flux limiter
    try:
        flux_limiter_file = pf.get_value('flux_limiter_file')
    except:
        flux_limiter_file = 'flux_limit.data'
    print('using : ', flux_limiter_file, ' for flux limit data')

    # plot n-flux at mid-plane
    try:
        flux_data_file_mp = pf.get_value('flux_data_file_mp')
    except:
        flux_data_file_mp = None

    orbit_output = open(output_dir + 'orbit_output').readlines()

    # find the EQ file used:
    eq_file = 'generic'
    for d in orbit_output:
        if (d.find('--> EQ File unit, name') >= 0.):
            eq_file = d.split()[-1:][0]

    # flux
    print('reading flux data')
    fl = gf.flux(output_dir + flux_data_file)

    print('reading flux limit data')
    fll_d = DF.dfile(output_dir + flux_limiter_file)
    r_fll = np.array(fll_d.get_data('xlim'))
    z_fll = np.array(fll_d.get_data('ylim'))

    # limiter
    print('reading limiter data')
    li = gl.limiter(output_dir + 'limiter_drawing.data')
    #orbits

    print('reading orbits data')

    # each view can now have several trajectories
    PD_views = []
    PD_views_f = []
    PD_accept = []
    PD_channel_number = []
    PD_step = []
    for i, i_d in enumerate(dn):
        cc = ch_touse[i]

        name_patt = output_dir + '/track_{}*.data'.format(i_d)

        PD_view_files = G.glob(name_patt)

        # use the first file in the list to get some parameters used for calculating rates
        PDd = DF.pdfile(PD_view_files[0])
        PD_accept.append(PDd.par.get_value('accept'))
        PD_channel_number.append(
            PDd.par.get_value('channel_number', var_type=int))
        PD_step.append(PDd.par.get_value('stepsize'))
        # load the trajectories for each view
        PD_v = [vd.view(f) for f in PD_view_files]
        PD_views_f.append(PD_view_files)
        PD_views.append(PD_v)
        print('channel : ', cc, ', detecor : ', i_d, ' loaded')
    PD_accept = np.array(PD_accept)

    #----------------------------------------------------------------------
    # start drawing
    #----------------------------------------------------------------------

    draw_top_view = pf.get_value('draw_top_view', var_type=pf.Bool)
    draw_top_view = True
    if draw_top_view:
        f1 = pl.figure(figsize=(11, 6))
#        f1=pickle.load(file('neutron.pickle_both_view'))
    else:
        f1 = pl.gcf()  #figure(figsize= (5,8))
    #f1.text(0.1, 0.925, eq_file)

    # draw 3 regions
    if draw_top_view:
        li.draw_all()
    else:
        li.draw_side_all()

    # draw the rel. flux
    # get a nice set of contour lines
    # select the first plot
    Em_cont = None

    # axes = li.ax1.get_axes()
    # f1.sca( axes )
    axes = li.ax1
    f1.sca(axes)

    # draw the flux limit
    pl.plot(r_fll, z_fll, color='m', linewidth=2.)

    if plot_em:
        Em_range = fl.Em.max() - fl.Em.min()
        Em_min = fl.Em.min() + Em_range / 100.
        v = np.linspace(Em_min, fl.Em.max() * cont_scale, ncont)
        if em_filled:
            Em_cont = fl.draw_Em_filled(v, cmap=colormap)
        else:
            Em_cont = fl.draw_Em(v)

    if plot_psirel:
        v = np.linspace(-0.1, fl.Zrel.max(), 23)
        if psirel_filled:
            fl.draw_psirel_filled(v, cmap=colormap)
        else:
            fl.draw_psirel(v)

    # make a nice x-axis
    axes.xaxis.set_major_locator(MaxNLocator(4))

    #----------------------------------------------------------------------
    # draw orbits
    #----------------------------------------------------------------------
    #    # animation part
    #    for i, PDv in enumerate(PD_views):
    #        icol = dn[i]-1
    #        animate(li, PDv, color = colors[icol])
    #
    # axes = li.ax1.get_axes()
    axes = li.ax1
    f1.sca(axes)
    for i, PDv in enumerate(PD_views):
        icol = dn[i] - 1
        plot_view_side(PDv, color=colors[icol], label='Ch {0:d}'.format(dn[i]))

    #pl.legend(fontsize = 12,loc = 'upper left')
    pl.title
    # draw  orbits into the top view
    #draw_top_view=True
    if draw_top_view:
        # axes = li.ax2.get_axes()
        axes = li.ax2
        f1.sca(axes)
        # draw a few orbits
        for i, PDv in enumerate(PD_views):
            icol = dn[i] - 1
            plot_view_top(PDv,
                          color=colors[icol],
                          label='Ch {0:d}'.format(dn[i]))
        # get the mid-plane emmissivity
        if plot_em:
            if (flux_data_file_mp != None):
                # load data file
                d = np.load(output_dir + '/' + flux_data_file_mp)
                X = d['X']
                Y = d['Y']
                Em_mid = d['EM_mp']
                Em_range = Em_mid.max() - Em_mid.min()
                Em_min = Em_mid.min() + Em_range / 100.
                v = np.linspace(Em_min, Em_mid.max() * cont_scale, ncont)
                if em_filled:
                    Em_cont = pl.contourf(X, Y, Em_mid, v, cmap=colormap)
                else:
                    Em_cont = pl.contour(X, Y, Em_mid, v, cmap=colormap)

        #pl.legend(fontsize = 12, loc = 'upper left')


# The following code plots histogram of orbits midplane intersection radii
#    h_range =(0.0, 0.3)#(0.6, 1.6)
#    r0 = []
#    f2 = pl.figure()
#    for  i,PDv in enumerate( PD_views ):
#        icol = dn[i]-1
#        rr = []
#        for v in PDv:
#            rr.append(get_effective_dist(v))#get_zero_crossing(v))
#
#        rr = np.array(rr)
#        r = rr.mean()
#        h = B.histo(rr, range =h_range, bins = 200)
#        h.plot(color = colors[icol])
#        print colors[icol]
#        sig_r = np.sqrt(rr.var())
#        r0.append([h, r, sig_r, rr])
#    # all done
#    pl.xlabel('R (m)')
#    pl.ylabel('counts')
#    pl.title('mid-plane Radius')
#
#    #pl.savefig(orbit_dir+'image.png')
    pl.show()
Exemplo n.º 25
0
def std_line_f(*x):
    fmt0 = "{"
    fmt1 = "{0:d}:16.9"
    fmt2 = "}, "
    string = ""
    for i, xx in enumerate(x):
        fmt = fmt0 + fmt1.format(i) + fmt2
        string += fmt
    string += "\n"
    return string.format(*x)


fi = B.get_file("mast_limiter_inner.data")
fo = B.get_file("mast_limiter_outer.data")

ri = B.get_data(fi, 'r')
zi = B.get_data(fi, 'z')
ro = B.get_data(fo, 'r')
zo = B.get_data(fo, 'z')

# now write the limiter data in a poper format
# there is only one toroidal region

o = open("MASTLIMIT00.DAT", 'w')

o.write(
    " 1                                       ! only one toroidal region\n")
o.write("MAST\n")
o.write("  0.0                                    ! start of region\n")
o.write(
    std_line_i2(len(ri), len(ro)) +
Exemplo n.º 26
0
B.pl.vlines(t_min_b, ymin, ymax, color='r')
B.pl.vlines(t_max_b, ymin, ymax, color='r')
# after
B.pl.vlines(t_min_a, ymin, ymax, color='m')
B.pl.vlines(t_max_a, ymin, ymax, color='m')

# get the various orbit radii for the 4 channels
if r_file != None:
    try:
        rd = B.get_file(r_file)
    except:
        print(r_file, ' does not exist, will not use radii!')
        r_file = None
if r_file != None:
    # radii
    r1 = B.get_data(rd, 'r0')
    r2 = B.get_data(rd, 'r1')
    r3 = B.get_data(rd, 'r2')
    r4 = B.get_data(rd, 'r3')
    # times
    t_rad = B.get_data(rd, 't') / 1000.  # in s
    # get channel number for checking
    c1 = B.get_data(rd, 'ch0')
    c2 = B.get_data(rd, 'ch1')
    c3 = B.get_data(rd, 'ch2')
    c4 = B.get_data(rd, 'ch3')
    radii = np.array([r1, r2, r3, r4])
    channel_id = np.array([c1, c2, c3, c4])

# write averaged rate into output file
output_file = res_dir + tsf.par.get_value('pro_file')