def write_array(fid,A,format='binary'): """ Write an ndarray or sparse matrix to a file format may be one of ['basic','ascii','binary'] basic - Most human readable - Only works for arrays of rank 1 and 2 - Does not work for sparse matrices ascii - Somewhat human readable - Works for ndarrays and sparse matrices binary - Fastest format - Works for ndarrays and sparse matrices - Data stored in LittleEndian """ if format not in ['basic','ascii','binary']: raise ArrayIOException('Unknown format: ['+format+']') if not isinstance(fid, io.IOBase): fid = open(fid,'wb') if isinstance(A, numpy.ndarray): A = numpy.ascontiguousarray(A) #strided arrays break in write if format == 'basic': if ndim(A) > 2: raise ArrayIOException('basic format only works for rank 1 or 2 arrays') write_basic(fid,A) else: write_ndarray(fid,A,format) elif scipy.sparse.isspmatrix(A): if format not in ['ascii','binary']: raise ArrayIOException('sparse matrices require ascii or binary format') write_sparse(fid,A,format) else: try: A = asarray(A) if format == 'basic': if ndim(A) > 2: raise ArrayIOException('basic format only works for rank 1 or 2 arrays') write_basic(fid,A) else: write_ndarray(fid,A,format) except: raise ArrayIOException('Unknown data type and unable to convert to numpy.ndarray')
def getclosest(self,coords,timelist=None): """This method will get the closest set of parameters in the coordinate space. It will return the parameters from all times. Input coords - A list of x,y and z coordinates. Output paramout - A NtxNp array from the closes output params sphereout - A Nc length array The sphereical coordinates of the closest point. cartout - Cartisian coordinates of the closes point. """ X_vec = self.Cart_Coords[:,0] Y_vec = self.Cart_Coords[:,1] Z_vec = self.Cart_Coords[:,2] xdiff = X_vec -coords[0] ydiff = Y_vec -coords[1] zdiff = Z_vec -coords[2] distall = xdiff**2+ydiff**2+zdiff**2 minidx = np.argmin(distall) paramout = self.Param_List[minidx] velout = self.Velocity[minidx] datatime = self.Time_Vector if sp.ndim(self.Time_Vector)>1: datatime = datatime[:,0] if timelist is not None: timeindx = [] for itime in timelist: timeindx.append(sp.argmin(sp.absolute(itime-datatime))) paramout=paramout[timeindx] velout=velout[timeindx] sphereout = self.Sphere_Coords[minidx] cartout = self.Cart_Coords[minidx] return (paramout,velout,sphereout,cartout,np.sqrt(distall[minidx]))
def _(ops, locs, n): ''' Put operators in a circuit and compile them. notice the big end are high loc bits! Args: ops (list): list of single bit operators. locs (list): list of positions. n (int): total number of bits. Returns: csr_matrix: resulting matrix. Note: rotation gates may be optimized, using 1+1j*sin(theta)*sigma ''' if np.ndim(locs) == 0: locs = [locs] if not isinstance(ops, (list, tuple)): ops = [ops] locs = np.asarray(locs) locs = n - locs - 1 order = np.argsort(locs) locs = np.concatenate([[-1], locs[order], [n]]) return _wrap_identity([ops[i] for i in order], np.diff(locs) - 1)
def ndarray_header(A): header = ArrayHeader() header['type'] = 'ndarray' header['rank'] = ndim(A) header['dims'] = ','.join(map(str,A.shape)) header['dtype'] = A.dtype.name return header
def concatenate(misalignmentsAndScales, biases): if sp.ndim(biases) > 1: biases = sp.reshape(biases, 3) modelParametersMatrix = sp.concatenate( (misalignmentsAndScales, sp.expand_dims(biases, axis=1)), axis=1) return sp.reshape(modelParametersMatrix, 12)
def getclosest(self, coords, timelist=None): """ This method will get the closest set of parameters in the coordinate space. It will return the parameters from all times. Input coords - A list of x,y and z coordinates. Output paramout - A NtxNp array from the closes output params sphereout - A Nc length array The sphereical coordinates of the closest point. cartout - Cartisian coordinates of the closes point. distance - The spatial distance between the returned location and the desired location. minidx - The spatial index point. tvec - The times of the returned data. """ X_vec = self.Cart_Coords[:, 0] Y_vec = self.Cart_Coords[:, 1] Z_vec = self.Cart_Coords[:, 2] xdiff = X_vec - coords[0] ydiff = Y_vec - coords[1] zdiff = Z_vec - coords[2] distall = xdiff**2 + ydiff**2 + zdiff**2 minidx = np.argmin(distall) paramout = self.Param_List[minidx] velout = self.Velocity[minidx] datatime = self.Time_Vector tvec = self.Time_Vector if sp.ndim(self.Time_Vector) > 1: datatime = datatime[:, 0] if isinstance(timelist, list): timelist = sp.array(timelist) if timelist is not None: timeindx = [] for itime in timelist: if sp.isscalar(itime): timeindx.append(sp.argmin(sp.absolute(itime - datatime))) else: # look for overlap log1 = (tvec[:, 0] >= itime[0]) & (tvec[:, 0] < itime[1]) log2 = (tvec[:, 1] > itime[0]) & (tvec[:, 1] <= itime[1]) log3 = (tvec[:, 0] <= itime[0]) & (tvec[:, 1] > itime[1]) log4 = (tvec[:, 0] > itime[0]) & (tvec[:, 1] < itime[1]) tempindx = sp.where(log1 | log2 | log3 | log4)[0] timeindx = timeindx + tempindx.tolist() paramout = paramout[timeindx] velout = velout[timeindx] tvec = tvec[timeindx] sphereout = self.Sphere_Coords[minidx] cartout = self.Cart_Coords[minidx] return (paramout, velout, sphereout, cartout, np.sqrt(distall[minidx]), minidx, tvec)
def getclosest(self,coords,timelist=None): """ This method will get the closest set of parameters in the coordinate space. It will return the parameters from all times. Input coords - A list of x,y and z coordinates. Output paramout - A NtxNp array from the closes output params sphereout - A Nc length array The sphereical coordinates of the closest point. cartout - Cartisian coordinates of the closes point. distance - The spatial distance between the returned location and the desired location. minidx - The spatial index point. tvec - The times of the returned data. """ X_vec = self.Cart_Coords[:,0] Y_vec = self.Cart_Coords[:,1] Z_vec = self.Cart_Coords[:,2] xdiff = X_vec -coords[0] ydiff = Y_vec -coords[1] zdiff = Z_vec -coords[2] distall = xdiff**2+ydiff**2+zdiff**2 minidx = np.argmin(distall) paramout = self.Param_List[minidx] velout = self.Velocity[minidx] datatime = self.Time_Vector tvec = self.Time_Vector if sp.ndim(self.Time_Vector)>1: datatime = datatime[:,0] if isinstance(timelist,list): timelist=sp.array(timelist) if timelist is not None: timeindx = [] for itime in timelist: if sp.isscalar(itime): timeindx.append(sp.argmin(sp.absolute(itime-datatime))) else: # look for overlap log1 = (tvec[:,0]>=itime[0]) & (tvec[:,0]<itime[1]) log2 = (tvec[:,1]>itime[0]) & (tvec[:,1]<=itime[1]) log3 = (tvec[:,0]<=itime[0]) & (tvec[:,1]>itime[1]) log4 = (tvec[:,0]>itime[0]) & (tvec[:,1]<itime[1]) tempindx = sp.where(log1|log2|log3|log4)[0] timeindx = timeindx +tempindx.tolist() paramout=paramout[timeindx] velout=velout[timeindx] tvec = tvec[timeindx] sphereout = self.Sphere_Coords[minidx] cartout = self.Cart_Coords[minidx] return (paramout,velout,sphereout,cartout,np.sqrt(distall[minidx]),minidx,tvec)
def triangulate_ncube(vertices, indices): n_dims = ndim(indices) - 1 n_cubes = indices.shape[0] n_verts = vertices.shape[0] if n_dims <= 1: #cube mesh only contains edges return vertices, indices if n_dims > 2: raise NotImplementedError('nCube meshes with n > 2 not supported') cell_centers = vertices[indices.reshape(n_cubes, -1)].mean(axis=1) n_faces = 2 * n_dims * n_cubes faces = zeros((n_faces, ) + (2, ) * (n_dims - 1), dtype=indices.dtype) for i in range(n_dims): s0 = [slice(None, None, None)] * (i + 1) + [ 0 ] + [slice(None, None, None)] * (n_dims - i - 1) s1 = [slice(None, None, None)] * (i + 1) + [ 1 ] + [slice(None, None, None)] * (n_dims - i - 1) faces[(2 * i + 0) * n_cubes:(2 * i + 1) * n_cubes] = indices[s0] faces[(2 * i + 1) * n_cubes:(2 * i + 2) * n_cubes] = indices[s1] #this seems to be the correct pattern if (n_dims - 1 - i) % 2 == n_dims % 2: #flip 1 temp = faces[(2 * i + 1) * n_cubes:(2 * i + 2) * n_cubes, 0].copy() faces[(2 * i + 1) * n_cubes:(2 * i + 2) * n_cubes, 0] = faces[(2 * i + 1) * n_cubes:(2 * i + 2) * n_cubes, 1] faces[(2 * i + 1) * n_cubes:(2 * i + 2) * n_cubes, 1] = temp else: #flip 0 temp = faces[(2 * i + 0) * n_cubes:(2 * i + 1) * n_cubes, 0].copy() faces[(2 * i + 0) * n_cubes:(2 * i + 1) * n_cubes, 0] = faces[(2 * i + 0) * n_cubes:(2 * i + 1) * n_cubes, 1] faces[(2 * i + 0) * n_cubes:(2 * i + 1) * n_cubes, 1] = temp face_vertices, face_indices = triangulate_ncube(vertices, faces) center_indices = (arange(n_cubes) + face_vertices.shape[0]).reshape( (n_cubes, 1)) center_indices = tile(center_indices, (face_indices.shape[0] / n_cubes, 1)) new_vertices = vstack((face_vertices, cell_centers)) new_indices = hstack((center_indices, face_indices)) return new_vertices, new_indices
def simplex_array_searchsorted(s, v): """Find the row indices (of s) corresponding to the simplices stored in the rows of simplex array v. The rows of s must be stored in lexicographical order. Example ------- >>> from numpy import array >>> s = array([[0,1],[0,2],[1,2],[1,3]]) >>> v = array([[1,2],[0,2]]) >>> simplex_array_searchsorted(s,v) array([2, 1]) """ s = asarray(s) v = asarray(v) if ndim(s) != 2 or ndim(v) != 2: raise ValueError('expected rank 2 arrays') if s.shape[1] != v.shape[1]: raise ValueError('number of columns must agree') # compute row indices by sorting both arrays together Ns = s.shape[0] Nv = v.shape[0] perm = lexsort(vstack((s, v))[:, ::-1].T) flags = concatenate((ones(Ns, dtype=int), zeros(Nv, dtype=int))) indices = empty(Ns + Nv, dtype=int) indices[perm] = cumsum(flags[perm]) indices = indices[Ns:].copy() indices -= 1 return indices
def test_dense(self): sizes = [(2, 2), (3, 3), (5, 1), (1, 5)] sizes += [(2, 2, 2), (4, 3, 2), (1, 1, 5), (1, 5, 1), (5, 1, 1)] for dims in sizes: mats = [arange(prod(dims)).reshape(dims), rand(*dims)] for A in mats: formats = ['binary', 'ascii'] if ndim(A) <= 2: formats.append('basic') #use basic when possible for format in formats: write_array(filename, A, format=format) B = read_array(filename) assert_almost_equal(A, B, decimal=12)
def check_param(self): """ Check parameters - mostly just that shape of ndarrays match """ if scipy.ndim(self.param['initial_heading'].shape) > 1: raise (ValueError, 'initial_heading must have ndim=1') equal_shape_list = [ 'x_start_position', 'y_start_position', 'flight_speed', 'release_time' ] for item in equal_shape_list: if self.param[item].shape != self.param['initial_heading'].shape: raise ( ValueError, '{0}.shape must equal initial_heading.shape'.format(item))
def exact_moments( w, M1, M2, M3 ): """Tests the algorithm with exact means""" assert( ndim( w ) == 1 ) # Input processing k = w.shape[0] M1, M2, M3 = M1, M2, M3 assert( mrank(M1) == k ) assert( mrank(M2) == k ) assert( mrank(M3) == k ) # Get pairwise estimates P12 = M1.dot( diag( w ).dot( M2.T ) ) P13 = M1.dot( diag( w ).dot( M3.T ) ) #P123 = sum( [ w[i] * tensorify( M1.T[i], M2.T[i], M3.T[i] ) for i in xrange( k ) ] ) P123 = lambda theta: M1.dot( diag( w ) ).dot( diag( M3.T.dot( theta ) ) ).dot( M2.T ) return P12, P13, P123
def exact_moments( w, M1, M2, M3 ): """Tests the algorithm with exact means""" assert( ndim( w ) == 1 ) # Input processing k = w.shape[0] M1, M2, M3 = M1, M2, M3 assert( mrank(M1) == k ) assert( mrank(M2) == k ) assert( mrank(M3) == k ) # Get pairwise estimates P12 = M1.dot( diag( w ).dot( M2.T ) ) P13 = M1.dot( diag( w ).dot( M3.T ) ) P123 = lambda eta: \ M1.dot( diag( M3.T.dot(eta) * w ) ).dot( M2.T ) return P12, P13, P123
def fullrho(qu, squ): print("#Starting full density matrix simulation!") #Build state from pure states received from the MPS processes rho = sp.zeros((2**N, 2**N), dtype=sp.complex128) psis = [None] * N_samp for n in range(N_samp): pnum, psi = squ.get() psis[pnum] = psi rho += sp.outer(psi, psi.conj()) squ.task_done() rho /= sp.trace(rho) Hfull = get_full_op(get_ham(N, lam)) linds = get_linds(N, eps) linds = [(n, L.reshape(tuple([sp.prod(L.shape[:sp.ndim(L)/2])]*2))) for (n, L) in linds] linds_full = [sp.kron(sp.eye(2**(n-1)), sp.kron(L, sp.eye(2**(N - n + 1) / L.shape[0]))) for (n, L) in linds] for L in linds_full: assert L.shape == Hfull.shape Qfull = -1.j * Hfull - 0.5 * sp.sum([L.conj().T.dot(L) for L in linds_full], axis=0) szs = [None] + [sp.kron(sp.kron(sp.eye(2**(n - 1)), Sz), sp.eye(2**(N - n))) for n in range(1, N + 1)] for i in range(N_steps + 1): rho /= sp.trace(rho) esz = [] for n in range(1, N + 1): esz.append(sp.trace(szs[n].dot(rho)).real) if i % res_every == 0: if qu is None: print(esz) else: qu.put([-1, i, esz]) qu.put([-2, i, [sp.NaN] * N]) #this slot is reserved for a second "exact" result #Do Euler steps, approximately integrating the Lindblad master equation rho += dt * (Qfull.dot(rho) + rho.dot(Qfull.conj().T) + sum([L.dot(rho).dot(L.conj().T) for L in linds_full]))
def _(ops, locs, n): ''' Put operators in a circuit and compile them. notice the big end are high loc bits! Args: ops (list): list of single bit operators. locs (list): list of positions. n (int): total number of bits. Returns: array: resulting matrix. ''' if np.ndim(locs) == 0: locs = [locs] if not isinstance(ops, (list, tuple)): ops = [ops] locs = np.asarray(locs) locs = n - locs order = np.argsort(locs) locs = np.concatenate([[0], locs[order], [n + 1]]) return _wrap_identity([ops[i] for i in order], np.diff(locs) - 1)
def plotacfs(coords, times, configfile, maindir, cartcoordsys=True, indisp=True, acfdisp=True, fitdisp=True, filetemplate='acf', suptitle='ACF Comparison', invacf=''): """ This will create a set of images that compare the input ISR acf to the output ISR acfs from the simulator. Inputs coords - An Nx3 numpy array that holds the coordinates of the desired points. times - A numpy list of times in seconds. configfile - The name of the configuration file used. cartcoordsys - (default True)A bool, if true then the coordinates are given in cartisian if false then it is assumed that the coords are given in sphereical coordinates. specsfilename - (default None) The name of the file holding the input spectrum. acfname - (default None) The name of the file holding the estimated ACFs. filetemplate (default 'spec') This is the beginning string used to save the images. """ # indisp = specsfilename is not None # acfdisp = acfname is not None maindir = Path(maindir).expanduser() sns.set_style("whitegrid") sns.set_context("notebook") acfname = maindir.joinpath('ACF', '00lags.h5') ffit = maindir.joinpath('Fitted', 'fitteddata.h5') specsfiledir = maindir.joinpath('Spectrums') (sensdict, simparams) = readconfigfile(configfile) simdtype = simparams['dtype'] npts = simparams['numpoints'] * 3.0 amb_dict = simparams['amb_dict'] if sp.ndim(coords) == 1: coords = coords[sp.newaxis, :] Nt = len(times) Nloc = coords.shape[0] sns.set_style("whitegrid") sns.set_context("notebook") pulse = simparams['Pulse'] ts = sensdict['t_s'] tau1 = sp.arange(pulse.shape[-1]) * ts if indisp: dirlist = [i.name for i in specsfiledir.glob('*.h5')] timelist = sp.array([float(i.split()[0]) for i in dirlist]) for itn, itime in enumerate(times): filear = sp.argwhere(timelist >= itime) if len(filear) == 0: filenum = len(timelist) - 1 else: filenum = filear[0][0] specsfilename = specsfiledir.joinpath(dirlist[filenum]) Ionoin = IonoContainer.readh5(str(specsfilename)) if itn == 0: specin = sp.zeros( (Nloc, Nt, Ionoin.Param_List.shape[-1])).astype( Ionoin.Param_List.dtype) omeg = Ionoin.Param_Names npts = Ionoin.Param_List.shape[-1] for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoin.getclosest(ic, times)[0] else: tempin = Ionoin.getclosestsphere(ic, times)[0] # if sp.ndim(tempin)==1: # tempin = tempin[sp.newaxis,:] specin[icn, itn] = tempin[0, :] / npts if acfdisp: Ionoacf = IonoContainer.readh5(str(acfname)) ACFin = sp.zeros( (Nloc, Nt, Ionoacf.Param_List.shape[-1])).astype(Ionoacf.Param_List.dtype) omeg = sp.arange(-sp.ceil((npts + 1) / 2), sp.floor( (npts + 1) / 2)) / ts / npts for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoacf.getclosest(ic, times)[0] else: tempin = Ionoacf.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] ACFin[icn] = tempin # Determine the inverse ACF stuff if len(invacf) == 0: invacfbool = False else: invacfbool = True invfile = maindir.joinpath('ACFInv', '00lags' + invacf + '.h5') Ionoacfinv = IonoContainer.readh5(str(invfile)) ACFinv = sp.zeros((Nloc, Nt, Ionoacfinv.Param_List.shape[-1])).astype( Ionoacfinv.Param_List.dtype) for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoacfinv.getclosest(ic, times)[0] else: tempin = Ionoacfinv.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] ACFinv[icn] = tempin if fitdisp: Ionofit = IonoContainer.readh5(str(ffit)) (omegfit, outspecsfit) = ISRspecmakeout(Ionofit.Param_List, sensdict['fc'], sensdict['fs'], simparams['species'], npts) Ionofit.Param_List = outspecsfit Ionofit.Param_Names = omegfit specfit = sp.zeros((Nloc, Nt, npts)) for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionofit.getclosest(ic, times)[0] else: tempin = Ionofit.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] specfit[icn] = tempin / npts / npts nfig = int(sp.ceil(Nt * Nloc / 3.)) imcount = 0 for i_fig in range(nfig): lines = [None] * 4 labels = [None] * 4 lines_im = [None] * 4 labels_im = [None] * 4 (figmplf, axmat) = plt.subplots(3, 2, figsize=(16, 12), facecolor='w') for ax in axmat: if imcount >= Nt * Nloc: break iloc = int(sp.floor(imcount / Nt)) itime = int(imcount - (iloc * Nt)) maxvec = [] minvec = [] if indisp: # apply ambiguity funciton to spectrum curin = specin[iloc, itime] (tau, acf) = spect2acf(omeg, curin) acf1 = scfft.ifftshift(acf)[:len(pulse)] * len(curin) rcs = acf1[0].real guess_acf = sp.dot(amb_dict['WttMatrix'], acf) guess_acf = guess_acf * rcs / guess_acf[0].real # fit to spectrums maxvec.append(guess_acf.real.max()) maxvec.append(guess_acf.imag.max()) minvec.append(acf1.real.min()) minvec.append(acf1.imag.min()) lines[0] = ax[0].plot(tau1 * 1e6, guess_acf.real, label='Input', linewidth=5)[0] labels[0] = 'Input ACF With Ambiguity Applied' lines_im[0] = ax[1].plot(tau1 * 1e6, guess_acf.imag, label='Input', linewidth=5)[0] labels_im[0] = 'Input ACF With Ambiguity Applied' if fitdisp: curinfit = specfit[iloc, itime] (taufit, acffit) = spect2acf(omegfit, curinfit) rcsfit = curinfit.sum() guess_acffit = sp.dot(amb_dict['WttMatrix'], acffit) guess_acffit = guess_acffit * rcsfit / guess_acffit[0].real lines[1] = ax[0].plot(tau1 * 1e6, guess_acffit.real, label='Input', linewidth=5)[0] labels[1] = 'Fitted ACF' lines_im[1] = ax[1].plot(tau1 * 1e6, guess_acffit.imag, label='Input', linewidth=5)[0] labels_im[1] = 'Fitted ACF' if acfdisp: lines[2] = ax[0].plot(tau1 * 1e6, ACFin[iloc, itime].real, label='Output', linewidth=5)[0] labels[2] = 'Estimated ACF' lines_im[2] = ax[1].plot(tau1 * 1e6, ACFin[iloc, itime].imag, label='Output', linewidth=5)[0] labels_im[2] = 'Estimated ACF' maxvec.append(ACFin[iloc, itime].real.max()) maxvec.append(ACFin[iloc, itime].imag.max()) minvec.append(ACFin[iloc, itime].real.min()) minvec.append(ACFin[iloc, itime].imag.min()) if invacfbool: lines[3] = ax[0].plot(tau1 * 1e6, ACFinv[iloc, itime].real, label='Output', linewidth=5)[0] labels[3] = 'Reconstructed ACF' lines_im[3] = ax[1].plot(tau1 * 1e6, ACFinv[iloc, itime].imag, label='Output', linewidth=5)[0] labels_im[3] = 'Reconstructed ACF' ax[0].set_xlabel(r'$\tau$ in $\mu$s') ax[0].set_ylabel('Amp') ax[0].set_title( 'Real Part' ) # Location {0}, Time {1}'.format(coords[iloc],times[itime])) ax[0].set_ylim(min(minvec), max(maxvec) * 1) ax[0].set_xlim([tau1.min() * 1e6, tau1.max() * 1e6]) ax[1].set_xlabel(r'$\tau$ in $\mu$s') ax[1].set_ylabel('Amp') ax[1].set_title( 'Imag Part' ) # Location {0}, Time {1}'.format(coords[iloc],times[itime])) ax[1].set_ylim(min(minvec), max(maxvec) * 1) ax[1].set_xlim([tau1.min() * 1e6, tau1.max() * 1e6]) imcount = imcount + 1 figmplf.suptitle(suptitle, fontsize=20) if None in labels: labels.remove(None) lines.remove(None) plt.figlegend(lines, labels, loc='lower center', ncol=5, labelspacing=0.) fname = filetemplate + '_{0:0>3}.png'.format(i_fig) plt.savefig(fname, dpi=300) plt.close(figmplf)
def plotspecs(coords, times, configfile, maindir, cartcoordsys=True, indisp=True, acfdisp=True, fitdisp=True, filetemplate='spec', suptitle='Spectrum Comparison'): """ This will create a set of images that compare the input ISR spectrum to the output ISR spectrum from the simulator. Inputs coords - An Nx3 numpy array that holds the coordinates of the desired points. times - A numpy list of times in seconds. configfile - The name of the configuration file used. cartcoordsys - (default True)A bool, if true then the coordinates are given in cartisian if false then it is assumed that the coords are given in sphereical coordinates. specsfilename - (default None) The name of the file holding the input spectrum. acfname - (default None) The name of the file holding the estimated ACFs. filetemplate (default 'spec') This is the beginning string used to save the images. """ sns.set_style("whitegrid") sns.set_context("notebook") maindir = Path(maindir).expanduser() acfname = maindir.joinpath('ACF', '00lags.h5') ffit = maindir.joinpath('Fitted', 'fitteddata.h5') specsfiledir = maindir.joinpath('Spectrums') (sensdict, simparams) = readconfigfile(configfile) simdtype = simparams['dtype'] npts = simparams['numpoints'] * 3.0 amb_dict = simparams['amb_dict'] if sp.ndim(coords) == 1: coords = coords[sp.newaxis, :] Nt = len(times) Nloc = coords.shape[0] sns.set_style("whitegrid") sns.set_context("notebook") if indisp: dirlist = [i.name for i in specsfiledir.glob('*.h5')] timelist = sp.array([float(i.split()[0]) for i in dirlist]) for itn, itime in enumerate(times): filear = sp.argwhere(timelist >= itime) if len(filear) == 0: filenum = len(timelist) - 1 else: filenum = filear[0][0] specsfilename = specsfiledir.joinpath(dirlist[filenum]) Ionoin = IonoContainer.readh5(str(specsfilename)) if itn == 0: specin = sp.zeros( (Nloc, Nt, Ionoin.Param_List.shape[-1])).astype( Ionoin.Param_List.dtype) omeg = Ionoin.Param_Names npts = Ionoin.Param_List.shape[-1] for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoin.getclosest(ic, times)[0] else: tempin = Ionoin.getclosestsphere(ic, times)[0] specin[icn, itn] = tempin[0, :] / npts / npts fs = sensdict['fs'] if acfdisp: Ionoacf = IonoContainer.readh5(str(acfname)) ACFin = sp.zeros( (Nloc, Nt, Ionoacf.Param_List.shape[-1])).astype(Ionoacf.Param_List.dtype) ts = sensdict['t_s'] omeg = sp.arange(-sp.ceil((npts - 1.) / 2.), sp.floor((npts - 1.) / 2.) + 1) / ts / npts for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoacf.getclosest(ic, times)[0] else: tempin = Ionoacf.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] ACFin[icn] = tempin specout = scfft.fftshift(scfft.fft(ACFin, n=npts, axis=-1), axes=-1) if fitdisp: Ionofit = IonoContainer.readh5(str(ffit)) (omegfit, outspecsfit) = ISRspecmakeout(Ionofit.Param_List, sensdict['fc'], sensdict['fs'], simparams['species'], npts) Ionofit.Param_List = outspecsfit Ionofit.Param_Names = omegfit specfit = sp.zeros((Nloc, Nt, npts)) for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionofit.getclosest(ic, times)[0] else: tempin = Ionofit.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] specfit[icn] = tempin / npts / npts nfig = int(sp.ceil(Nt * Nloc / 6.0)) imcount = 0 for i_fig in range(nfig): lines = [None] * 3 labels = [None] * 3 (figmplf, axmat) = plt.subplots(2, 3, figsize=(16, 12), facecolor='w') axvec = axmat.flatten() for iax, ax in enumerate(axvec): if imcount >= Nt * Nloc: break iloc = int(sp.floor(imcount / Nt)) itime = int(imcount - (iloc * Nt)) maxvec = [] if fitdisp: curfitspec = specfit[iloc, itime] rcsfit = curfitspec.sum() (taufit, acffit) = spect2acf(omegfit, curfitspec) guess_acffit = sp.dot(amb_dict['WttMatrix'], acffit) guess_acffit = guess_acffit * rcsfit / guess_acffit[0].real spec_intermfit = scfft.fftshift(scfft.fft(guess_acffit, n=npts)) lines[1] = ax.plot(omeg * 1e-3, spec_intermfit.real, label='Fitted Spectrum', linewidth=5)[0] labels[1] = 'Fitted Spectrum' if indisp: # apply ambiguity function to spectrum curin = specin[iloc, itime] rcs = curin.real.sum() (tau, acf) = spect2acf(omeg, curin) guess_acf = sp.dot(amb_dict['WttMatrix'], acf) guess_acf = guess_acf * rcs / guess_acf[0].real # fit to spectrums spec_interm = scfft.fftshift(scfft.fft(guess_acf, n=npts)) maxvec.append(spec_interm.real.max()) lines[0] = ax.plot(omeg * 1e-3, spec_interm.real, label='Input', linewidth=5)[0] labels[0] = 'Input Spectrum With Ambiguity Applied' if acfdisp: lines[2] = ax.plot(omeg * 1e-3, specout[iloc, itime].real, label='Output', linewidth=5)[0] labels[2] = 'Estimated Spectrum' maxvec.append(specout[iloc, itime].real.max()) ax.set_xlabel('f in kHz') ax.set_ylabel('Amp') ax.set_title('Location {0}, Time {1}'.format( coords[iloc], times[itime])) ax.set_ylim(0.0, max(maxvec) * 1) ax.set_xlim([-fs * 5e-4, fs * 5e-4]) imcount = imcount + 1 figmplf.suptitle(suptitle, fontsize=20) if None in labels: labels.remove(None) lines.remove(None) plt.figlegend(lines, labels, loc='lower center', ncol=5, labelspacing=0.) fname = filetemplate + '_{0:0>3}.png'.format(i_fig) plt.savefig(fname) plt.close(figmplf)
def plotacfs(coords,times,configfile,maindir,cartcoordsys = True, indisp=True,acfdisp= True, fitdisp=True, filetemplate='acf',suptitle = 'ACF Comparison'): """ This will create a set of images that compare the input ISR acf to the output ISR acfs from the simulator. Inputs coords - An Nx3 numpy array that holds the coordinates of the desired points. times - A numpy list of times in seconds. configfile - The name of the configuration file used. cartcoordsys - (default True)A bool, if true then the coordinates are given in cartisian if false then it is assumed that the coords are given in sphereical coordinates. specsfilename - (default None) The name of the file holding the input spectrum. acfname - (default None) The name of the file holding the estimated ACFs. filetemplate (default 'spec') This is the beginning string used to save the images.""" # indisp = specsfilename is not None # acfdisp = acfname is not None acfname = os.path.join(maindir,'ACF','00lags.h5') ffit = os.path.join(maindir,'Fitted','fitteddata.h5') specsfiledir = os.path.join(maindir,'Spectrums') (sensdict,simparams) = readconfigfile(configfile) simdtype = simparams['dtype'] npts = simparams['numpoints']*3.0 amb_dict = simparams['amb_dict'] if sp.ndim(coords)==1: coords = coords[sp.newaxis,:] Nt = len(times) Nloc = coords.shape[0] sns.set_style("whitegrid") sns.set_context("notebook") pulse = simparams['Pulse'] ts = sensdict['t_s'] tau1 = sp.arange(pulse.shape[-1])*ts if indisp: dirlist = os.listdir(specsfiledir) timelist = sp.array([int(i.split()[0]) for i in dirlist]) for itn,itime in enumerate(times): filear = sp.argwhere(timelist>=itime) if len(filear)==0: filenum = len(timelist)-1 else: filenum = filear[0][0] specsfilename = os.path.join(specsfiledir,dirlist[filenum]) Ionoin = IonoContainer.readh5(specsfilename) if itn==0: specin = sp.zeros((Nloc,Nt,Ionoin.Param_List.shape[-1])).astype(Ionoin.Param_List.dtype) omeg = Ionoin.Param_Names npts = Ionoin.Param_List.shape[-1] for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoin.getclosest(ic,times)[0] else: tempin = Ionoin.getclosestsphere(ic,times)[0] # if sp.ndim(tempin)==1: # tempin = tempin[sp.newaxis,:] specin[icn,itn] = tempin[0,:]/npts if acfdisp: Ionoacf = IonoContainer.readh5(acfname) ACFin = sp.zeros((Nloc,Nt,Ionoacf.Param_List.shape[-1])).astype(Ionoacf.Param_List.dtype) omeg = sp.arange(-sp.ceil((npts+1)/2),sp.floor((npts+1)/2))/ts/npts for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoacf.getclosest(ic,times)[0] else: tempin = Ionoacf.getclosestsphere(ic,times)[0] if sp.ndim(tempin)==1: tempin = tempin[sp.newaxis,:] ACFin[icn] = tempin if fitdisp: Ionofit = IonoContainer.readh5(ffit) (omegfit,outspecsfit) =ISRspecmakeout(Ionofit.Param_List,sensdict['fc'],sensdict['fs'],simparams['species'],npts) Ionofit.Param_List= outspecsfit Ionofit.Param_Names = omegfit specfit = sp.zeros((Nloc,Nt,npts)) for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionofit.getclosest(ic,times)[0] else: tempin = Ionofit.getclosestsphere(ic,times)[0] if sp.ndim(tempin)==1: tempin = tempin[sp.newaxis,:] specfit[icn] = tempin/npts/npts nfig = int(sp.ceil(Nt*Nloc/6.0)) imcount = 0 for i_fig in range(nfig): lines = [None]*6 labels = [None]*6 (figmplf, axmat) = plt.subplots(2, 3,figsize=(24, 18), facecolor='w') axvec = axmat.flatten() for iax,ax in enumerate(axvec): if imcount>=Nt*Nloc: break iloc = int(sp.floor(imcount/Nt)) itime = int(imcount-(iloc*Nt)) maxvec = [] minvec = [] if indisp: # apply ambiguity funciton to spectrum curin = specin[iloc,itime] (tau,acf) = spect2acf(omeg,curin) acf1 = scfft.ifftshift(acf)[:len(pulse)] rcs=acf1[0].real guess_acf = sp.dot(amb_dict['WttMatrix'],acf) guess_acf = guess_acf*rcs/guess_acf[0].real # fit to spectrums maxvec.append(guess_acf.real.max()) maxvec.append(guess_acf.imag.max()) minvec.append(acf1.real.min()) minvec.append(acf1.imag.min()) lines[0]= ax.plot(tau1*1e6,guess_acf.real,label='Input',linewidth=5)[0] labels[0] = 'Input ACF With Ambiguity Applied Real' lines[1]= ax.plot(tau1*1e6,guess_acf.imag,label='Input',linewidth=5)[0] labels[1] = 'Input ACF With Ambiguity Applied Imag' if fitdisp: curinfit = specfit[iloc,itime] (taufit,acffit) = spect2acf(omegfit,curinfit) rcsfit=acffit[0].real guess_acffit = sp.dot(amb_dict['WttMatrix'],acffit) guess_acffit = guess_acffit*rcsfit/guess_acffit[0].real lines[2]= ax.plot(tau1*1e6,guess_acffit.real,label='Input',linewidth=5)[0] labels[2] = 'Fitted ACF real' lines[3]= ax.plot(tau1*1e6,guess_acffit.imag,label='Input',linewidth=5)[0] labels[3] = 'Fitted ACF Imag' if acfdisp: lines[4]=ax.plot(tau1*1e6,ACFin[iloc,itime].real,label='Output',linewidth=5)[0] labels[4] = 'Estimated ACF Real' lines[5]=ax.plot(tau1*1e6,ACFin[iloc,itime].imag,label='Output',linewidth=5)[0] labels[5] = 'Estimated ACF Imag' maxvec.append(ACFin[iloc,itime].real.max()) maxvec.append(ACFin[iloc,itime].imag.max()) minvec.append(ACFin[iloc,itime].real.min()) minvec.append(ACFin[iloc,itime].imag.min()) ax.set_xlabel('t in us') ax.set_ylabel('Amp') ax.set_title('Location {0}, Time {1}'.format(coords[iloc],times[itime])) ax.set_ylim(min(minvec),max(maxvec)*1) ax.set_xlim([tau1.min()*1e6,tau1.max()*1e6]) imcount=imcount+1 figmplf.suptitle(suptitle, fontsize=20) if None in labels: labels.remove(None) lines.remove(None) plt.figlegend( lines, labels, loc = 'lower center', ncol=5, labelspacing=0. ) fname= filetemplate+'_{0:0>3}.png'.format(i_fig) plt.savefig(fname) plt.close(figmplf)
def plotspecs( coords, times, configfile, maindir, cartcoordsys=True, indisp=True, acfdisp=True, fitdisp=True, filetemplate="spec", suptitle="Spectrum Comparison", ): """ This will create a set of images that compare the input ISR spectrum to the output ISR spectrum from the simulator. Inputs coords - An Nx3 numpy array that holds the coordinates of the desired points. times - A numpy list of times in seconds. configfile - The name of the configuration file used. cartcoordsys - (default True)A bool, if true then the coordinates are given in cartisian if false then it is assumed that the coords are given in sphereical coordinates. specsfilename - (default None) The name of the file holding the input spectrum. acfname - (default None) The name of the file holding the estimated ACFs. filetemplate (default 'spec') This is the beginning string used to save the images. """ sns.set_style("whitegrid") sns.set_context("notebook") maindir = Path(maindir).expanduser() acfname = maindir.joinpath("ACF", "00lags.h5") ffit = maindir.joinpath("Fitted", "fitteddata.h5") specsfiledir = maindir.joinpath("Spectrums") (sensdict, simparams) = readconfigfile(configfile) simdtype = simparams["dtype"] npts = simparams["numpoints"] * 3.0 amb_dict = simparams["amb_dict"] if sp.ndim(coords) == 1: coords = coords[sp.newaxis, :] Nt = len(times) Nloc = coords.shape[0] sns.set_style("whitegrid") sns.set_context("notebook") if indisp: dirlist = [i.name for i in specsfiledir.glob("*.h5")] timelist = sp.array([float(i.split()[0]) for i in dirlist]) for itn, itime in enumerate(times): filear = sp.argwhere(timelist >= itime) if len(filear) == 0: filenum = len(timelist) - 1 else: filenum = filear[0][0] specsfilename = specsfiledir.joinpath(dirlist[filenum]) Ionoin = IonoContainer.readh5(str(specsfilename)) if itn == 0: specin = sp.zeros((Nloc, Nt, Ionoin.Param_List.shape[-1])).astype(Ionoin.Param_List.dtype) omeg = Ionoin.Param_Names npts = Ionoin.Param_List.shape[-1] for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoin.getclosest(ic, times)[0] else: tempin = Ionoin.getclosestsphere(ic, times)[0] specin[icn, itn] = tempin[0, :] / npts / npts fs = sensdict["fs"] if acfdisp: Ionoacf = IonoContainer.readh5(str(acfname)) ACFin = sp.zeros((Nloc, Nt, Ionoacf.Param_List.shape[-1])).astype(Ionoacf.Param_List.dtype) ts = sensdict["t_s"] omeg = sp.arange(-sp.ceil((npts - 1.0) / 2.0), sp.floor((npts - 1.0) / 2.0) + 1) / ts / npts for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoacf.getclosest(ic, times)[0] else: tempin = Ionoacf.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] ACFin[icn] = tempin specout = scfft.fftshift(scfft.fft(ACFin, n=npts, axis=-1), axes=-1) if fitdisp: Ionofit = IonoContainer.readh5(str(ffit)) (omegfit, outspecsfit) = ISRspecmakeout( Ionofit.Param_List, sensdict["fc"], sensdict["fs"], simparams["species"], npts ) Ionofit.Param_List = outspecsfit Ionofit.Param_Names = omegfit specfit = sp.zeros((Nloc, Nt, npts)) for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionofit.getclosest(ic, times)[0] else: tempin = Ionofit.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] specfit[icn] = tempin / npts / npts nfig = int(sp.ceil(Nt * Nloc / 6.0)) imcount = 0 for i_fig in range(nfig): lines = [None] * 3 labels = [None] * 3 (figmplf, axmat) = plt.subplots(2, 3, figsize=(16, 12), facecolor="w") axvec = axmat.flatten() for iax, ax in enumerate(axvec): if imcount >= Nt * Nloc: break iloc = int(sp.floor(imcount / Nt)) itime = int(imcount - (iloc * Nt)) maxvec = [] if fitdisp: curfitspec = specfit[iloc, itime] rcsfit = curfitspec.sum() (taufit, acffit) = spect2acf(omegfit, curfitspec) guess_acffit = sp.dot(amb_dict["WttMatrix"], acffit) guess_acffit = guess_acffit * rcsfit / guess_acffit[0].real spec_intermfit = scfft.fftshift(scfft.fft(guess_acffit, n=npts)) lines[1] = ax.plot(omeg * 1e-3, spec_intermfit.real, label="Fitted Spectrum", linewidth=5)[0] labels[1] = "Fitted Spectrum" if indisp: # apply ambiguity function to spectrum curin = specin[iloc, itime] rcs = curin.real.sum() (tau, acf) = spect2acf(omeg, curin) guess_acf = sp.dot(amb_dict["WttMatrix"], acf) guess_acf = guess_acf * rcs / guess_acf[0].real # fit to spectrums spec_interm = scfft.fftshift(scfft.fft(guess_acf, n=npts)) maxvec.append(spec_interm.real.max()) lines[0] = ax.plot(omeg * 1e-3, spec_interm.real, label="Input", linewidth=5)[0] labels[0] = "Input Spectrum With Ambiguity Applied" if acfdisp: lines[2] = ax.plot(omeg * 1e-3, specout[iloc, itime].real, label="Output", linewidth=5)[0] labels[2] = "Estimated Spectrum" maxvec.append(specout[iloc, itime].real.max()) ax.set_xlabel("f in kHz") ax.set_ylabel("Amp") ax.set_title("Location {0}, Time {1}".format(coords[iloc], times[itime])) ax.set_ylim(0.0, max(maxvec) * 1) ax.set_xlim([-fs * 5e-4, fs * 5e-4]) imcount = imcount + 1 figmplf.suptitle(suptitle, fontsize=20) if None in labels: labels.remove(None) lines.remove(None) plt.figlegend(lines, labels, loc="lower center", ncol=5, labelspacing=0.0) fname = filetemplate + "_{0:0>3}.png".format(i_fig) plt.savefig(fname) plt.close(figmplf)
def plotacfs( coords, times, configfile, maindir, cartcoordsys=True, indisp=True, acfdisp=True, fitdisp=True, filetemplate="acf", suptitle="ACF Comparison", invacf="", ): """ This will create a set of images that compare the input ISR acf to the output ISR acfs from the simulator. Inputs coords - An Nx3 numpy array that holds the coordinates of the desired points. times - A numpy list of times in seconds. configfile - The name of the configuration file used. cartcoordsys - (default True)A bool, if true then the coordinates are given in cartisian if false then it is assumed that the coords are given in sphereical coordinates. specsfilename - (default None) The name of the file holding the input spectrum. acfname - (default None) The name of the file holding the estimated ACFs. filetemplate (default 'spec') This is the beginning string used to save the images. """ # indisp = specsfilename is not None # acfdisp = acfname is not None maindir = Path(maindir).expanduser() sns.set_style("whitegrid") sns.set_context("notebook") acfname = maindir.joinpath("ACF", "00lags.h5") ffit = maindir.joinpath("Fitted", "fitteddata.h5") specsfiledir = maindir.joinpath("Spectrums") (sensdict, simparams) = readconfigfile(configfile) simdtype = simparams["dtype"] npts = simparams["numpoints"] * 3.0 amb_dict = simparams["amb_dict"] if sp.ndim(coords) == 1: coords = coords[sp.newaxis, :] Nt = len(times) Nloc = coords.shape[0] sns.set_style("whitegrid") sns.set_context("notebook") pulse = simparams["Pulse"] ts = sensdict["t_s"] tau1 = sp.arange(pulse.shape[-1]) * ts if indisp: dirlist = [i.name for i in specsfiledir.glob("*.h5")] timelist = sp.array([float(i.split()[0]) for i in dirlist]) for itn, itime in enumerate(times): filear = sp.argwhere(timelist >= itime) if len(filear) == 0: filenum = len(timelist) - 1 else: filenum = filear[0][0] specsfilename = specsfiledir.joinpath(dirlist[filenum]) Ionoin = IonoContainer.readh5(str(specsfilename)) if itn == 0: specin = sp.zeros((Nloc, Nt, Ionoin.Param_List.shape[-1])).astype(Ionoin.Param_List.dtype) omeg = Ionoin.Param_Names npts = Ionoin.Param_List.shape[-1] for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoin.getclosest(ic, times)[0] else: tempin = Ionoin.getclosestsphere(ic, times)[0] # if sp.ndim(tempin)==1: # tempin = tempin[sp.newaxis,:] specin[icn, itn] = tempin[0, :] / npts if acfdisp: Ionoacf = IonoContainer.readh5(str(acfname)) ACFin = sp.zeros((Nloc, Nt, Ionoacf.Param_List.shape[-1])).astype(Ionoacf.Param_List.dtype) omeg = sp.arange(-sp.ceil((npts + 1) / 2), sp.floor((npts + 1) / 2)) / ts / npts for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoacf.getclosest(ic, times)[0] else: tempin = Ionoacf.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] ACFin[icn] = tempin # Determine the inverse ACF stuff if len(invacf) == 0: invacfbool = False else: invacfbool = True invfile = maindir.joinpath("ACFInv", "00lags" + invacf + ".h5") Ionoacfinv = IonoContainer.readh5(str(invfile)) ACFinv = sp.zeros((Nloc, Nt, Ionoacfinv.Param_List.shape[-1])).astype(Ionoacfinv.Param_List.dtype) for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionoacfinv.getclosest(ic, times)[0] else: tempin = Ionoacfinv.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] ACFinv[icn] = tempin if fitdisp: Ionofit = IonoContainer.readh5(str(ffit)) (omegfit, outspecsfit) = ISRspecmakeout( Ionofit.Param_List, sensdict["fc"], sensdict["fs"], simparams["species"], npts ) Ionofit.Param_List = outspecsfit Ionofit.Param_Names = omegfit specfit = sp.zeros((Nloc, Nt, npts)) for icn, ic in enumerate(coords): if cartcoordsys: tempin = Ionofit.getclosest(ic, times)[0] else: tempin = Ionofit.getclosestsphere(ic, times)[0] if sp.ndim(tempin) == 1: tempin = tempin[sp.newaxis, :] specfit[icn] = tempin / npts / npts nfig = int(sp.ceil(Nt * Nloc / 3.0)) imcount = 0 for i_fig in range(nfig): lines = [None] * 4 labels = [None] * 4 lines_im = [None] * 4 labels_im = [None] * 4 (figmplf, axmat) = plt.subplots(3, 2, figsize=(16, 12), facecolor="w") for ax in axmat: if imcount >= Nt * Nloc: break iloc = int(sp.floor(imcount / Nt)) itime = int(imcount - (iloc * Nt)) maxvec = [] minvec = [] if indisp: # apply ambiguity funciton to spectrum curin = specin[iloc, itime] (tau, acf) = spect2acf(omeg, curin) acf1 = scfft.ifftshift(acf)[: len(pulse)] * len(curin) rcs = acf1[0].real guess_acf = sp.dot(amb_dict["WttMatrix"], acf) guess_acf = guess_acf * rcs / guess_acf[0].real # fit to spectrums maxvec.append(guess_acf.real.max()) maxvec.append(guess_acf.imag.max()) minvec.append(acf1.real.min()) minvec.append(acf1.imag.min()) lines[0] = ax[0].plot(tau1 * 1e6, guess_acf.real, label="Input", linewidth=5)[0] labels[0] = "Input ACF With Ambiguity Applied" lines_im[0] = ax[1].plot(tau1 * 1e6, guess_acf.imag, label="Input", linewidth=5)[0] labels_im[0] = "Input ACF With Ambiguity Applied" if fitdisp: curinfit = specfit[iloc, itime] (taufit, acffit) = spect2acf(omegfit, curinfit) rcsfit = curinfit.sum() guess_acffit = sp.dot(amb_dict["WttMatrix"], acffit) guess_acffit = guess_acffit * rcsfit / guess_acffit[0].real lines[1] = ax[0].plot(tau1 * 1e6, guess_acffit.real, label="Input", linewidth=5)[0] labels[1] = "Fitted ACF" lines_im[1] = ax[1].plot(tau1 * 1e6, guess_acffit.imag, label="Input", linewidth=5)[0] labels_im[1] = "Fitted ACF" if acfdisp: lines[2] = ax[0].plot(tau1 * 1e6, ACFin[iloc, itime].real, label="Output", linewidth=5)[0] labels[2] = "Estimated ACF" lines_im[2] = ax[1].plot(tau1 * 1e6, ACFin[iloc, itime].imag, label="Output", linewidth=5)[0] labels_im[2] = "Estimated ACF" maxvec.append(ACFin[iloc, itime].real.max()) maxvec.append(ACFin[iloc, itime].imag.max()) minvec.append(ACFin[iloc, itime].real.min()) minvec.append(ACFin[iloc, itime].imag.min()) if invacfbool: lines[3] = ax[0].plot(tau1 * 1e6, ACFinv[iloc, itime].real, label="Output", linewidth=5)[0] labels[3] = "Reconstructed ACF" lines_im[3] = ax[1].plot(tau1 * 1e6, ACFinv[iloc, itime].imag, label="Output", linewidth=5)[0] labels_im[3] = "Reconstructed ACF" ax[0].set_xlabel(r"$\tau$ in $\mu$s") ax[0].set_ylabel("Amp") ax[0].set_title("Real Part") # Location {0}, Time {1}'.format(coords[iloc],times[itime])) ax[0].set_ylim(min(minvec), max(maxvec) * 1) ax[0].set_xlim([tau1.min() * 1e6, tau1.max() * 1e6]) ax[1].set_xlabel(r"$\tau$ in $\mu$s") ax[1].set_ylabel("Amp") ax[1].set_title("Imag Part") # Location {0}, Time {1}'.format(coords[iloc],times[itime])) ax[1].set_ylim(min(minvec), max(maxvec) * 1) ax[1].set_xlim([tau1.min() * 1e6, tau1.max() * 1e6]) imcount = imcount + 1 figmplf.suptitle(suptitle, fontsize=20) if None in labels: labels.remove(None) lines.remove(None) plt.figlegend(lines, labels, loc="lower center", ncol=5, labelspacing=0.0) fname = filetemplate + "_{0:0>3}.png".format(i_fig) plt.savefig(fname, dpi=300) plt.close(figmplf)