コード例 #1
0
    def get_absmag(
        self, filter_name: str
    ) -> Union[Tuple[float, Optional[float]], Tuple[np.ndarray,
                                                    Optional[np.ndarray]]]:
        """
        Function for calculating the absolute magnitudes of the object from the apparent
        magnitudes and distance. The errors on the apparent magnitude and distance are propagated
        into an error on the absolute magnitude.

        Parameters
        ----------
        filter_name : str
            Filter name.

        Returns
        -------
        float, np.ndarray
            Absolute magnitude (mag)
        float, np.ndarray
            Error (mag).
        """

        with h5py.File(self.database, 'r') as h5_file:
            obj_distance = np.asarray(
                h5_file[f'objects/{self.object_name}/distance'])

            if filter_name in h5_file[f'objects/{self.object_name}']:
                obj_phot = np.asarray(
                    h5_file[f'objects/{self.object_name}/{filter_name}'])

            else:
                raise ValueError(
                    f'There is no photometric data of \'{self.object_name}\' '
                    f'available with the {filter_name}.')

        if obj_phot.ndim == 1:
            abs_mag = phot_util.apparent_to_absolute(
                (obj_phot[0], obj_phot[1]), (obj_distance[0], obj_distance[1]))

        elif obj_phot.ndim == 2:
            abs_mag = phot_util.apparent_to_absolute(
                (obj_phot[0, :], obj_phot[1, :]),
                (obj_distance[0], obj_distance[1]))

        return abs_mag
コード例 #2
0
    def get_absmag(self,
                   filter_name):
        """
        Parameters
        ----------
        filter_name : str
            Filter name.

        Returns
        -------
        float, float
            Absolute magnitude (mag), magnitude error (error).
        """

        h5_file = h5py.File(self.database, 'r')
        obj_distance = np.asarray(h5_file['objects/'+self.object_name+'/distance'])
        obj_phot = np.asarray(h5_file['objects/'+self.object_name+'/'+filter_name])
        h5_file.close()

        abs_mag = phot_util.apparent_to_absolute(obj_phot[0], obj_distance)

        return abs_mag, obj_phot[1]
