def get_filter_curve(filter_name): """ Return a Vis/NIR broadband filter TransmissionCurve object Parameters ---------- filter_name : str Notes ----- Acceptable filters can be found be calling get_filter_set() To access the values use TransmissionCurve.lam and TransmissionCurve.val Examples -------- >>> transmission_curve = get_filter_curve("TC_filter_Ks.dat") >>> wavelength = transmission_curve.lam >>> transmission = transmission_curve.val """ fname = find_file(filter_name, silent=True) if fname is None: fname = find_file("TC_filter_" + filter_name + ".dat") if fname is None: raise ValueError("filter not recognised: " + filter_name) return sc.TransmissionCurve(filename=fname)
def yaml_docs(self): sys_descrip = self.cmds["SIM_SYSTEM_DESCRIPTION"] with open(find_file(sys_descrip)) as filename: yaml_files = yaml.load(filename) for element in yaml_files: with open(find_file(yaml_files[element])) as filename: yaml_files[element] = yaml.load(filename) return yaml_files
def test_throws_error_if_file_doesnt_exist(self, throw_error): rc.__currsys__["!SIM.file.error_on_missing_file"] = throw_error filename = 'utils987654.pz' if throw_error: with pytest.raises(ValueError): utils.find_file(filename, rc.__search_path__) else: assert utils.find_file(filename, rc.__search_path__) is None rc.__currsys__["!SIM.file.error_on_missing_file"] = False
def set_mode(self, mode_name): """ Takes the name of an instrument MODE and reads appropriate config file Parameters ---------- mode_name : str The name of a mode config file inside the instrument package Use ``<UserCommands>.list("modes")`` to list the available modes Examples -------- :: >>> import scopesim as sim >>> cmd_micado = sim.UserCommands(instrument="MICADO") >>> cmd_micado.set_mode("MODE_MCAO_WIDE") >>> cmd_micado.list("modes") """ if ".config" not in mode_name: mode_name += ".config" mode_path = find_file(mode_name, [self.inst_pkg_path]) if mode_path is None: raise ValueError("Instrument package isn't set. mode_path is None") elif not os.path.exists(mode_path): raise ValueError("{} mode file was not found in the folder: " "\n {}".format(mode_name, mode_path)) self.update(mode_path) self._find_files()
def install_noise_cube(n=9): """ Install a noise cube in the package directory Parameters ---------- n : int, optional number of layers. Warning ------- Each layer is ~64MB, default is 9 layers (~600MB). If you have less than 1 GB on the drive where your Python installation is. Be careful! """ if sys.version_info.major >= 3: print("WARNING - this process can take up to 10 minutes. Fear not!") hdu = make_noise_cube(n, filename=None) filename = find_file("FPA_noise.fits") hdu.writeto(filename, overwrite=True, checksum=True) print("Saved noise cube with", n, "layers to the package directory:") print(filename) else: print("Sorry, but this only works in Python 3 and above. \ See the ScopeSim FAQs for work-around options")
def yaml_dicts(self): _yaml_dicts = [] for yaml_name in [ "SIM_GENERAL_YAML", "SIM_ATMOSPHERE_YAML", "SIM_TELESCOPE_YAML", "SIM_RELAY_OPTICS_YAML", "SIM_INSTRUMENT_YAML", "SIM_DETECTOR_YAML" ]: yaml_obj = self.cmds[yaml_name] if isinstance(yaml_obj, dict): _yaml_dicts += [yaml_obj] elif isinstance(yaml_obj, str): with open(find_file(yaml_obj)) as f: _yaml_dicts += [dic for dic in yaml.load_all(f)] self._yaml_dicts = _yaml_dicts return self._yaml_dicts
def update(self, new_input): if isinstance(new_input, UserCommands): tmp_cmds = new_input.cmds elif isinstance(new_input, dict): tmp_cmds = new_input elif isinstance(new_input, str): fname = find_file(new_input) if fname is not None: new_input = fname tmp_cmds = cutils.read_config(new_input) else: raise ValueError("Cannot update with type: " + type(new_input)) # Use self.update so that we reject all the invalid keywords for key in tmp_cmds: self[key] = tmp_cmds[key]
def yaml_file_can_be_loaded_into_optical_train(self): # .. todo: get this working on Travis filename = os.path.join(TEST_PATH, "MICADO_SCAO_WIDE_2.yaml") cmds = UserCommands(yamls=[filename]) assert isinstance(cmds, UserCommands) assert isinstance(cmds.yaml_dicts, list) psf_file = cmds.yaml_dicts[1]["effects"][0]["kwargs"]["filename"] if find_file(psf_file) is None: new_file = "test_FVPSF.fits" cmds.yaml_dicts[1]["effects"][0]["kwargs"]["filename"] = new_file opt = OpticalTrain(cmds=cmds) assert isinstance(opt, OpticalTrain) assert isinstance(opt.optics_manager, OpticsManager) assert isinstance( opt.optics_manager.get_all(efs.FieldVaryingPSF)[0], efs.FieldVaryingPSF) assert isinstance(opt.image_plane, ImagePlane) assert opt.image_plane.hdu.header["NAXIS1"] >= 4096 assert isinstance(opt.fov_manager, FOVManager) assert len(opt.fov_manager.fovs) == 64 if PLOTS: for fov in opt.fov_manager.fovs: sky_cnrs, det_cnrs = fov.corners plt.plot(sky_cnrs[0], sky_cnrs[1]) plt.show() r = np.arange(-25, 25) x, y = np.meshgrid(r, r) x = x.flatten() * u.arcsec y = y.flatten() * u.arcsec ref = [0] * len(x) weight = [1] * len(x) spec = sp.SourceSpectrum(sp.Empirical1D, points=[0.5, 3.0] * u.um, lookup_table=[1e3, 1e3] * u.Unit("ph s-1 m-2 um-1")) src = Source(x=x, y=y, ref=ref, weight=weight, spectra=[spec]) opt.observe(src) if PLOTS: plt.imshow(opt.image_plane.image.T, origin="lower", norm=LogNorm()) plt.colorbar() plt.show()
def _get_data(self): """ Get the wavelength and value vectors from the input parameters Returns ------- lam, val : 1D array """ if self.params["lam"] is not None and self.params["val"] is not None: lam = self.params["lam"] val = self.params["val"] # test if it is a skycalc file elif self.params["filename"] is not None: filename = find_file(self.params["filename"]) if ".fits" in filename: hdr = fits.getheader(filename) if any([ "SKYCALC" in hdr[i] for i in range(len(hdr)) if isinstance(hdr[i], str) ]): if self.params["Type"] == "Emission": lam = fits.getdata(filename)["lam"] val = fits.getdata(filename)["flux"] else: lam = fits.getdata(filename)["lam"] val = fits.getdata(filename)["trans"] else: data = fits.getdata("../data/skytable.fits") lam = data[data.columns[0].name] val = data[data.columns[1].name] elif self.params["airmass"] is not None: lam, val = get_sky_spectrum(filename, airmass=self.params["airmass"]) else: data = ioascii.read(filename) lam = data[data.colnames[0]] val = data[data.colnames[1]] else: raise ValueError("Please pass either filename or lam/val keywords") return lam, val
def _update_lam_extremes(self): """Gets the current wave_min and wave_max""" # if SIM_USE_FILTER_LAM is true, then use the filter curve to set the # wavelength boundaries where the filter is < SIM_FILTER_THRESHOLD if self.cmds["SIM_USE_FILTER_LAM"].lower() == "yes": if isinstance(self.cmds["INST_FILTER_TC"], str): tc_filt = sc.TransmissionCurve( filename=find_file(self.cmds['INST_FILTER_TC'])) else: tc_filt = self.cmds["INST_FILTER_TC"] mask = np.where(tc_filt.val > self.cmds["SIM_FILTER_THRESHOLD"])[0] imin = np.max((mask[0] - 1, 0)) imax = np.min((mask[-1] + 1, len(tc_filt.lam) - 1)) lam_min, lam_max = tc_filt.lam[imin], tc_filt.lam[imax] else: lam_min = self.cmds["SIM_LAM_MIN"] lam_max = self.cmds["SIM_LAM_MAX"] return lam_min, lam_max
def test_fails_if_file_doesnt_exist(self): filename = 'utils987654.pz' assert find_file(filename, rc.__search_path__) is None
def test_ignores_none_objects_in_search_path_list(self): filename = 'utils.py' new_filename = find_file(filename, [None] + rc.__search_path__) assert filename in new_filename
def test_passes_if_file_exists(self): filename = 'utils.py' assert find_file(filename, rc.__search_path__)
def test_fails_if_filename_not_a_string(self): # python 3.6: TypeError # python 3.4, 3.5: AttributeError (change in os.path.isabs) with pytest.raises((TypeError, AttributeError)): find_file(1.2, rc.__search_path__)
def _unity_cmds(): return UserCommands(yamls=[find_file("CMD_unity_cmds.yaml")])
def _basic_cmds(): return UserCommands(yamls=[find_file("CMD_mvs_cmds.yaml")])
def _find_files(self, silent=True): """ Checks for files in the package search path ``_find_files`` searches the following directories in this order:: . <i.e. local working dir> SIM_DATA_DIR SIM_INSTRUMENT_PACKAGE SIM_TELESCOPE_PACKAGE FILE_PSF_LOCAL_PATH SIM_SOURCE_PACKAGE Parameters ---------- silent : bool If True, displays any broken paths Returns ------- broken_paths : list """ pkg_paths = [ "./", self.sim_data_dir, self.inst_pkg_path, self.scope_pkg_path, self.psf_pkg_path, self.source_pkg_path ] new_search_path = [pp for pp in pkg_paths if pp is not None] new_search_path += rc.__search_path__ if self["SIM_INSTRUMENT_PACKAGE"] is None: warnings.warn("Instrument package not set.") self["SCOPE_PSF_FILE"] = self._get_psf_path() broken_paths = [] for key in self.cmds: if key == "OBS_OUTPUT_DIR": # need not exist continue keyval = self.cmds[key] # not a string: not a filename if not isinstance(keyval, str): continue # ignore RC keywords that start with FILE_ if key[:4] == "FILE": continue # If string has no extension, assume it's not a file name. # This is a strong assumption, but we need to guard from # looking for "yes", "no", "none", "scao", etc. # TODO Can we have a list of reserved keywords? if "." in keyval and len(keyval.split(".")[-1]) > 1: # look for the file fname = find_file(keyval, path=new_search_path, silent=silent) if fname is None: broken_paths += [keyval] warnings.warn("Keyword " + key + " path doesn't exist: " + keyval) else: self.cmds[key] = fname return broken_paths