def test_abund(libsme, abund): """Test abundance behaviour""" libsme.InputAbund(abund) # TODO: What should be the expected behaviour? empty = Abund(monh=0, pattern="empty") empty.update_pattern({"H": 12}) libsme.InputAbund(empty) with pytest.raises(TypeError): libsme.InputAbund(None)
def test_totype_fromtype(): """Test behavior of totype() and fromtype(), which are static methods that return a copy of the input abundance pattern transformed to or from the specified abudnance pattern type. """ # Round trip tests that compare copy=fromtype(totype()) with original. orig = Abund(pattern=pattern_names[0], monh=0)() for type in types: pattern = Abund.totype(orig, type) copy = Abund.fromtype(pattern, type) # Same elements in the same order for full dictionary. assert copy.keys() == orig.keys() # Same elements have abundance defined (!= None). o = OrderedDict((k, v) for k, v in orig.items() if not np.isnan(v)) c = OrderedDict((k, v) for k, v in copy.items() if not np.isnan(v)) assert c.keys() == o.keys() # Logarithmic abundances differ by less than 1e-10. assert all([abs(o[k] - c[k]) < 1e-10 for k in o.keys()]) # Lowercase type yields same result as mixed case type. # type_lc = type.lower() # assert copy == Abund.fromtype(Abund.totype(orig, type_lc), type_lc) # Invalid abundance pattern type raises error. with pytest.raises(ValueError): copy = Abund.totype(orig, "INVALID") with pytest.raises(ValueError): copy = Abund.fromtype(orig, "INVALID")
def test_init_using_pattern_names(): """Test handling of abundance pattern name passed to __init__().""" # Each abundance pattern name yields an Abund object. for pattern_name in pattern_names: assert isinstance(Abund(pattern=pattern_name, monh=0), Abund) # The 'Empty' abundance pattern has a value of None for all elements. abund = Abund(monh=0, pattern="Empty") pattern = abund.get_pattern(raw=True) assert pattern[0] == 0 assert np.all(np.isnan(pattern[1:])) # An invalid abundance pattern name raises an error. with pytest.raises(ValueError): Abund(monh=0, pattern="INVALID")
def test_call_returns_abund_in_odict(): """Test return value, which is an ordered dictionary with element abbreviations as the keys and abundances as the values. """ abund = Abund(pattern=pattern_names[0], monh=0) assert isinstance(abund(), dict) assert tuple(abund().keys()) == abund.elem
def main(fname_out, pattern_name, pattern_type="H=12"): abund = Abund(monh=0, pattern=pattern_name) pattern = abund(type=pattern_type, raw=True) pattern = pattern.astype("<f8") with open(fname_out, "w") as f: pattern.tofile(f) return abund
def make_minimum_structure(): sme = SME_Struct() sme.teff = 5000 sme.logg = 4.4 sme.vmic = 1 sme.vmac = 1 sme.vsini = 1 sme.abund = Abund.solar() sme.linelist = ValdFile("{}/testcase3.lin".format((cwd))) sme.atmo.source = "marcs2012p_t2.0.sav" sme.atmo.method = "grid" sme.wran = [[6436, 6444]] return sme
def create_sme_structure(teff=5770, logg=4.4): examples_dir = os.path.dirname(os.path.realpath(__file__)) in_file = os.path.join(examples_dir, "sun_6440_grid.inp") # Load your existing SME structure or create your own sme = SME.SME_Structure.load(in_file) sme.abund = Abund(0.05, "asplund2009") sme.linelist = ValdFile(os.path.join(examples_dir, "sun.lin")) # Change parameters if your want sme.vrad_flag = "none" sme.cscale_flag = "none" sme.cscale_type = "mask" sme.vsini = 0 sme.vrad = 0 # Set input parameters sme.teff = teff sme.logg = logg # Start SME solver sme = synthesize_spectrum(sme) return sme
def sme_2segments(): cwd = dirname(__file__) sme = SME_Struct() sme.teff = 5000 sme.logg = 4.4 sme.vmic = 1 sme.vmac = 1 sme.vsini = 1 sme.abund = Abund(monh=0, pattern="asplund2009") sme.linelist = ValdFile("{}/testcase1.lin".format((cwd))) sme.atmo.source = "marcs2012p_t2.0.sav" sme.atmo.method = "grid" sme.wran = [[6550, 6560], [6560, 6574]] sme.vrad_flag = "none" sme.cscale_flag = "none" return sme
def test_update_pattern(): """Test behavior of update_pattern(), which modifies values in _pattern for the specified element(s). """ # Update for one element yields float with the specified value. abund = Abund(pattern="Empty", monh=0) assert np.isnan(abund["Fe"]) abund.update_pattern({"Fe": "3.14"}) assert isinstance(abund["Fe"], float) assert abund["Fe"] == 3.14 # Update for two elements yields floats with the specified values. abund.update_pattern({"C": 8.4, "F": 5}) assert isinstance(abund["C"], float) assert isinstance(abund["F"], float) assert abund["C"] == 8.4 assert abund["F"] == 5.0
def test_monh_property_set_and_get(): """Test setting and getting monh property. Set converts input to float.""" # Input str convertable to float yields a float with the specified value. abund = Abund(pattern=pattern_names[0], monh="-6e-1") assert isinstance(abund.monh, float) assert abund.monh == -0.6 # Input int yields a float with the specified value. abund.monh = -2 assert isinstance(abund.monh, float) assert abund.monh == -2.0 # Input float yields a float with the specified value. abund.monh = 0.3 assert isinstance(abund.monh, float) assert abund.monh == 0.3 # Input str that cannot be converted to float raises an error. with pytest.raises(ValueError): abund = Abund(pattern=pattern_names[0], monh="ABC") # Input that is not a string or a number raises an error. with pytest.raises(TypeError): abund.monh = []
# Define the location of all your files # this will put everything into the example dir target = "sun" examples_dir = join(dirname(realpath(__file__)), "..") in_file = join(examples_dir, "sun_6440_test.inp") out_file = join(examples_dir, f"{target}.sme") plot_file = join(examples_dir, f"{target}.html") log_file = join(examples_dir, f"{target}.log") # Start the logging to the file util.start_logging(log_file) # Load your existing SME structure or create your own sme = SME.SME_Structure.load(in_file) sme.abund = Abund(0, "asplund2009") sme.linelist = ValdFile(join(examples_dir, "sun.lin")) sme.nmu = 7 sme.vrad = 0 sme.cscale = None sme.vrad_flag = "none" sme.cscale_flag = "none" sme.cscale_type = "match" sme.atmo.source = "marcs2012.sav" # save_as_idl(sme, "speedtest.inp") # Run it once to load the atmosphere start = time.time() sme = synthesize_spectrum(sme) end = time.time()
sme.cscale = 1 sme.vrad_flag = "whole" sme.vrad = 31.82 fitparameters = ["logg", "teff", "monh"] # Start SME solver sme = synthesize_spectrum(sme) # solver = SME_Solver(filename=f"test2.sme") # sme = solver.solve(sme, fitparameters) try: # Calculate stellar age based on abundances solar = Abund.solar() y, mg = sme.abund["Y"], sme.abund["Mg"] sy, smg = ( sme.fitresults.punc["Y abund"], sme.fitresults.punc["Mg abund"], ) x = y - mg - (solar["Y"] - solar["Mg"]) sx = np.sqrt(sy**2 + smg**2) # Values from paper a = 0.175 sa = 0.011 b = -0.0404 sb = 0.0019 age = (x - a) / b sigma_age = 1 / b * np.sqrt(sx**2 + sa**2 + ((x - a) / b)**2 * sb**2)
np.nan_to_num(1 / np.sqrt(np.abs(spec)) ** 2, nan=1) for spec in sme.spec ] # sme.mask = get_mask_from_neural_network(sme) # sme.mask = sme.mask_values["line"] # for i in range(sme.nseg): # sme.mask[i][sme.mask[i] == 0] = sme.mask_values["bad"] # Add telluric data (without rayleigh scattering) ftapas = [np.interp(w, wtapas, ftapas) for w in wave] sme.telluric = Iliffe_vector(values=ftapas) # Get first guess from literature values sme.teff = star["t_eff"].to_value("K") if "t_eff" in star else 6000 sme.logg = star["logg"].to_value(1) if "logg" in star else 4 monh = star["metallicity"].to_value(1) if "metallicity" in star else 0 sme.abund = Abund(monh, "asplund2009") sme.vmic = ( star["velocity_turbulence"].to_value("km/s") if "velocity_turbulence" in star else 3 ) # Test this sme.vmic = 0 sme.vsini = 0 # load the linelist sme.linelist = ValdFile(vald_file) # Set the atmosphere grid sme.atmo.source = "marcs2014.sav" sme.atmo.geom = "PP"
def abund(): return Abund(monh=0, pattern="Asplund2009")
def test_getitem_returns_abund_values(): """Test getitem method, which return computed abundance values for the specified element or list of elements. """ abund = Abund(pattern=pattern_names[0], monh=0) assert abund["H"] == 12
def test_init_with_too_few_args(): """Test that __init__ raise an error if too few arguments are passed.""" Abund() Abund(monh=0) Abund(pattern="asplund2009") Abund(type="H=12")
def test_pattern_property_set_and_get(): """Test setting and getting pattern property. Set is not allowed.""" # Raise error is user tries to set pattern abund = Abund(pattern="Empty", monh=0) with pytest.raises(AttributeError): abund.pattern = 0.0