コード例 #3
0
ファイル: read_color.py プロジェクト: tomasstolker/species
    def get_color_magnitude(self,
                            object_type: Optional[str] = None
                            ) -> box.ColorMagBox:
        """
        Function for extracting color-magnitude data from the selected
        library.

        Parameters
        ----------
        object_type : str, None
            Object type for which the colors and magnitudes are
            extracted. Either field dwarfs ('field') or
            young/low-gravity objects ('young'). All objects are
            selected if set to ``None``.

        Returns
        -------
        species.core.box.ColorMagBox
            Box with the colors and magnitudes.
        """

        if self.lib_type == "phot_lib":
            with h5py.File(self.database, "r") as h5_file:
                sptype = np.asarray(
                    h5_file[f"photometry/{self.library}/sptype"])
                parallax = np.asarray(
                    h5_file[f"photometry/{self.library}/parallax"])
                parallax_error = np.asarray(
                    h5_file[f"photometry/{self.library}/parallax_error"])
                flag = np.asarray(h5_file[f"photometry/{self.library}/flag"])
                obj_names = np.asarray(
                    h5_file[f"photometry/{self.library}/name"])

                for i in range(sptype.shape[0]):
                    if isinstance(sptype[i], bytes):
                        sptype[i] = sptype[i].decode("utf-8")

                    if isinstance(flag[i], bytes):
                        flag[i] = flag[i].decode("utf-8")

                    if isinstance(obj_names[i], bytes):
                        obj_names[i] = obj_names[i].decode("utf-8")

            if object_type is None:
                indices = np.arange(0, np.size(sptype), 1)

            elif object_type == "field":
                indices = np.where(flag == "null")[0]

            elif object_type == "young":
                indices = []

                for j, object_flag in enumerate(flag):
                    if "young" in object_flag:
                        indices.append(j)

                    elif "lowg" in object_flag:
                        indices.append(j)

                indices = np.array(indices)

            if indices.size > 0:
                with h5py.File(self.database, "r") as h5_file:
                    mag1 = np.asarray(h5_file[
                        f"photometry/{self.library}/{self.filters_color[0]}"])
                    mag2 = np.asarray(h5_file[
                        f"photometry/{self.library}/{self.filters_color[1]}"])

            else:
                raise ValueError(
                    f"There is not data available from '{self.library}' for "
                    f"'{object_type}' type objects with the chosen filters.")

            color = mag1 - mag2

            distance = phot_util.parallax_to_distance(
                (parallax, parallax_error))

            if self.filter_mag == self.filters_color[0]:
                mag, _ = phot_util.apparent_to_absolute(
                    (mag1, None), (distance[0], distance[1]))

            elif self.filter_mag == self.filters_color[1]:
                mag, _ = phot_util.apparent_to_absolute(
                    (mag2, None), (distance[0], distance[1]))

            color = color[indices]
            mag = mag[indices]
            sptype = sptype[indices]
            obj_names = obj_names[indices]

            indices = []
            for i in range(color.size):
                if not np.isnan(color[i]) and not np.isnan(mag[i]):
                    indices.append(i)

            colormag_box = box.create_box(
                boxtype="colormag",
                library=self.library,
                object_type=object_type,
                filters_color=self.filters_color,
                filter_mag=self.filter_mag,
                color=color[indices],
                magnitude=mag[indices],
                sptype=sptype[indices],
                names=obj_names[indices],
            )

        elif self.lib_type == "spec_lib":
            read_spec_0 = read_spectrum.ReadSpectrum(
                spec_library=self.library, filter_name=self.filters_color[0])

            read_spec_1 = read_spectrum.ReadSpectrum(
                spec_library=self.library, filter_name=self.filters_color[1])

            read_spec_2 = read_spectrum.ReadSpectrum(
                spec_library=self.library, filter_name=self.filter_mag)

            phot_box_0 = read_spec_0.get_magnitude(sptypes=None)
            phot_box_1 = read_spec_1.get_magnitude(sptypes=None)
            phot_box_2 = read_spec_2.get_magnitude(sptypes=None)

            colormag_box = box.create_box(
                boxtype="colormag",
                library=self.library,
                object_type=object_type,
                filters_color=self.filters_color,
                filter_mag=self.filter_mag,
                color=phot_box_0.app_mag[:, 0] - phot_box_1.app_mag[:, 0],
                magnitude=phot_box_2.abs_mag[:, 0],
                sptype=phot_box_0.sptype,
                names=None,
            )

        return colormag_box
コード例 #4
0
    def flux_to_magnitude(
        self,
        flux: float,
        error: Optional[Union[float, np.ndarray]] = None,
        parallax: Optional[Union[Tuple[float, Optional[float]],
                                 Tuple[np.ndarray,
                                       Optional[np.ndarray]]]] = None,
        distance: Optional[Union[Tuple[float, Optional[float]],
                                 Tuple[np.ndarray,
                                       Optional[np.ndarray]]]] = None,
    ) -> Tuple[Union[Tuple[float, Optional[float]], Tuple[
            np.ndarray, Optional[np.ndarray]]], Union[Tuple[
                float, Optional[float]], Tuple[np.ndarray,
                                               Optional[np.ndarray]]], ]:
        """
        Function for converting a flux into a magnitude.

        Parameters
        ----------
        flux : float, np.ndarray
            Flux (W m-2 um-1).
        error : float, np.ndarray, None
            Uncertainty (W m-2 um-1). Not used if set to None.
        parallax : tuple(float, float), , tuple(np.ndarray, np.ndarray), None
            Parallax and uncertainty (mas). The returned absolute
            magnitude is set to ``None`` in case ``parallax`` and
            ``distance`` are set to ``None``. The error is not
            propagated into the error on the absolute magnitude
            in case the parallax uncertainty is set to ``None``,
            for example ``parallax=(10., None)``.
        distance : tuple(float, float), tuple(np.ndarray, np.ndarray), None
            Distance and uncertainty (pc). The returned absolute
            magnitude is set to ``None`` in case ``distance`` and
            ``parallax`` are set to ``None``. The error is not
            propagated into the error on the absolute magnitude in
            case the distance uncertainty is set to ``None``, for
            example ``distance=(20., None)``. This parameter is
            ignored if the ``parallax`` parameter is used.

        Returns
        -------
        tuple(float, float), tuple(np.ndarray, np.ndarray)
            Apparent magnitude and uncertainty.
        tuple(float, float), tuple(np.ndarray, np.ndarray)
            Absolute magnitude and uncertainty.
        """

        if parallax is not None:
            distance = phot_util.parallax_to_distance(parallax)

        zp_flux = self.zero_point()

        app_mag = self.vega_mag - 2.5 * np.log10(flux / zp_flux)

        if error is None:
            error_app_mag = None
            error_abs_mag = None

        else:
            error_app_lower = app_mag - (self.vega_mag - 2.5 * np.log10(
                (flux + error) / zp_flux))
            error_app_upper = (self.vega_mag - 2.5 * np.log10(
                (flux - error) / zp_flux)) - app_mag
            error_app_mag = (error_app_lower + error_app_upper) / 2.0

        if distance is None:
            abs_mag = None
            error_abs_mag = None

        else:
            abs_mag, error_abs_mag = phot_util.apparent_to_absolute(
                (app_mag, error_app_mag), distance)

        return (app_mag, error_app_mag), (abs_mag, error_abs_mag)
