def ISRSspecmake(ionocont,sensdict,npts): """ This function will take an ionocontainer instance of plasma parameters and create ISR spectra for each object. Inputs ionocont - An instance of the ionocontainer class with plasma parameters. Its param list must an array of [Nl,Nt,Ni,2]. sensdict - A dictionary with sensort information. npts - The number of points for the spectra. Outputs omeg - The frequency vector in Hz. outspects - The spectra which have been weighted using the RCS. The weighting is npts^2 *rcs. """ Vi = ionocont.getDoppler() specobj = ISRSpectrum(centerFrequency =sensdict['fc'],nspec = npts,sampfreq=sensdict['fs']) if ionocont.Time_Vector is None: N_x = ionocont.Param_List.shape[0] N_t = 1 outspecs = sp.zeros((N_x,1,npts)) full_grid = False else: (N_x,N_t) = ionocont.Param_List.shape[:2] outspecs = sp.zeros((N_x,N_t,npts)) full_grid = True (N_x,N_t) = outspecs.shape[:2] outspecsorig = sp.zeros_like(outspecs) outrcs = sp.zeros((N_x,N_t)) #pdb.set_trace() for i_x in sp.arange(N_x): for i_t in sp.arange(N_t): print('\t Time:{0:d} of {1:d} Location:{2:d} of {3:d}, now making spectrum.'.format(i_t,N_t,i_x,N_x)) if full_grid: cur_params = ionocont.Param_List[i_x,i_t] cur_vel = Vi[i_x,i_t] else: cur_params = ionocont.Param_List[i_x] (omeg,cur_spec,rcs) = specobj.getspecsep(cur_params,ionocont.Species,cur_vel,rcsflag=True) specsum = sp.absolute(cur_spec).sum() cur_spec_weighted = len(cur_spec)**2*cur_spec*rcs/specsum outspecsorig[i_x,i_t] = cur_spec outrcs[i_x,i_t] = rcs outspecs[i_x,i_t] = cur_spec_weighted return (omeg,outspecs)
def ISRspecmakeout(paramvals, fc, fs, species, npts): """ This will make a spectra for a set a param values. This is mainly used in the plotting functions to get spectra for given parameters. Input paramvals - A N_x x N_t x 2Nsp+1 numpy array that holds the parameter values. Nx is number of spatial locations, N_t is number of times and Nsp is number of ion and electron species. fc - The carrier frequency of the ISR. fs - The sampling frequency of the ISR. species - A list of species. npts - The number of points for each spectrum Output omeg - Frequency vector in Hz. outspecs - the spectra to be output.""" if paramvals.ndim == 2: paramvals = paramvals[np.newaxis] (N_x, N_t) = paramvals.shape[:2] Nsp = len(species) Vi = paramvals[:, :, 2 * Nsp] Parammat = paramvals[:, :, :2 * Nsp].reshape((N_x, N_t, Nsp, 2)) outspecs = np.zeros((N_x, N_t, npts)) specobj = ISRSpectrum(centerFrequency=fc, nspec=npts, sampfreq=fs) outspecsorig = np.zeros_like(outspecs) outrcs = np.zeros((N_x, N_t)) for i_x in np.arange(N_x): for i_t in np.arange(N_t): cur_params = Parammat[i_x, i_t] cur_vel = Vi[i_x, i_t] (omeg, cur_spec, rcs) = specobj.getspecsep(cur_params, species, cur_vel, rcsflag=True) specsum = np.absolute(cur_spec).sum() cur_spec_weighted = 0.5 * np.pi * len( cur_spec)**2 * cur_spec * rcs / specsum outspecsorig[i_x, i_t] = cur_spec outrcs[i_x, i_t] = rcs outspecs[i_x, i_t] = cur_spec_weighted return (omeg, outspecs)
def fitcheck(repall=[100]): x_0 = sp.array([[[1.00000000e+11, 2.00000000e+03], [1.00000000e+11, 2.00000000e+03]], [[5.00000000e+11, 2.00000000e+03], [5.00000000e+11, 2.00000000e+03]], [[1.00000000e+11, 3.00000000e+03], [1.00000000e+11, 2.00000000e+03]], [[1.00000000e+11, 2.00000000e+03], [1.00000000e+11, 3.00000000e+03]]]) sns.set_style("whitegrid") sns.set_context("notebook") x_0_red = x_0[0].flatten() x_0_red[-2] = x_0_red[-1] x_0_red[-1] = 0. configfile = 'statsbase.ini' (sensdict, simparams) = readconfigfile(configfile) ambdict = simparams['amb_dict'] pulse = simparams['Pulse'] l_p = len(pulse) Nlags = l_p lagv = sp.arange(l_p) ntypes = x_0.shape[0] nspec = 128 nrg = 64 des_pnt = 16 ISpec = ISRSpectrum(nspec=nspec, sampfreq=50e3) species = ['O+', 'e-'] spvtime = sp.zeros((ntypes, nspec)) lablist = ['Normal', 'E-Ne', 'E-Ti', 'E-Te'] v_i = 0 fitfunc = ISRSfitfunction sumrule = simparams['SUMRULE'] Nrg1 = nrg + 1 - l_p minrg = -sumrule[0].min() maxrg = Nrg1 - sumrule[1].max() Nrg2 = maxrg - minrg for i in range(ntypes): f, curspec, rcs = ISpec.getspecsep(x_0[i], species, v_i, rcsflag=True) specsum = sp.absolute(curspec).sum() spvtime[i] = rcs * curspec * nspec**2 / specsum acforig = scfft.ifft(scfft.ifftshift(spvtime, axes=1), axis=1) / nspec acfamb = sp.dot(ambdict['WttMatrix'], scfft.fftshift(acforig, axes=1).transpose()).transpose() specamb = scfft.fftshift(scfft.fft(acfamb, n=nspec, axis=1), axes=1) fig, axmat = plt.subplots(2, 2) axvec = axmat.flatten() figs, axmats = plt.subplots(2, 2) axvecs = axmats.flatten() for i in range(ntypes): ax = axvec[i] ax.plot(lagv, acfamb[i].real, label='Input') ax.set_title(lablist[i]) axs = axvecs[i] axs.plot(f * 1e-3, specamb[i].real, label='Input', linewidth=4) axs.set_title(lablist[i]) for irep, rep1 in enumerate(repall): rawdata = sp.zeros((ntypes, rep1, nrg), dtype=sp.complex128) acfest = sp.zeros((ntypes, Nrg1, l_p), dtype=rawdata.dtype) acfestsr = sp.zeros((ntypes, Nrg2, l_p), dtype=rawdata.dtype) specest = sp.zeros((ntypes, nspec), dtype=rawdata.dtype) for i in range(ntypes): for j in range(nrg - (l_p - 1)): rawdata[i, :, j:j + l_p] = MakePulseDataRepLPC( pulse, spvtime[i], 20, rep1) + rawdata[i, :, j:j + l_p] acfest[i] = CenteredLagProduct(rawdata[i], pulse=pulse) / (rep1) for irngnew, irng in enumerate(sp.arange(minrg, maxrg)): for ilag in range(Nlags): acfestsr[i][irngnew, ilag] = acfest[i][irng + sumrule[0, ilag]:irng + sumrule[1, ilag] + 1, ilag].mean(axis=0) ax = axvec[i] ax.plot(lagv, acfestsr[i, des_pnt].real / l_p, label='Np = {0}'.format(rep1)) if irep == len(repall) - 1: ax.legend() specest[i] = scfft.fftshift( scfft.fft(acfestsr[i, des_pnt], n=nspec)) axs = axvecs[i] axs.plot(f * 1e-3, specest[i].real / l_p, label='Np = {0}'.format(rep1), linewidth=4) if irep == len(repall) - 1: axs.legend() print('Parameters fitted after {0} pulses'.format(rep1)) print('Ni Ti Te Vi') for i in range(ntypes): d_func = (acfestsr[i, des_pnt] / l_p, sensdict, simparams) (x, cov_x, infodict, mesg, ier) = scipy.optimize.leastsq(func=fitfunc, x0=x_0_red, args=d_func, full_output=True) print(x) print(' ') fig.suptitle('ACF with Sum Rule') fig.savefig('pulsetestacf.png', dpi=400) plt.close(fig) figs.suptitle('Spectrum Full Array') figs.savefig('pulsetestspec.png', dpi=400) plt.close(figs)
""" import numpy as np import matplotlib.pylab as plt import seaborn as sns # from ISRSpectrum.ISRSpectrum import ISRSpectrum if __name__ == '__main__': sns.set_style("whitegrid") sns.set_context("notebook") f = np.linspace(20e3, 2.5e6, 2**10) ISpec = ISRSpectrum(nspec=2**16, bMag=3.5e-5, sampfreq=15e6, alphamax=80, f=f, dFlag=True) species = ['O+', 'e-'] databloc = np.array([[1.66e10, 863.], [1.66e10, 863.]]) #%% No B-Field f, [iline, eline] = ISpec.getspecsep(databloc, species, alphadeg=90, seplines=True) plt.figure() spec1 = iline + eline maxy = spec1.max()
""" import numpy as np import matplotlib.pylab as plt import seaborn as sns sns.set_style("whitegrid") sns.set_context("notebook") # from ISRSpectrum.ISRSpectrum import ISRSpectrum if __name__ == '__main__': ISS2 = ISRSpectrum(centerFrequency=440.2 * 1e6, bMag=0.4e-4, nspec=129, sampfreq=50e3, dFlag=True) ti_list = np.linspace(1000, 5000, 5) te = 2e3 Ne = 1e11 Ni = 1e11 species = ['O+', 'e-'] databloc = np.array([[1e11, 1100.], [1e11, 2500.]]) fig, ax = plt.subplots() for ti in ti_list: datablock = np.array([[Ni, ti], [Ne, te]]) species = ['O+', 'e-']
def ISRSfitfunction(x, y_acf, sensdict, simparams, Niratios, y_err=None): """ This is the fit fucntion that is used with scipy.optimize.leastsquares. It will take a set parameter values construct a spectrum/acf based on those values, apply the ambiguity function and take the difference between the two. Since the ACFs are complex the arrays split up and the size doubled as it is output. Inputs x - A Np array of parameter values used y_acf - This is the esitmated ACF/spectrum represented as a complex numpy array sensdict - This is a dictionary that holds many of the sensor parameters. simparams - This is a dictionary that holds info on the simulation parameters. y_err - default None - A numpy array of size Nd that holds the standard deviations of the data. Output y_diff - A Nd or 2Nd array if input data is complex that is the difference between the data and the fitted model""" npts = simparams['numpoints'] specs = simparams['species'] amb_dict = simparams['amb_dict'] numtype = simparams['dtype'] if 'FitType' in simparams.keys(): fitspec = simparams['FitType'] else: fitspec = 'Spectrum' nspecs = len(specs) (Ti, Ne, Te, v_i) = x datablock = np.zeros((nspecs, 2), dtype=x.dtype) datablock[:-1, 0] = Ne * Niratios datablock[:-1, 1] = Ti datablock[-1, 0] = Ne datablock[-1, 1] = Te # determine if you've gone beyond the bounds # penalty for being less then zero grt0 = np.exp(-datablock) pentsum = np.zeros(grt0.size + 1) pentsum[:-1] = grt0.flatten() specobj = ISRSpectrum(centerFrequency=sensdict['fc'], nspec=npts, sampfreq=sensdict['fs']) (omeg, cur_spec, rcs) = specobj.getspecsep(datablock, specs, v_i, rcsflag=True) cur_spec.astype(numtype) # Create spectrum guess (tau, acf) = spect2acf(omeg, cur_spec) if amb_dict['WttMatrix'].shape[-1] != acf.shape[0]: pdb.set_trace() guess_acf = np.dot(amb_dict['WttMatrix'], acf) # apply ambiguity function guess_acf = guess_acf * rcs / guess_acf[0].real if fitspec.lower() == 'spectrum': # fit to spectrums spec_interm = scfft.fft(guess_acf, n=len(cur_spec)) spec_final = spec_interm.real y_interm = scfft.fft(y_acf, n=len(spec_final)) y = y_interm.real yout = (y - spec_final) elif fitspec.lower() == 'acf': yout = y_acf - guess_acf if y_err is not None: yout = yout * 1. / y_err # Cannot make the output a complex array! To avoid this problem simply double # the size of the array and place the real and imaginary parts in alternating spots. if np.iscomplexobj(yout): youttmp = yout.copy() yout = np.zeros(2 * len(youttmp)).astype(youttmp.real.dtype) yout[::2] = youttmp.real yout[1::2] = youttmp.imag penadd = np.sqrt(np.power(np.absolute(yout), 2).sum()) * pentsum.sum() return yout + penadd
import numpy as np from ISRSpectrum.ISRSpectrum import ISRSpectrum import matplotlib.pylab as plt import seaborn as sns if __name__== '__main__': sns.set_style("whitegrid") sns.set_context("notebook") # f = np.lin(1,7,2**10) f = np.linspace(0.,5e6,2**12) ISpec = ISRSpectrum(nspec=2**16,sampfreq=15e6,alphamax=60,f=f,dFlag=True) species=['O+','e-'] databloc = np.array([[1e11,1100.],[1e11,2500.]]) #%% No B-Field f,[iline,eline] = ISpec.getspecsep(databloc,species,alphadeg=90,seplines=True) plt.figure() spec1=iline+eline maxy=spec1.max() l1=plt.plot(f,spec1,'-',label='Sum',lw=3)[0] l2=plt.plot(f,iline,':',label='Ion Line',lw=3)[0] l3=plt.plot(f,eline,'--',label='Elec. Line',lw=3)[0]
def main(): sns.set_style("whitegrid") sns.set_context("notebook") inifile= "/Users/Bodangles/Documents/Python/RadarDataSim/Testdata/PFISRExample.pickle" (sensdict,simparams) = readconfigfile(inifile) simdtype = simparams['dtype'] sumrule = simparams['SUMRULE'] npts = simparams['numpoints'] amb_dict = simparams['amb_dict'] # for spectrum ISS2 = ISRSpectrum(centerFrequency = 440.2*1e6, bMag = 0.4e-4, nspec=npts, sampfreq=sensdict['fs'],dFlag=True) ti = 2e3 te = 2e3 Ne = 1e11 Ni = 1e11 datablock90 = sp.array([[Ni,ti],[Ne,te]]) species = simparams['species'] (omega,specorig,rcs) = ISS2.getspecsep(datablock90, species,rcsflag = True) cur_filt = sp.sqrt(scfft.ifftshift(specorig*npts*npts*rcs/specorig.sum())) #for data Nrep = 10000 pulse = sp.ones(14) lp_pnts = len(pulse) N_samps = 100 minrg = -sumrule[0].min() maxrg = N_samps+lp_pnts-sumrule[1].max() Nrng2 = maxrg-minrg; out_data = sp.zeros((Nrep,N_samps+lp_pnts),dtype=simdtype) samp_num = sp.arange(lp_pnts) for isamp in range(N_samps): cur_pnts = samp_num+isamp cur_pulse_data = MakePulseDataRep(pulse,cur_filt,rep=Nrep) out_data[:,cur_pnts] = cur_pulse_data+out_data[:,cur_pnts] lagsData = CenteredLagProduct(out_data,numtype=simdtype,pulse =pulse) lagsData=lagsData/Nrep # divide out the number of pulses summed Nlags = lagsData.shape[-1] lagsDatasum = sp.zeros((Nrng2,Nlags),dtype=lagsData.dtype) for irngnew,irng in enumerate(sp.arange(minrg,maxrg)): for ilag in range(Nlags): lagsDatasum[irngnew,ilag] = lagsData[irng+sumrule[0,ilag]:irng+sumrule[1,ilag]+1,ilag].mean(axis=0) lagsDatasum=lagsDatasum/lp_pnts # divide out the pulse length (tau,acf) = spect2acf(omega,specorig) # apply ambiguity function tauint = amb_dict['Delay'] acfinterp = sp.zeros(len(tauint),dtype=simdtype) acfinterp.real =spinterp.interp1d(tau,acf.real,bounds_error=0)(tauint) acfinterp.imag =spinterp.interp1d(tau,acf.imag,bounds_error=0)(tauint) # Apply the lag ambiguity function to the data guess_acf = sp.zeros(amb_dict['Wlag'].shape[0],dtype=sp.complex128) for i in range(amb_dict['Wlag'].shape[0]): guess_acf[i] = sp.sum(acfinterp*amb_dict['Wlag'][i]) # pdb.set_trace() guess_acf = guess_acf*rcs/guess_acf[0].real # fit to spectrums spec_interm = scfft.fftshift(scfft.fft(guess_acf,n=npts)) spec_final = spec_interm.real allspecs = scfft.fftshift(scfft.fft(lagsDatasum,n=len(spec_final),axis=-1),axes=-1) # allspecs = scfft.fftshift(scfft.fft(lagsDatasum,n=npts,axis=-1),axes=-1) fig = plt.figure() plt.plot(omega,spec_final.real,label='In',linewidth=5) plt.hold(True) plt.plot(omega,allspecs[40].real,label='Out',linewidth=5) plt.axis((omega.min(),omega.max(),0.0,2e11)) plt.show(False)
import matplotlib.pylab as plt import seaborn as sns sns.set_style("white") sns.set_context("notebook") # from ISRSpectrum.ISRSpectrum import ISRSpectrum if __name__ == '__main__': mpl.rcParams['text.usetex'] = True mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}' ] #for \text command databloc = np.array([[1e11, 1e3], [1e11, 2.5e3]]) nspec = 256 spfreq = 50e3 ISpec_ion = ISRSpectrum(centerFrequency=449e6, nspec=nspec, sampfreq=spfreq, dFlag=True) species = ['O+', 'e-'] # databloc = np.array([[1.66e10,863.],[1.66e10,863.]]) ylim = [0, 1.4] ylim2 = [-.5, 1.4] flims = np.array([3.03e6, 3.034e6]) #%% With B-Field fion, ionline = ISpec_ion.getspecsep(databloc, species) acf = scfft.ifft(scfft.ifftshift(ionline)).real tau = scfft.ifftshift( np.arange(-np.ceil((float(nspec) - 1) / 2), np.floor((float(nspec) - 1) / 2) + 1)) / spfreq
""" import numpy as np from matplotlib.pyplot import subplots, show import seaborn as sns sns.set_style("white") sns.set_context("talk", font_scale=1.25) # from ISRSpectrum.ISRSpectrum import ISRSpectrum if __name__ == '__main__': databloc = np.array([[1e11, 1e3], [1e11, 2.5e3]]) f = np.linspace(3.03e6, 3.034e6, 256) f_n = -f[::-1] # f = np.logspace(1,np.log10(8e3),2**10) ISpec = ISRSpectrum(centerFrequency=449e6, f=f, dFlag=True) ISpec_n = ISRSpectrum(centerFrequency=449e6, f=f_n, dFlag=True) ISpec_ion = ISRSpectrum(centerFrequency=449e6, nspec=256, sampfreq=50e3, dFlag=True) species = ['O+', 'e-'] # databloc = np.array([[1.66e10,863.],[1.66e10,863.]]) flims = np.array([3.03e6, 3.034e6]) #%% With B-Field eline = ISpec.getspecsep(databloc, species)[1] eline_neg = ISpec_n.getspecsep(databloc, species)[1] fion, ionline = ISpec_ion.getspecsep(databloc, species) fall = np.concatenate((f_n, fion, f), 0)
sns.set_context("notebook") # from ISRSpectrum.ISRSpectrum import ISRSpectrum from isrutilities.physConstants import v_C_0 if __name__ == '__main__': databloc = np.array([[1e11, 1e3], [1e11, 2.5e3]]) species = ['O+', 'e-'] newcentfreq = 449e6 + np.linspace(-200, 550, 250) * 1e6 k_all = 2 * 2 * np.pi * newcentfreq / v_C_0 k_lims = np.array([k_all.min(), k_all.max()]) freq_lims = np.array([newcentfreq.min(), newcentfreq.max()]) oution = [] for i, if_0 in enumerate(newcentfreq): ISpec_ion = ISRSpectrum(centerFrequency=if_0, nspec=256, sampfreq=50e3, dFlag=False) fion, ionline = ISpec_ion.getspecsep(databloc, species) oution.append(ionline) oution = np.array(oution) F, K_b = np.meshgrid(fion, k_all) fig, ax = plt.subplots(1, 1, sharey=True, figsize=(4, 4), facecolor='w') l1 = ax.pcolor(F * 1e-3, K_b, oution / oution.max(), cmap='viridis') cb1 = plt.colorbar(l1, ax=ax) ax.set_xlim([-25, 25]) ax.set_ylim(k_lims) ax.set_xlabel('Frequency (kHz)', fontsize=14)