def _transfer_single(self, bl_index, f_index, lmax): if self._nside != hputil.nside_for_lmax(lmax, accuracy_boost=self.accuracy_boost): self._init_trans(hputil.nside_for_lmax(lmax, accuracy_boost=self.accuracy_boost)) cvis = self._beam_map_single(bl_index, f_index) beam_cart = hpproj.cartesian_proj(cvis[0], self.cart_projector) # Perform the inverse Fourier transform along phi direction to get the transfer matrix btrans = np.fft.fft(beam_cart, axis=1) / self.phi_size # m = 0 is at left return [ btrans ]
def _transfer_single(self, bl_index, f_index, lmax): if self._nside != hputil.nside_for_lmax( lmax, accuracy_boost=self.accuracy_boost): self._init_trans( hputil.nside_for_lmax(lmax, accuracy_boost=self.accuracy_boost)) cvis = self._beam_map_single(bl_index, f_index) beam_cart = hpproj.cartesian_proj(cvis[0], self.cart_projector) # Perform the inverse Fourier transform along phi direction to get the transfer matrix btrans = np.fft.fft(beam_cart, axis=1) / self.phi_size # m = 0 is at left return [btrans]
def simulate(beamtransfer, outdir, tsname, maps=[], ndays=None, resolution=0, add_noise=True, seed=None, **kwargs): """Create a simulated timestream and save it to disk. Parameters ---------- beamtransfer : fmmode.core.beamtransfer.BeamTransfer BeamTransfer object containing the analysis products. outdir : directoryname Directory that we will save the timestream into. maps : list List of map filenames. The sum of these form the simulated sky. ndays : int, optional Number of days of observation. Setting `ndays = None` (default) uses the default stored in the telescope object; `ndays = 0`, assumes the observation time is infinite so that the noise is zero. resolution : scalar, optional Approximate time resolution in seconds. Setting `resolution = 0` (default) calculates the value from the mmax. add_noise : bool, optional Weather to add random noise to the simulated visibilities. Default True. Returns ------- timestream : Timestream """ # Create timestream object tstream = Timestream(outdir, tsname, beamtransfer) completed_file = tstream._tsdir + '/COMPLETED_TIMESTREAM' if os.path.exists(completed_file): if mpiutil.rank0: print "******* timestream-files already generated ********" mpiutil.barrier() return tstream # Make directory if required try: os.makedirs(tstream._tsdir) except OSError: # directory exists pass if mpiutil.rank0: # if not os.path.exists(tstream._tsdir): # os.makedirs(tstream._tsdir) tstream.save() ## Read in telescope system bt = beamtransfer tel = bt.telescope lmax = tel.lmax mmax = tel.mmax nfreq = tel.nfreq nbl = tel.nbase npol = tel.num_pol_sky # If ndays is not set use the default value. if ndays is None: ndays = tel.ndays # Calculate the number of timesamples from the resolution if resolution == 0: # Set the minimum resolution required for the sky. ntime = 2*mmax+1 else: # Set the cl ntime = int(np.round(24 * 3600.0 / resolution)) indices = list(itertools.product(np.arange(nfreq), np.arange(npol))) lind, sind, eind = mpiutil.split_local(nfreq * npol) # local section of the Tm array theta_size = tel.theta_size phi_size = tel.phi_size Tm = np.zeros((lind, theta_size, phi_size), dtype=np.complex128) for ind, (f_ind, p_ind) in enumerate(indices[sind:eind]): hp_map = None for idx, mapfile in enumerate(maps): with h5py.File(mapfile, 'r') as f: if idx == 0: hp_map = f['map'][f_ind, p_ind, :] else: hp_map += f['map'][f_ind, p_ind, :] if hp_map is not None: cart_map = hpproj.cartesian_proj(hp_map, tel.cart_projector) # Calculate the Tm's for the local sections Tm[ind] = np.fft.ifft(cart_map, axis=1) # / phi_size # m = 0 is at left Tm = MPIArray.wrap(Tm, axis=0) # redistribute along different m Tm = Tm.redistribute(axis=2) Tm = Tm.reshape((nfreq, npol, theta_size, None)) Tm = Tm.reshape((nfreq, npol*theta_size, None)) ms = np.concatenate([np.arange(0, mmax+1), np.arange(-mmax, 0)]) lm, sm, em = mpiutil.split_local(phi_size) # local section of mmode # mmode = np.zeros((lm, nbl, nfreq), dtype=np.complex128) mmode = np.zeros((lm, nfreq, nbl), dtype=np.complex128) for ind, mi in enumerate(ms[sm:em]): mmode[ind] = bt.project_vector_sky_to_telescope(mi, Tm[:, :, ind].view(np.ndarray)) mmode = MPIArray.wrap(mmode, axis=0) mmode = mmode.redistribute(axis=2) # distribute along bl # add noise if required if add_noise: lbl, sbl, ebl = mpiutil.split_local(nbl) # Fetch the noise powerspectrum noise_ps = tel.noisepower(np.arange(sbl, ebl)[:, np.newaxis], np.arange(nfreq)[np.newaxis, :], ndays=ndays).reshape(lbl, nfreq).T[np.newaxis, :, :] # Seed random number generator to give consistent noise if seed is not None: # Must include rank such that we don't have massive power deficit from correlated noise np.random.seed(seed + mpiutil.rank) # Create and weight complex noise coefficients noise_mode = (np.array([1.0, 1.0J]) * np.random.standard_normal(mmode.shape + (2,))).sum(axis=-1) noise_mode *= (noise_ps / 2.0)**0.5 mmode += noise_mode del noise_mode # Reset RNG if seed is not None: np.random.seed() # The time samples the visibility is calculated at tphi = np.linspace(0, 2*np.pi, ntime, endpoint=False) # inverse FFT to get timestream vis_stream = np.fft.ifft(mmode, axis=0) * ntime vis_stream = MPIArray.wrap(vis_stream, axis=2) # save vis_stream to file vis_h5 = memh5.MemGroup(distributed=True) vis_h5.create_dataset('/timestream', data=vis_stream) vis_h5.create_dataset('/phi', data=tphi) # Telescope layout data vis_h5.create_dataset('/feedmap', data=tel.feedmap) vis_h5.create_dataset('/feedconj', data=tel.feedconj) vis_h5.create_dataset('/feedmask', data=tel.feedmask) vis_h5.create_dataset('/uniquepairs', data=tel.uniquepairs) vis_h5.create_dataset('/baselines', data=tel.baselines) # Telescope frequencies vis_h5.create_dataset('/frequencies', data=tel.frequencies) # Write metadata vis_h5.attrs['beamtransfer_path'] = os.path.abspath(bt.directory) vis_h5.attrs['ntime'] = ntime # save to file vis_h5.to_hdf5(tstream._tsfile) if mpiutil.rank0: # Make file marker that the m's have been correctly generated: open(completed_file, 'a').close() mpiutil.barrier() return tstream
def simulate(beamtransfer, outdir, tsname, maps=[], ndays=None, resolution=0, add_noise=True, seed=None, **kwargs): """Create a simulated timestream and save it to disk. Parameters ---------- beamtransfer : fmmode.core.beamtransfer.BeamTransfer BeamTransfer object containing the analysis products. outdir : directoryname Directory that we will save the timestream into. maps : list List of map filenames. The sum of these form the simulated sky. ndays : int, optional Number of days of observation. Setting `ndays = None` (default) uses the default stored in the telescope object; `ndays = 0`, assumes the observation time is infinite so that the noise is zero. resolution : scalar, optional Approximate time resolution in seconds. Setting `resolution = 0` (default) calculates the value from the mmax. add_noise : bool, optional Weather to add random noise to the simulated visibilities. Default True. Returns ------- timestream : Timestream """ # Create timestream object tstream = Timestream(outdir, tsname, beamtransfer) completed_file = tstream._tsdir + '/COMPLETED_TIMESTREAM' if os.path.exists(completed_file): if mpiutil.rank0: print "******* timestream-files already generated ********" mpiutil.barrier() return tstream # Make directory if required try: os.makedirs(tstream._tsdir) except OSError: # directory exists pass if mpiutil.rank0: # if not os.path.exists(tstream._tsdir): # os.makedirs(tstream._tsdir) tstream.save() ## Read in telescope system bt = beamtransfer tel = bt.telescope lmax = tel.lmax mmax = tel.mmax nfreq = tel.nfreq nbl = tel.nbase npol = tel.num_pol_sky # If ndays is not set use the default value. if ndays is None: ndays = tel.ndays # Calculate the number of timesamples from the resolution if resolution == 0: # Set the minimum resolution required for the sky. ntime = 2 * mmax + 1 else: # Set the cl ntime = int(np.round(24 * 3600.0 / resolution)) indices = list(itertools.product(np.arange(nfreq), np.arange(npol))) lind, sind, eind = mpiutil.split_local(nfreq * npol) # local section of the Tm array theta_size = tel.theta_size phi_size = tel.phi_size Tm = np.zeros((lind, theta_size, phi_size), dtype=np.complex128) for ind, (f_ind, p_ind) in enumerate(indices[sind:eind]): hp_map = None for idx, mapfile in enumerate(maps): with h5py.File(mapfile, 'r') as f: if idx == 0: hp_map = f['map'][f_ind, p_ind, :] else: hp_map += f['map'][f_ind, p_ind, :] if hp_map is not None: cart_map = hpproj.cartesian_proj(hp_map, tel.cart_projector) # Calculate the Tm's for the local sections Tm[ind] = np.fft.ifft(cart_map, axis=1) # / phi_size # m = 0 is at left Tm = MPIArray.wrap(Tm, axis=0) # redistribute along different m Tm = Tm.redistribute(axis=2) Tm = Tm.reshape((nfreq, npol, theta_size, None)) Tm = Tm.reshape((nfreq, npol * theta_size, None)) ms = np.concatenate([np.arange(0, mmax + 1), np.arange(-mmax, 0)]) lm, sm, em = mpiutil.split_local(phi_size) # local section of mmode # mmode = np.zeros((lm, nbl, nfreq), dtype=np.complex128) mmode = np.zeros((lm, nfreq, nbl), dtype=np.complex128) for ind, mi in enumerate(ms[sm:em]): mmode[ind] = bt.project_vector_sky_to_telescope( mi, Tm[:, :, ind].view(np.ndarray)) mmode = MPIArray.wrap(mmode, axis=0) mmode = mmode.redistribute(axis=2) # distribute along bl # add noise if required if add_noise: lbl, sbl, ebl = mpiutil.split_local(nbl) # Fetch the noise powerspectrum noise_ps = tel.noisepower(np.arange(sbl, ebl)[:, np.newaxis], np.arange(nfreq)[np.newaxis, :], ndays=ndays).reshape( lbl, nfreq).T[np.newaxis, :, :] # Seed random number generator to give consistent noise if seed is not None: # Must include rank such that we don't have massive power deficit from correlated noise np.random.seed(seed + mpiutil.rank) # Create and weight complex noise coefficients noise_mode = (np.array([1.0, 1.0J]) * np.random.standard_normal(mmode.shape + (2, ))).sum(axis=-1) noise_mode *= (noise_ps / 2.0)**0.5 mmode += noise_mode del noise_mode # Reset RNG if seed is not None: np.random.seed() # The time samples the visibility is calculated at tphi = np.linspace(0, 2 * np.pi, ntime, endpoint=False) # inverse FFT to get timestream vis_stream = np.fft.ifft(mmode, axis=0) * ntime vis_stream = MPIArray.wrap(vis_stream, axis=2) # save vis_stream to file vis_h5 = memh5.MemGroup(distributed=True) vis_h5.create_dataset('/timestream', data=vis_stream) vis_h5.create_dataset('/phi', data=tphi) # Telescope layout data vis_h5.create_dataset('/feedmap', data=tel.feedmap) vis_h5.create_dataset('/feedconj', data=tel.feedconj) vis_h5.create_dataset('/feedmask', data=tel.feedmask) vis_h5.create_dataset('/uniquepairs', data=tel.uniquepairs) vis_h5.create_dataset('/baselines', data=tel.baselines) # Telescope frequencies vis_h5.create_dataset('/frequencies', data=tel.frequencies) # Write metadata vis_h5.attrs['beamtransfer_path'] = os.path.abspath(bt.directory) vis_h5.attrs['ntime'] = ntime # save to file vis_h5.to_hdf5(tstream._tsfile) if mpiutil.rank0: # Make file marker that the m's have been correctly generated: open(completed_file, 'a').close() mpiutil.barrier() return tstream