コード例 #5
0
ファイル: read_color.py プロジェクト: vandalt/species
    def get_color_magnitude(self,
                            object_type: Optional[str] = None) -> box.ColorMagBox:
        """
        Function for extracting color-magnitude data from the selected library.

        Parameters
        ----------
        object_type : str, None
            Object type for which the colors and magnitudes are extracted. Either field dwarfs
            ('field') or young/low-gravity objects ('young'). All objects are selected if set
            to ``None``.

        Returns
        -------
        species.core.box.ColorMagBox
            Box with the colors and magnitudes.
        """

        if self.lib_type == 'phot_lib':
            with h5py.File(self.database, 'r') as h5_file:
                sptype = np.asarray(h5_file[f'photometry/{self.library}/sptype'])
                dist = np.asarray(h5_file[f'photometry/{self.library}/distance'])
                dist_error = np.asarray(h5_file[f'photometry/{self.library}/distance_error'])
                flag = np.asarray(h5_file[f'photometry/{self.library}/flag'])
                obj_names = np.asarray(h5_file[f'photometry/{self.library}/name'])

            if object_type is None:
                indices = np.arange(0, np.size(sptype), 1)

            elif object_type == 'field':
                indices = np.where(flag == 'null')[0]

            elif object_type == 'young':
                indices = []

                for j, object_flag in enumerate(flag):
                    if 'young' in object_flag:
                        indices.append(j)

                    elif 'lowg' in object_flag:
                        indices.append(j)

                indices = np.array(indices)

            if indices.size > 0:
                with h5py.File(self.database, 'r') as h5_file:
                    mag1 = np.asarray(h5_file[f'photometry/{self.library}/{self.filters_color[0]}'])
                    mag2 = np.asarray(h5_file[f'photometry/{self.library}/{self.filters_color[1]}'])

            else:
                raise ValueError(f'There is not data available from \'{self.library}\' for '
                                 f'\'{object_type}\' type objects with the chosen filters.')

            color = mag1 - mag2

            if self.filter_mag == self.filters_color[0]:
                mag, _ = phot_util.apparent_to_absolute((mag1, None), (dist, dist_error))

            elif self.filter_mag == self.filters_color[1]:
                mag, _ = phot_util.apparent_to_absolute((mag2, None), (dist, dist_error))

            color = color[indices]
            mag = mag[indices]
            sptype = sptype[indices]
            obj_names = obj_names[indices]

            indices = []
            for i in range(color.size):
                if not np.isnan(color[i]) and not np.isnan(mag[i]):
                    indices.append(i)

            colormag_box = box.create_box(boxtype='colormag',
                                          library=self.library,
                                          object_type=object_type,
                                          filters_color=self.filters_color,
                                          filter_mag=self.filter_mag,
                                          color=color[indices],
                                          magnitude=mag[indices],
                                          sptype=sptype[indices],
                                          names=obj_names[indices])

        elif self.lib_type == 'spec_lib':
            read_spec_0 = read_spectrum.ReadSpectrum(spec_library=self.library,
                                                     filter_name=self.filters_color[0])

            read_spec_1 = read_spectrum.ReadSpectrum(spec_library=self.library,
                                                     filter_name=self.filters_color[1])

            read_spec_2 = read_spectrum.ReadSpectrum(spec_library=self.library,
                                                     filter_name=self.filter_mag)

            phot_box_0 = read_spec_0.get_magnitude(sptypes=None)
            phot_box_1 = read_spec_1.get_magnitude(sptypes=None)
            phot_box_2 = read_spec_2.get_magnitude(sptypes=None)

            colormag_box = box.create_box(boxtype='colormag',
                                          library=self.library,
                                          object_type=object_type,
                                          filters_color=self.filters_color,
                                          filter_mag=self.filter_mag,
                                          color=phot_box_0.app_mag[:, 0]-phot_box_1.app_mag[:, 0],
                                          magnitude=phot_box_2.abs_mag[:, 0],
                                          sptype=phot_box_0.sptype,
                                          names=None)

        return colormag_box
