def generateMatrix(): """This function is where any user-specified values should be. Given shots in the x, y and z direction, it finds position vectors (a 16 by 3 array becuase there are 16 probe locations (4 locations on 4 probes) and each probe location has an x, y, and z coordinate relative to the center of the Bfield) then uses those positions to calculate the magnetic field at that point. Then, """ num_probes = 16 # print(position_vectors) # Create the (48x4) calibration matrix: calibration_matrix = [[0] * 9 for i in range(num_probes)] # counter = 0 #Not bothering to average: day ='050119' x_shot = 17 y_shot = 23 z_shot = 12 x_shot = day+'r'+ str(x_shot) y_shot = day+'r'+ str(y_shot) z_shot = day+'r'+ str(z_shot) x_magdata = hdr.getquikData(x_shot) y_magdata = hdr.getquikData(y_shot) z_magdata = hdr.getquikData(z_shot) for probe in range(num_probes): #first make the B and V arrays: B = np.zeros((3,3)) V = np.zeros((3,3)) B[0,:], x_max_time= get_b(0, x_shot, probe) B[1,:], y_max_time= get_b(1, y_shot, probe) B[2,:], z_max_time= get_b(2, z_shot, probe) V[0,:] = get_v(x_magdata, probe, x_max_time) V[1,:] = get_v(y_magdata, probe, y_max_time) V[2,:] = get_v(z_magdata, probe, z_max_time) V_inv = np.linalg.inv(V) # take the dot product of the arrays C = np.matmul(B, V_inv) #store the flattened 3x3 array as a row in the text file calibration_matrix[probe] = np.reshape(C, 9) # print(calibration_matrix) # print(calibration_matrix[probe]) pth = os.getcwd() date = '050119' # print(calibration_matrix.shape()) savetxt(os.path.join(pth, 'calib-%s-4x4_matrix_1.txt' % (date)) , calibration_matrix) print("Finished! File saved as 'calib-%s-4x4_matrix.txt_1' in current working directory" %(date))
def get_Bxy_vecRendering_format_lookup(shot, fix=False, num_probes=16): """Basically get_data() but returns data in a form that is compatible with the b-field animations found in anim_bfield_merging files Returns data, the calibrated, integrated magentic field data using lookup calibration. --KG 07/25/19 """ data = [[0] * 3 for i in range(num_probes)] # B25 = [[0] *num_probes for i in range(3)] magdata = hdr.getquikData(shot) timeB = magdata.time calibFile = 'calib-050119-4x4_lookup_final.txt' calibFile = os.path.join(os.getcwd() + "\\magcalib\\", calibFile) #change where caliv file is here calibFactor = np.loadtxt(calibFile) B25 = np.zeros([3, num_probes, len(timeB) - 1]) for probe in range(num_probes): Bx_all = cumtrapz( magdata.unCalibData[0, probe, :] - mj.get_gaussian_moving_avg( timeB, magdata.unCalibData[0, probe, :], num_probes - 1), timeB) Bx = Bx_all * calibFactor[probe][0] By_all = cumtrapz( magdata.unCalibData[1, probe, :] - mj.get_gaussian_moving_avg( timeB, magdata.unCalibData[1, probe, :], num_probes - 1), timeB) By = By_all * calibFactor[probe][1] Bz_all = cumtrapz( magdata.unCalibData[2, probe, :] - mj.get_gaussian_moving_avg( timeB, magdata.unCalibData[2, probe, :], num_probes - 1), timeB) Bz = Bz_all * calibFactor[probe][2] B25[0, probe, :] = Bx B25[1, probe, :] = By B25[2, probe, :] = Bz if fix: B25[2, 9, :] = B25[2, 9, :] * 100 B25[2, 11, :] = B25[2, 11, :] * 100 B25[1, 12, :] = B25[1, 12, :] * 100 Bmod25 = np.zeros([num_probes, len(timeB) - 1]) for j in range(num_probes): Bmod25[j, :] = np.sqrt(B25[0, j, :]**2 + B25[1, j, :]**2 + B25[2, j, :]**2) return (timeB, B25)
def integrated_B(shot, num_probes=16, probe=3): """ There are different way that I've seen the data integrated: this will plot the different ones, along with a variety of different moving averages --KG 06/13/19 """ # data = [[0] *3 for i in range(num_probes)] fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) data = hdr.getquikData(shot) btime = data.time Bz_nBT_15 = cumtrapz( data.unCalibData[2, probe, :] - mj.get_gaussian_moving_avg( data.time, data.unCalibData[2, probe, :], 15), data.time) * -1.103810335732411829e+02 Bz_nBT_100 = cumtrapz( data.unCalibData[2, probe, :] - mj.get_gaussian_moving_avg( data.time, data.unCalibData[2, probe, :], 100), data.time) * -1.103810335732411829e+02 Bz_nBT_500 = cumtrapz( data.unCalibData[2, probe, :] - mj.get_gaussian_moving_avg( data.time, data.unCalibData[2, probe, :], 500), data.time) * -1.103810335732411829e+02 # num_probes = 1 #only plot the first probe # probe_locs = get_probeLocs_calib_setup(shot) # Bz=sp.signal.detrend(magdata.fullData[2,probe_num,:]) # Bx=sp.signal.detrend(magdata.fullData[0,probe_num,:]) # By=sp.signal.detrend(magdata.fullData[1,probe_num,:]) # Bz=cumtrapz(data.unCalibData[2,1,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[2,1,:], 1), data.time) Bz = sp.signal.detrend(cumtrapz(data.unCalibData[2, probe, :], data.time)) btime = btime[:len(Bz)] ax1.plot(btime, Bz, label='Detrend, integrated') ax1.plot(btime, Bz_nBT_15, label='-moving avg, win = 15') ax1.plot(btime, Bz_nBT_100, label='-moving avg, win = 100') ax1.plot(btime, Bz_nBT_500, label='-moving avg, win = 500') ax1.legend() Bdot25 = np.zeros([3, 25, 8192]) timeB = data.time[801:] Bdot25[0, 3, :] = data.Bdot[0, 3, :] Bdot25[1, 3, :] = data.Bdot[1, 3, :] Bdot25[2, 3, :] = data.Bdot[2, 3, :] bzero = pyl.detrend_linear(Bdot25[2, 3, 800:]) bint = sp.integrate.cumtrapz(bzero, data.time[800:]) ax2.plot(btime, Bz_nBT_15, label='-moving avg, win = 15') ax2.plot(btime, Bz_nBT_500, label='-moving avg, win = 500') ax2.plot(timeB, bint, label="detrend LINEAR and integrated time shifted") # ax2.set_title("Current") plt.legend() plt.show()
def getMagData(shot, t0=-1, tf=-1, num_probes=16): """The main function that should be used Gets the data from the 4x4 probe setup at ALL TIMES Returns Bx,By and Bz, the calibrated, integrated magentic field data using a matrix calibration Data has the dimensions of [probes][time] - probes is the number of probes, from 0 to 15 typically assumes the calibration file is stored in magcalib folder --KG 07/10/19""" magdata = hdr.getquikData(shot) timeB = magdata.time if t0 != -1 and tf != -1: #trim to desired time t_index, t = my.fix_bounds(np.array((t0, tf)), timeB) magdata = magdata[:, :, t0:tf] calibFile = 'calib-050119-4x4_matrix.txt' calibFile = os.path.join(os.getcwd() + '\\magcalib\\', calibFile) #change where caliv file is here calibFactor = np.loadtxt(calibFile) B = np.zeros([3, num_probes, len(timeB) - 1]) win_size = 25 for probe in range(num_probes): for i in range(3): B_vec[i, probe, :] = cumtrapz( magdata.unCalibData[i, probe, :] - mj.get_gaussian_moving_avg( timeB, magdata.unCalibData[i, probe, :], win_size), timeB) for t in range(len(timeB) - 1): for probe in range(num_probes): C = np.reshape(calibFactor[probe], (3, 3)) #put into 3 x1 matric V = [[B_vec[0, probe, t]], [B_vec[1, probe, t]], [B_vec[2, probe, t]]] B_data = np.dot(C, V) B[0, probe, t], B[1, probe, t], B[2, probe, t] = B_data return B
def plot_every_single_calib_chan(shot, dir, lim, save=False, show=True, num_probes=16): """This function will plot a 4x4 (though there is some funcitonality built in for a different number of probes) grid of the CALIBRATED, INTEGRATED signals. Unless the calibration value was zero (when I built this some of the probes were dead during calibration) In which case it will plot the UNCALIBRATED (INTEGRATED) DATA IN RED for un-dead probes. Give it the shot (date + r + shot number) and the direction - 0 for x 1 for y 2 for z and it will plot all the signals. If you want to mess around with the number of probes, try passing it in as the parameter, though you may need to adjust cols or rows or both, and also maybe the figure size, (make is smaller if you have more probes) --KG 06/13/19 """ if (dir == 0): direction = 'X' elif (dir == 1): direction = 'Y' else: direction = 'Z' figsize = (9, 5) cols = 4 rows = (num_probes) // cols # define the data for cartesian plots def trim_axs(axs, N): """helper function to make sure the axs list to have correct length""" axs = axs.flat for ax in axs[N:]: ax.remove() return axs[:N] calibFile = 'calib-050119-4x4_lookup_1.txt' calibFile = os.path.join(os.getcwd(), calibFile) calibFactor = np.loadtxt(calibFile) fig1, axs = plt.subplots(rows, cols, figsize=figsize) axs = trim_axs(axs, num_probes) # for ax, case in zip(axs, cases) magdata = hdr.getquikData(shot) # Bx,By, Bz = pmd.getMagData(shot) for i in range(len(axs)): y = cumtrapz( magdata.unCalibData[dir, i, :] - mj.get_gaussian_moving_avg( magdata.time, magdata.unCalibData[dir, i, :], 15), magdata.time) # print(calibFactor[i][dir]) x = magdata.time x = x[:len(y)] ax = axs[i] ax.set_title('Probe (%s,%s %s)' % (str(i // 4 + 1), str(i % 4 + 1), direction), fontsize=10) if (calibFactor[i][dir] == 0): # If the probe was dead during calibration ax.plot(x, y, color='r', linestyle='dashed') else: y = y * calibFactor[i][dir] ax.plot(x, y) ax.set_ylim(-lim, lim) # if np.average(np.abs(y)) < lim*1e-2: # ax.plot(x, y, color = 'r') # ax.set_ylim(-lim*1e-5, lim*1e-5) # print(i, np.max(y), np.min(y)) ax.tick_params(axis='both', which='major', labelsize=7) ax.tick_params(axis='both', which='minor', labelsize=7) if (i % cols == 0): #lable all the left cols with y label ax.set_ylabel("Gauss", fontsize=8) if (i // rows == rows - 1): #lable all the left cols with y label ax.set_xlabel("Time $\\mu$s", fontsize=8) # plt.title("Shot %s" %(shot)) if show: plt.show() if save: try: figname = os.getcwd() + '\\generated_images\\' + str( shot) + "-" + direction + "-chans.png" # print("Saved fig: %s" %(figname)) plt.savefig(figname) except: figname = os.getcwd() + str(shot) + "-" + direction + "-chans.png" plt.savefig(figname) print("No generated_images folder. \nSaved fig: %s" % (figname))
def plots_4_doc(shot, num_probes=16): """ This plots the magentic field from every single probe one at a timeself. The advantage is that is also calculates what the helmholtz field at that point should be and plots it (as a function of time) and also current all one one plot, making it easy to find the ratio, and also verify it vizually. However, to make this function run in a reasonable amount of time, I thinned the data for the calulated helmholtz field, so that it only calculates every 10th point, meaning it is less accurate at actually producing the ratio (becuase it may not find the true peak ) TODO: - check if the units for the third plot are ok??? - Add y-units -- KG 06/13/19""" # data = [[0] *3 for i in range(num_probes)] magdata = hdr.getMagData(shot) probe_locs = get_probeLocs_calib_setup(shot) for probe_num in range(num_probes): # Bz=sp.signal.detrend(magdata.fullData[2,probe_num,:]) # Bx=sp.signal.detrend(magdata.fullData[0,probe_num,:]) # By=sp.signal.detrend(magdata.fullData[1,probe_num,:]) ratio = 1 timeb, Bx, By, Bz = load_smallbdot(shot) data = hdr.getquikData(shot) fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True) # Bz=cumtrapz(data.unCalibData[2,1,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[2,1,:], 1), data.time) Bz = sp.signal.detrend( cumtrapz(data.unCalibData[1, probe_num, :], data.time)) if (abs(np.max(Bz)) > abs(np.min(Bz))): print("Max %d, min %d, abs: %d" % (np.max(Bz), np.min(Bz), abs(np.min(Bz)))) Bz = Bz * -1 ratio = -1 Bz += np.abs(np.min(Bz)) btime = data.time[:len(Bz)] ax1.plot(btime, Bz) ax1.set_title("By - integrated") ax1.set_xlim(-25, 175) time, eastcurrent, westcurrent = loadcurrent(shot) ax2.plot(time[::10], eastcurrent[::10]) ax2.set_title("Current") r = probe_locs[1] # helmB = helmholtz_listcomp(r,eastcurrent) status = 0 max = len(eastcurrent) / 100 helmB = np.zeros((3, max)) i = 0 while i + 100 < len(eastcurrent): # currmax = polyPeak_noPlot(time,eastcurrent,[10,100],axis = 'current') x, y, z = helmholtz2(r, eastcurrent[i]) helmB[0][status] = x helmB[1][status] = y helmB[2][status] = z status += 1 i += 100 # thin the thing thinned_time = time[::100] thinned_time = thinned_time[:len(helmB[2])] helmB[2] = helmB[2] * -1 max_measured = np.max(Bz) max_theoretical = np.max(helmB[2]) ratio = ratio * max_theoretical / max_measured print("Shot: %s, probe %d, Ratio around: %d" % (shot[:6], probe_num, ratio)) ax3.plot(thinned_time, helmB[2]) ax3.set_title("Predicted B based on current and location in helmholtz") print("Ratio is: %d" % (ratio)) plt.show()
def get_Bxy_vecRendering_format(shot, fix=False, num_probes=16): """ Returns data, the calibrated, integrated magentic field data using matrix calibration. UNFINISHED becuase of the matrix thing. But this function would return getMagData() data but in a version compatible with the animations in anim_bfield_merging.py --KG 07/25/19 """ data = [[0] * 3 for i in range(num_probes)] # B25 = [[0] *num_probes for i in range(3)] magdata = hdr.getquikData(shot) timeB = magdata.time calibFile = 'calib-050119-4x4_matrix.txt' calibFile = os.path.join(os.getcwd() + '\\magcalib\\', calibFile) #change where caliv file is here print("\n\nHERE") calibFactor = np.loadtxt(calibFile) # calibFactor[14] = [0,0,0] # calibFactor[6] = [0,0,0] # calibFactor[7] = [0,0,0] B25 = np.zeros([3, num_probes, len(timeB) - 1]) B_vec = np.zeros([3, num_probes, len(timeB) - 1]) win_size = 25 for probe in range(num_probes): for i in range(3): B_vec[i, probe, :] = cumtrapz( magdata.unCalibData[i, probe, :] - mj.get_gaussian_moving_avg( timeB, magdata.unCalibData[i, probe, :], win_size), timeB) for t in range(len(timeB) - 1): for probe in range(num_probes): C = np.reshape(calibFactor[probe], (3, 3)) #put into 3 x1 matric V = [[B_vec[0, probe, t]], [B_vec[1, probe, t]], [B_vec[2, probe, t]]] B = np.dot(C, V) Bx, By, Bz = B B25[0, probe, t] = Bx B25[1, probe, t] = By B25[2, probe, t] = Bz Bmod25 = np.zeros([num_probes, len(timeB) - 1]) for j in range(num_probes): Bmod25[j, :] = np.sqrt(B25[0, j, :]**2 + B25[1, j, :]**2 + B25[2, j, :]**2) return (timeB, B25)
def main(): minorLocator = AutoMinorLocator(10) # leads to a single minor tick #ml = MultipleLocator(5) #minorLocator = MultipleLocator(10) gs = gridspec.GridSpec(4, 1) # plt.rc('text', usetex=True) plt.rcParams['text.latex.preamble'] = [r'\boldmath'] # where day day = '061219' shot_range = [6, 15] ## 87 code broke # Looks like the scope that is used for inferometer? scope_used = '1' t0 = 40 tf = 70 path = 'data\\2019\\' + day + '\\' + day + '-Analysed\\' BEGIN = 35 END = 100 setting1 = '_wind-tunnel' setting2 = '_beta_Alfvenspeed' #'_WLH_GasDelay_550mus' setting3 = '_eos_windtunnel' title1 = r': WLH, 1 mW, 600 $\mu s$, Merging Configuration' #title1 = ': WLH, 1 mW, 600 $\mu s$, coil scan at 25 kV' title2 = ': WLH, 1 mW, 600 $\mu s$, Merging Configuration' title3 = ': WLH, 1 mW, 600 $\mu s$, Merging Configuration' env, offset, phasediff = ds.dens_calib(dcs.calshot(day), scope=scope_used) a = env[0] / 2 b = env[1] / 2 # a = 1.312/2 for day = '013017' # b = 1.234/2 # a = 0.928/2 # b = 0.978/2 def f(time, A, B): # this is your 'straight line' y=f(x) return A * time + B for shot in range(shot_range[0], shot_range[1] + 1): print('On Shot', shot) # if shot==11 or 12: continue ######################################### plt.close('all') fig = plt.figure(num=1, figsize=(8.5, 10), facecolor='w', edgecolor='k') #, dpi=600) #plt.clf() fig.subplots_adjust(top=0.95, bottom=0.11, left=0.14, right=0.96, hspace=0.2) ax1 = plt.subplot(3, 1, 1) plt.text( 0.07, 0.92, '(a)', fontsize=26, weight='bold', horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes, ) density = np.zeros([20002]) dens = ssxd.interferometer(day + 'r' + str(shot), [a, b], scope=scope_used, showPlot=False) density = dens.density sm_density = ism.iter_smooth(density, loops=30, window_len=29) n = sm_density / (1e15) #popt, pcov = curve_fit(f, dens.time[0:2000], n[0:2000]) #n = n + f(dens.time, *popt*1.3) timeN = dens.time plt.plot(timeN, n, color='k', lw=2) plt.ylabel(r'n $(10^{15}\ cm^{-3})$', fontsize=20, weight='bold') plt.title(day + 'r' + str(shot) + title1, fontsize=20, weight='bold') ax1.get_yaxis().set_label_coords( -0.11, 0.6) # for aligning the y-labels in one line plt.setp(ax1.spines.values(), linewidth=2) #changing the axis linewidth ax1.tick_params(axis='both', direction='in', length=7, width=2, labelsize=20) ax1.tick_params(axis='x', which='minor', direction='in', length=5, width=1) ax1.xaxis.set_minor_locator(minorLocator) #ax1.set_xticklabels([]) #ax1.set_yticks([0.5,1.0,1.5,2.0]) plt.xlim(20, 100) # plt.ylim(0, 2) ######################################### ax2 = plt.subplot(3, 1, 2) plt.text(0.07, 0.92, '(b)', fontsize=26, weight='bold', horizontalalignment='center', verticalalignment='center', transform=ax2.transAxes) d = idsd.ids(day + 'r' + str(shot)) d.processIDS(times=[-2, 125]) timeT = d.time indices = np.where( d.kTFit.mask == False)[0] #Get indices of unmasked values Temp = d.kTFit.compressed() #Get unmasked values timeT = timeT[indices] #Adjust length of time array Terr = d.kTErr[indices] plt.errorbar(timeT, Temp, Terr, fmt='None', ecolor='k', elinewidth=2, markeredgewidth=2, capsize=4) plt.plot(timeT, Temp, 'kx', color='k', ms=8, mew=2) plt.plot(timeT, Temp, color='k', linewidth=1) plt.ylabel(r'T$_i\ (eV)$', fontsize=20, weight='bold') #ax2.set_xticklabels([]) ax2.get_yaxis().set_label_coords(-0.11, 0.6) plt.setp(ax2.spines.values(), linewidth=2) ax2.tick_params(axis='both', direction='in', length=7, width=2, labelsize=20) ax2.tick_params(axis='x', which='minor', direction='in', length=5, width=1) ax2.xaxis.set_minor_locator(minorLocator) #ax2.tick_params(axis='y', direction='in', length=7, width =2) plt.xlim(20, 100) plt.ylim(0, 35) ######################################### ax3 = plt.subplot(3, 1, 3) plt.text(0.07, 0.92, '(c)', fontsize=26, weight='bold', horizontalalignment='center', verticalalignment='center', transform=ax3.transAxes) data = hdr.getquikData( day + 'r' + str(shot)) #x, y and z components of the 5th probe ##### changing from 15x, 15y and 15z to 6x, 6y and 6z # Bx=cumtrapz(data.unCalibData[0,14,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[0,14,:], 15), data.time)/7.63e-4 # By=cumtrapz(data.unCalibData[1,14,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[1,14,:], 15), data.time)/8.06e-4 # Bz=cumtrapz(data.unCalibData[2,2,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[2,2,:], 15), data.time)/6.76e-4 # I think the get moving average is accounting for some ofset... # Bx=cumtrapz(data.unCalibData[0,5,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[0,5,:], 15), data.time)/7.63e-4 # By=cumtrapz(data.unCalibData[1,5,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[1,5,:], 15), data.time)/8.06e-4 # Bz=cumtrapz(data.unCalibData[2,1,:]-mj.get_gaussian_moving_avg(data.time, data.unCalibData[2,1,:], 15), data.time)/6.76e-4 Bx = cumtrapz( data.unCalibData[0, 5, :] - mj.get_gaussian_moving_avg( data.time, data.unCalibData[0, 5, :], 15), data.time) * -1.088718234303543795e+03 By = cumtrapz( data.unCalibData[1, 5, :] - mj.get_gaussian_moving_avg( data.time, data.unCalibData[1, 5, :], 15), data.time) * -1.119343007186590285e+03 Bz = cumtrapz( data.unCalibData[2, 1, :] - mj.get_gaussian_moving_avg( data.time, data.unCalibData[2, 1, :], 15), data.time) * -1.422749719357707363e+03 timeB = data.time - data.time[0] - 2 timeB = timeB[:-1] # Bx=cumtrapz(data.unCalibData[0,14,1500:] - np.mean(data.unCalibData[0,14,4700:6500]), data.time[1500:])/7.63e-4 # By=cumtrapz(data.unCalibData[1,14,1500:] - np.mean(data.unCalibData[1,14,4700:6500]), data.time[1500:])/8.06e-4 # Bz=cumtrapz(data.unCalibData[2,2,1500:] - np.mean(data.unCalibData[2,2,4700:6500]), data.time[1500:])/6.76e-4 # timeB=data.time-data.time[0]-2 # timeB= timeB[1500:-1] ########## detrending the Bx, By, Bz signals ################ # poptx, pcovx = curve_fit(f, timeB, Bx) # Bx = Bx - f(timeB, *poptx) # popty, pcovy = curve_fit(f, timeB, By) # By = By - f(timeB, *popty) # poptz, pcovz = curve_fit(f, timeB, Bz) # Bz = Bz - f(timeB, *poptz) # plt.plot(timeB, Bx,color='r', lw =2) # plt.plot(timeB, By,color='b', lw =2) # plt.plot(timeB, Bz,color='g', lw =2) modB = np.sqrt((Bx**2) + (By**2) + (Bz**2)) #poptz, pcovz = curve_fit(f, timeB, modB) #plt.plot(timeB, modB, linewidth=2) # plt.plot(timeB, f(timeB, *poptz),color='g', lw =2) # modB_diff = np.mean(data.unCalibData[0,14,4700:4700]) # modB = modB-modB_diff plt.plot(timeB, Bx, color='r', lw=1, label='B$_{x,6}$') plt.plot(timeB, By, color='g', lw=1, label='B$_{y,6}$') plt.plot(timeB, Bz, color='b', lw=1, label='B$_{z,6}$') plt.plot(timeB, modB, color='k', lw=2, label='$|B|$') plt.legend().draggable() plt.ylabel(r'$|B|\ (T)$', fontsize=20, weight='bold') #ax.set_xticklabels([]) #ax.xaxis.set_tick_params(labeltop='on',labelsize=20) plt.setp(ax3.spines.values(), linewidth=2) ax3.get_yaxis().set_label_coords(-0.11, 0.6) ax3.tick_params(axis='both', direction='in', length=7, width=2, labelsize=20) ax3.tick_params(axis='x', which='minor', direction='in', length=5, width=1) ax3.xaxis.set_minor_locator(minorLocator) plt.xlim(20, 100) plt.xlabel(r'$Time\ (\mu s)$', fontsize=20, weight='bold') ########## Saving Figure 1 ################## plt.show() fName = path + day + 'r' + str(shot) + setting1 + '_plot.png' # fig.savefig(fName,dpi=600,facecolor='w',edgecolor='k') '''
def run_nBT(shots, day, t_min=15, t_max=100, show=True, save=False, ylim=35): """All of this based on Manjit's code, with a minimal amount of modifications. This is the main code to prodcue graphs of the temperature, density and magnetic feidl strength -- KG 06/28/19 """ minorLocator = AutoMinorLocator(10) # leads to a single minor tick gs = gridspec.GridSpec(4, 1) plt.rcParams['text.latex.preamble'] = [r'\boldmath'] # Looks like the scope that is used for inferometer? scope_used = '1' path = 'data\\2019\\' + day + '\\Analyzed\\' setting1 = '_wind-tunnel' setting2 = '_beta_Alfvenspeed' #'_WLH_GasDelay_550mus' setting3 = '_eos_windtunnel' title1 = r': WLH, 1 mW, 600 $\mu s$, Merging Configuration' #title1 = ': WLH, 1 mW, 600 $\mu s$, coil scan at 25 kV' title2 = ': WLH, 1 mW, 600 $\mu s$, Merging Configuration' title3 = ': WLH, 1 mW, 600 $\mu s$, Merging Configuration' env, offset, phasediff = ds.dens_calib(dcs.calshot(day), scope=scope_used) a = env[0] / 2 b = env[1] / 2 # a = 1.312/2 for day = '013017' # b = 1.234/2 # a = 0.928/2 # b = 0.978/2 def f(time, A, B): # this is your 'straight line' y=f(x) return A * time + B for shot in shots: print('On Shot', shot) plt.close('all') # Adjust the spacing: fig = plt.figure(num=1, figsize=(8.5, 10), facecolor='w', edgecolor='k') #, dpi=600) fig.subplots_adjust(top=0.95, bottom=0.11, left=0.14, right=0.96, hspace=0.2) ax1 = plt.subplot(3, 1, 1) plt.text( 0.07, 0.92, '(a)', fontsize=26, weight='bold', horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes, ) dens = ssxd.interferometer(day + 'r' + str(shot), [a, b], scope=scope_used, showPlot=False) density = dens.density sm_density = ism.iter_smooth(density, loops=30, window_len=29) n = sm_density / (1e15) #popt, pcov = curve_fit(f, dens.time[0:2000], n[0:2000]) #n = n + f(dens.time, *popt*1.3) timeN = dens.time plt.plot(timeN, n, color='k', lw=2) plt.ylabel(r'n $(10^{15}\ cm^{-3})$', fontsize=20, weight='bold') # plt.title(day+'r'+str(shot)+title1, fontsize=20, weight='bold') plt.title(day + 'r' + str(shot), fontsize=20, weight='bold') ax1.get_yaxis().set_label_coords( -0.11, 0.6) # for aligning the y-labels in one line plt.setp(ax1.spines.values(), linewidth=2) #changing the axis linewidth ax1.tick_params(axis='both', direction='in', length=7, width=2, labelsize=20) ax1.tick_params(axis='x', which='minor', direction='in', length=5, width=1) ax1.xaxis.set_minor_locator(minorLocator) plt.xlim(t_min, t_max) ######################################### ax2 = plt.subplot(3, 1, 2) plt.text(0.07, 0.92, '(b)', fontsize=26, weight='bold', horizontalalignment='center', verticalalignment='center', transform=ax2.transAxes) d = idsd.ids(day + 'r' + str(shot)) d.processIDS(times=[-2, 125]) timeT = d.time # This is where the errors happen? indices = np.where( d.kTFit.mask == False)[0] #Get indices of unmasked values Temp = d.kTFit.compressed() #Get unmasked values timeT = timeT[indices] #Adjust length of time array Terr = d.kTErr[indices] plt.errorbar(timeT, Temp, Terr, fmt='None', ecolor='k', elinewidth=2, markeredgewidth=2, capsize=4) plt.plot(timeT, Temp, 'kx', color='k', ms=8, mew=2) plt.plot(timeT, Temp, color='k', linewidth=1) plt.ylabel(r'T$_i\ (eV)$', fontsize=20, weight='bold') #ax2.set_xticklabels([]) ax2.get_yaxis().set_label_coords(-0.11, 0.6) plt.setp(ax2.spines.values(), linewidth=2) ax2.tick_params(axis='both', direction='in', length=7, width=2, labelsize=20) ax2.tick_params(axis='x', which='minor', direction='in', length=5, width=1) ax2.xaxis.set_minor_locator(minorLocator) #ax2.tick_params(axis='y', direction='in', length=7, width =2) plt.xlim(t_min, t_max) plt.ylim(0, ylim) ######################################### ax3 = plt.subplot(3, 1, 3) plt.text(0.07, 0.92, '(c)', fontsize=26, weight='bold', horizontalalignment='center', verticalalignment='center', transform=ax3.transAxes) data = hdr.getquikData( day + 'r' + str(shot)) #x, y and z components of the 5th probe #calibration factors from lookup_4 calib = [ 9.834933502238857272e+02, -1.263620982013806497e+03, -1.679900552773548725e+03 ] Bx = cumtrapz( data.unCalibData[0, 4, :] - mj.get_gaussian_moving_avg( data.time, data.unCalibData[0, 4, :], 15), data.time) * calib[0] By = cumtrapz( data.unCalibData[1, 4, :] - mj.get_gaussian_moving_avg( data.time, data.unCalibData[1, 4, :], 15), data.time) * calib[1] Bz = cumtrapz( data.unCalibData[2, 4, :] - mj.get_gaussian_moving_avg( data.time, data.unCalibData[2, 4, :], 15), data.time) * calib[2] timeB = data.time - data.time[0] - 2 # timeB= data.time # make sure that the dimesntions match timeB = timeB[:len(Bx)] modB = np.sqrt((Bx**2) + (By**2) + (Bz**2)) plt.plot(timeB, Bx, color='r', lw=1, label='B$_{x,6}$') plt.plot(timeB, By, color='g', lw=1, label='B$_{y,6}$') plt.plot(timeB, Bz, color='b', lw=1, label='B$_{z,6}$') plt.plot(timeB, modB, color='k', lw=2, label='$|B|$') plt.legend().draggable() plt.ylabel(r'$|B|\ (G)$', fontsize=20, weight='bold') plt.setp(ax3.spines.values(), linewidth=2) ax3.get_yaxis().set_label_coords(-0.11, 0.6) ax3.tick_params(axis='both', direction='in', length=7, width=2, labelsize=20) ax3.tick_params(axis='x', which='minor', direction='in', length=5, width=1) ax3.xaxis.set_minor_locator(minorLocator) plt.xlim(t_min, t_max) plt.xlabel(r'$Time\ (\mu s)$', fontsize=20, weight='bold') ########## Saving Figure 1 ################## if show: plt.show() fName = path + day + 'r' + str(shot) + setting1 + '_plot.png' if save: fig.savefig(fName, dpi=600, facecolor='w', edgecolor='k')
def ratio_4_doc(shot, dir, num_probes = 16): """ This finds the ratio between the idealized helmholtz field and the actual recoreded signal This also corrects for inverted signals... however due to what I'm assuming is noise, finding the inverted ones are a bit tricky - feel free to uncomment the plotting lines and see if it needs adjusments, though I did get it working reliably for the 050119 calibration (SI units, meters, Tesla) -- KG 06/24/19 """ # data = [[0] *3 for i in range(num_probes)] # magdata = hdr.getMagData(shot) probe_locs = get_probeLocs_calib_setup(shot) data=hdr.getquikData(shot) time,eastcurrent,westcurrent = loadcurrent(shot)#using eastcurrent ratios = [[0]*3 for i in range(num_probes)] for probe in range(num_probes): ratio =1 inverted = False # fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True) B=sp.signal.detrend(cumtrapz(data.unCalibData[dir,probe,:], data.time)) plot_time = data.time[:-1] if(np.max(B[2000:6000]) < abs(np.average(B[2000:6000]))): # print("\ninverted!") inverted = True # B = B* -1 # ratio = -1 r = probe_locs[probe] max_current = polyPeak_noPlot(time,eastcurrent) # if(np.max(eastcurrent) < -1*(np.min(eastcurrent))): # max_current = -1*np.min(eastcurrent) helmB = helmholtz2(r,max_current) # THis is intentional! I am only using shots where the cmponent is lined # up with the z-direction of the helmholz field # helmB[2] = helmB[2]*-1 max_theoretical = np.max(helmB[2]) max_measured = polyPeak_noPlot(plot_time, B) ratio = ratio * max_theoretical/max_measured if ratio > 30000 or ratio < -30000: ratio = 0 ratios[probe][dir] = ratio # print("\tRatio is: %f" %(ratio)) # if(inverted and ratio <0): # print("Inverted and ratio reflects that") # elif(not inverted and ratio <0): if probe ==1: print("\n Ratio: %5f \n\t max_measured: %3f, \n\t max_theoretical: %5f"%(ratio,max_measured,max_theoretical ) ) # Compute the median of the non-zero elements # m = np.median(foo[foo > 0]) # Assign the median to the zero elements # foo[foo == 0] = m return ratios