Repository: skypyproject/skypy

Issue:
Galaxy property - metallicity
## Description
This function calculates the metallicity of galaxies

## Inputs
 - Galaxy spectral energy distribution

## Outputs
 - Galaxy metallicity

## References


Discussion:

Patch:
diff --git a/skypy/galaxy/spectrum.py b/skypy/galaxy/spectrum.py
index a4913de..e96d234 100644
--- a/skypy/galaxy/spectrum.py
+++ b/skypy/galaxy/spectrum.py
@@ -340,6 +340,8 @@ class KCorrectTemplates(SpectrumTemplates):
         with fits.open(filename) as hdul:
             self.templates = hdul[hdu].data * units.Unit('erg s-1 cm-2 angstrom-1')
             self.wavelength = hdul[11].data * units.Unit('angstrom')
+            self.mremain = hdul[17].data
+            self.mets = hdul[18].data
 
     def stellar_mass(self, coefficients, magnitudes, filter):
         r'''Compute stellar mass from absolute magnitudes in a reference filter.
@@ -367,6 +369,29 @@ class KCorrectTemplates(SpectrumTemplates):
         Mt = self.absolute_magnitudes(coefficients, filter)
         return np.power(10, 0.4*(Mt-magnitudes))
 
+    def metallicity(self, coefficients):
+        r'''Galaxy metallicities from kcorrect templates.
+
+        This function calculates the matallicities of galaxies modelled as a
+        linear combination of the kcorrect templates [1]_.
+
+        Parameters
+        ----------
+        coefficients : (ng, 5) array_like
+            Array of template coefficients.
+
+        Returns
+        -------
+        metallicity : (ng,) array_like
+            Metallicity of each galaxy.
+
+        References
+        ----------
+        .. [1] M. R. Blanton and S. Roweis, 2007, AJ, 125, 2348
+        '''
+
+        return np.sum(coefficients * self.mremain * self.mets) / np.sum(coefficients * self.mremain)
+
 
 kcorrect = KCorrectTemplates(hdu=1)
 kcorrect.__doc__ = '''Galaxy spectra from kcorrect smoothed templates.'''


Test patch:
diff --git a/skypy/galaxy/tests/test_spectrum.py b/skypy/galaxy/tests/test_spectrum.py
index 63c3d4a..942ef1e 100644
--- a/skypy/galaxy/tests/test_spectrum.py
+++ b/skypy/galaxy/tests/test_spectrum.py
@@ -294,3 +294,13 @@ def test_kcorrect_stellar_mass():
     stellar_mass = kcorrect.stellar_mass(coeff, Mb, 'test-filt')
     truth = np.power(10, -0.4*(Mb-Mt))
     np.testing.assert_allclose(stellar_mass, truth)
+
+def test_kcorrect_metallicity():
+
+    from skypy.galaxy.spectrum import kcorrect
+
+    # Each test galaxy is exactly one of the templates
+    coefficients = np.diag(np.ones(5))
+    mets = kcorrect.metallicity(coefficients)
+    truth = np.sum(kcorrect.mremain * kcorrect.mets) / np.sum(kcorrect.mremain)
+    np.testing.assert_allclose(mets, truth)