Exemplo n.º 1
0
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(0, "Empty")
    with pytest.raises(AttributeError):
        abund.pattern = 0.0
Exemplo n.º 2
0
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(0, pattern_names[0]).pattern
    for type in types:
        copy = Abund.fromtype(Abund.totype(orig, type), 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 v)
        c = OrderedDict((k, v) for k, v in copy.items() if 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])
        # 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')
Exemplo n.º 3
0
def test_init_with_too_few_args():
    """Test that __init__ raise an error if too few arguments are passed.
    """
    # Passing zero arguments to __init__() raises an error.
    with pytest.raises(TypeError):
        Abund()

    # Passing one argument to __init__() raises an error.
    with pytest.raises(TypeError):
        Abund(0)
Exemplo n.º 4
0
def test_abund(libsme, abund):
    """ Test abundance behaviour """
    libsme.InputAbund(abund)

    # TODO: What should be the expected behaviour?
    empty = Abund(0, "empty")
    empty.update_pattern({"H": 12})
    libsme.InputAbund(empty)

    with pytest.raises(TypeError):
        libsme.InputAbund(None)
Exemplo n.º 5
0
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(0, pattern_name), Abund)

    # The 'Empty' abundance pattern has a value of None for all elements.
    abund = Abund(0, "Empty")
    assert np.all(np.isnan(abund.pattern))

    # An invalid abundance pattern name raises an error.
    with pytest.raises(ValueError):
        Abund(0, "INVALID")
Exemplo n.º 6
0
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(0, pattern_names[0])
    assert isinstance(abund(), dict)
    assert tuple(abund().keys()) == abund.elem
Exemplo n.º 7
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("-6e-1", pattern_names[0])
    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("ABC", pattern_names[0])

    # Input that is not a string or a number raises an error.
    with pytest.raises(TypeError):
        abund.monh = []
Exemplo n.º 8
0
 def parse_abund(self, lines):
     """Parse VALD abundance lines from a VALD line data file.
     """
     abstr = ''.join([''.join(line.split()) for line in lines])
     words = [w[1:-1] for w in abstr.split(',')]
     if len(words) != 100 or words[99] != 'END':
         raise ValdFileError(f'error parsing abundances: {abstr}')
     values = [w.split(':') for w in words[:-1]]
     values = OrderedDict([(el, float(ab)) for el, ab in values])
     monh = 0.0
     return Abund(monh, values, 'sme')
Exemplo n.º 9
0
    def _parse_abund(self, lines):
        """Parse abundances from an ATLAS9 atmosphere file.

        Check 'ABUNDANCE SCALE' label. Parse abundance scale factor.
        Join remaining text into string. Split on 'ABUNDANCE CHANGE' label.
        Split again on white space. Even index words are atomic number.
        Odd index words are abundances relative to total number of nuclei.
        Leave H abundances linear. Convert H3 abundance to log10.
        Leave all other abundances log10.
        """
        try:
            assert lines[0][0:16] == 'ABUNDANCE SCALE '
            monh = log10(float(lines[0][16:25]))
            abstr = lines[0][25:] + ''.join(lines[1:])
            words = ''.join(abstr.split('ABUNDANCE CHANGE')).split()
            assert [int(s) for s in words[0::2]] == list(range(1, 100))
            abund = [float(s) for s in words[1::2]]
            abund[1] = log10(abund[1])
            elements = Abund(0, 'Empty').elements
            values = {el: ab for el, ab in zip(elements, abund)}
            return Abund(monh, values, 'sme')
        except (AssertionError, ValueError):
            raise AtmoFileError(f'error parsing abund: {self._path}')
Exemplo n.º 10
0
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(0, "Empty")
    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
Exemplo n.º 11
0
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(0, 'Empty')
    assert not abund.pattern['Fe']
    abund.update_pattern({'Fe': '3.14'})
    assert isinstance(abund.pattern['Fe'], float)
    assert abund.pattern['Fe'] == 3.14

    # Update for two elements yields floats with the specified values.
    abund.update_pattern({'C': 8.4, 'F': 5})
    assert isinstance(abund.pattern['C'], float)
    assert isinstance(abund.pattern['F'], float)
    assert abund.pattern['C'] == 8.4
    assert abund.pattern['F'] == 5.0
Exemplo n.º 12
0
def test_abund():
    """Code coverage tests for Abund() class and methods.
    """
    abund = Abund(0, pattern_names[0])
    for name in pattern_names:
        a1 = Abund(0, name)
        a2 = Abund(0, name.lower())
        a3 = Abund(-0.1, Abund(0.1, name).abund, 'H=12')
        a1.__repr__()
        a2.__str__()
        abund.compare(a3)
        a3.compare(abund)
        assert len(a1) == len(a1.elements) == 99
        assert a1 is not a2
        assert a1 == a2
        assert tuple(a1.keys()) == a1.elements
        assert list(a1.values()) == [a1[k] for k, v in a1.items()]
        if a2['Fe'] is not None:
            for norm in norms:
                a1 == to_H12(a1.normalized(norm), norm)
                a1 == to_H12(a1.normalized(norm, prune=True), norm)
            a2.pattern['Fe'] = a1.pattern['Fe'] + 0.999e-4
            assert a1['Fe'] != a2['Fe']
            assert a1 == a2
            assert not a1 != a2
            a2.pattern['Fe'] = a1.pattern['Fe'] + 1.001e-4
            assert a1 != a2
            a2.pattern['Fe'] = None
            assert a1 != a2
            assert a1 != 'wrong object type'
            assert all(
                [abs(a1[k] - a3[k]) < 1e-8 for k in a1.elements if a1[k]])
            assert a1 != a3
    with raises(AbundError, match='set monh and pattern separately'):
        abund['C'] = 8.2
    with raises(ValueError, match='could not convert string'):
        abund.monh = 'text'
    with raises(AbundError, match='must be an AbundPattern object'):
        abund.pattern = {'H': 12, 'He': 11, 'Li': 1}
    with raises(AbundError, match='unknown element key'):
        abund['Water']
    with raises(AbundError, match='unknown element key'):
        abund.pattern._pattern['Water'] = 5
        abund.abund()
Exemplo n.º 13
0
    fitparameters = ["teff", "logg", "monh"]
    # sme.vrad_flag = "whole"
    # sme.cscale_flag = "constant"
    # sme.nlte.set_nlte("Ca")
    # sme.nlte.remove_nlte("Ca")
    # sme.nlte.remove_nlte("Na")
    # sme.nlte.remove_nlte("Ba")

    # Start SME solver
    # sme = synthesize_spectrum(sme, segments=[0])
    sme = solve(sme, fitparameters, filename=f"{target}.npz")

    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)
        sigma_age = abs(sigma_age)
        logging.info("Age       \t%.3f +- %.3f Gyr", age, sigma_age)
Exemplo n.º 14
0
def abund():
    return Abund(0, "Asplund2009")
Exemplo n.º 15
0
def test_getitem_returns_abund_values():
    """Test getitem method, which return computed abundance values for
    the specified element or list of elements.
    """
    abund = Abund(0, pattern_names[0])
    assert abund["H"] == 12