コード例 #6
0
    def get_color_magnitude(self,
                            object_type):
        """
        Parameters
        ----------
        object_type : str

        Returns
        -------
        species.core.box.ColorMagBox
            Box with the colors and magnitudes.
        """

        h5_file = h5py.File(self.database, 'r')

        for i, item in enumerate(self.library):
            try:
                h5_file['photometry/'+item]

            except KeyError:
                h5_file.close()
                species_db = database.Database()
                species_db.add_photometry(item)
                h5_file = h5py.File(self.database, 'r')

            sptype_tmp = np.asarray(h5_file['photometry/'+item+'/sptype'])
            distance_tmp = np.asarray(h5_file['photometry/'+item+'/distance'])  # [pc]
            flag_tmp = np.asarray(h5_file['photometry/'+item+'/flag'])

            if object_type == 'field':
                indices_tmp = np.where(flag_tmp == b'null')[0]
            else:
                indices_tmp = np.arange(0, np.size(sptype_tmp), 1)

            if i == 0:
                sptype = sptype_tmp
                distance = distance_tmp
                flag = flag_tmp
                indices = indices_tmp

                mag1 = np.asarray(h5_file['photometry/'+item+'/'+self.filters_color[0]])
                mag2 = np.asarray(h5_file['photometry/'+item+'/'+self.filters_color[1]])

            else:
                distance_tmp = np.asarray(h5_file['photometry/'+item+'/distance'])  # [pc]
                distance = np.concatenate((distance, distance_tmp), axis=0)

                sptype_tmp = np.asarray(h5_file['photometry/'+item+'/sptype'])
                sptype = np.concatenate((sptype, sptype_tmp), axis=0)

                flag = np.concatenate((flag, flag_tmp), axis=0)
                indices = np.concatenate((indices, indices.shape+indices_tmp), axis=0)

                mag1_tmp = np.asarray(h5_file['photometry/'+item+'/'+self.filters_color[0]])
                mag2_tmp = np.asarray(h5_file['photometry/'+item+'/'+self.filters_color[1]])

                mag1 = np.concatenate((mag1, mag1_tmp), axis=0)
                mag2 = np.concatenate((mag2, mag2_tmp), axis=0)

        color = mag1 - mag2

        if self.filter_mag == self.filters_color[0]:
            mag = phot_util.apparent_to_absolute(mag1, distance)

        elif self.filter_mag == self.filters_color[1]:
            mag = phot_util.apparent_to_absolute(mag2, distance)

        h5_file.close()

        return box.create_box(boxtype='colormag',
                              library=self.library,
                              object_type=object_type,
                              filters_color=self.filters_color,
                              filter_mag=self.filter_mag,
                              color=color[indices],
                              magnitude=mag[indices],
                              sptype=sptype[indices])