Code Monkey home page Code Monkey logo

nirdust's People

Contributors

gaiana avatar j0sealacoria avatar leliel12 avatar mchalela avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

Forkers

leliel12

nirdust's Issues

add to metadata the spectral region information

add to metadata the spectral region information in the case of using the default values or in the case the user changes it with 'compute_noise'. Once the region is in the metadata, change "line_spectrum" to use that info.

Create setup.py

  • copy ez_setup.py
  • Copy and modify the setup.py from grispy

handle different spectrum_lengths

Study the best way to handle different spectral_axis lenght

One idea is convert cut_edges into a function that takes both spectrum and cut them in the same spectral range and then cut the extra pixels that could be left.

Other idea is to leave this issue to be solved in sp_correction but using wavelenght to compare the spectra instead of pixels (actually both have to be used)

testing de empaquetado

Los archivos MANIFEST.in controlan el contenido de los paquetes binarios en python.

Por ejemplo controlan que no se agrgegue toda la documentacion, pero si la licencia al paquete (importante por cuestiones legales)

Agregar el environment de test siguiente a tox (y travis)

[testenv:check-manifest]
skip_install = True
usedevelop = False
deps = check-manifest
commands =
    check-manifest

Puede crearse un archivo MANIFEST vacio con check-manifest -c es importante tener en cuenta que para que todo funcione tienen que hacer git add MANIFEST.in

Ver MANIFEST.in de pyedra

add doct testing

Agregar documentacion a todos sus modulos, metodos y clases

Copiar de pyedra

[testenv:docstyle]
deps = pydocstyle
commands =
    pydocstyle nirdust.py --convention=numpy

add tox environment

Acordarse de agregarlo a travis

[testenv]
deps =
    ipdb
    pytest
commands =
    pytest test_nirdust.py {posargs}

Detect spectrum wavelength input units

Provide a way to allow the wavelength to be in different units, like micrometers, angstrom, nanometers, etc. Maybe automatically detect the units in "read_spectrum" according to the order of magnitude of the spectral axis.

smell in compute_noise

compute_noise is doing something wrong. Either it is not computing the noise in the region asigned by the user or it is not resetting the "noise" parameter

Implementat cut_edges

  • Primero definir el test
  • Funcion de corte cut_edges
def test_cut_edges(NGC4945_continuum):
    spectrum = NGC4945_continuum
    reg = sp.SpectralRegion(min, max)
    expected = sp.manipulation.extract_region(spectrum.spec1d, region)
    result = spectrum.cut_edges(min, max)
    np.testing.assert_array_equal(result.spec1d.flux, expected.flux)

Extract IO from class

Prototype

# ==============================================================================
# DOCS
# ==============================================================================

"""Nirdust test suite."""


# ==============================================================================
# IMPORTS
# ==============================================================================

import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
import specutils as su
import os
import pathlib
from pathlib import Path
from astropy import units as u


# ==============================================================================
# CONSTANTS
# ==============================================================================

PATH = pathlib.Path(os.path.abspath(os.path.dirname(__file__)))


# ==============================================================================
# CLASSES
# ==============================================================================


class NuclearSpectrum(su.Spectrum1D):
    def __init__(
        self,
        
        flux,
        header, 
        spectrum_length,
        
        radius=None,
        spectral_axis=None,
        data=None,
        flux_unit=None,
        wav_unit=None,
        wcs=None,
        velocity_convention=None,
        rest_value=None,
        redshift=None,
        radial_velocity=None,
        bin_specification=None,
        uncertainty=None,
        mask=None,
        meta=None,
        dispersion_key="CRVAL1",
        wavelength="CD1_1",
    ):

        self.spectrum_length = spectrum_length
        self.radius = radius

        super().__init__(
            flux=self.spectrum[extension].data * u.adu,
            spectral_axis=(
                self.header[dispersion_key]
                + self.header[wavelength]
                * np.arange(0, spectrum_length)
            )
            * u.AA,
            wcs=wcs,
            velocity_convention=velocity_convention,
            rest_value=rest_value,
            redshift=redshift,
            radial_velocity=radial_velocity,
            bin_specification=bin_specification,
            uncertainty=uncertainty,
            mask=mask,
            meta=meta,
        )





# class OffNuclearSpectrum(NuclearSpectrum):
#     ...



# ==============================================================================
# LOAD SPECTRA
# ==============================================================================


def read_nuclear_spectrum(fname, extension, **kwargs):  # IO
    spectrums = []
    with fits.open(fname) spectrum:
        fluxx = pectrum[extension].data
        header = fits.getheader(spectrum)
        spectrum_length = len(spectrum[extension].data)

    single_spectrum = NuclearSpectrum(
        spectrum_length=spectrum_legth, 
        flux=flux, header=header, 
        *args, **kwargs)
        
    return single_spectrum


spectrums = []
for path in glob.glob("/spectrums*.fots"):
    spec = nd.read_nuclear_spectrum(path, 0)
    spectrums.append(spec)

Integrate with travis

  • Configure the .travis.yml file
  • Enable the continuous integration to the master branch
  • Add the build badge to the README.md

Copy the .travis.yml file from grispy and modify it

Flake8 plugins

Add two flake8 plugins in tox.ini for the style environment.

The plugins only need to be installed and then flake8 works.

The plugins are:

these two plugins will achieve a much cleaner code

The tox environment configuration must be:

[testenv:style]
skip_install = True
usedevelop = False
deps = 
    flake8
    flake8-import-order
    flake8-black
commands = flake8 setup.py nirdust.py test_nirdust.py {posargs}

Also to correctly configure the black tool you need to create the pyproject.toml file, with the content

[tool.black]
line-length = 79
target-version = ["py38"]

Función con nombre incorrecto

Las funciones no empiezan con mayuscula y son un verbo descriptivo.

LAs funciones tienen nombres tipo substract_spectrum_to_another_zaraza

nirdust/nirdust.py

Lines 218 to 230 in 2a6b1ee

def Nirdustprepare(nuclear_spectrum, external_spectrum, mini, maxi):
"""Perform operations upon nuclear and external spactra.
The operations applied prepare the nuclear spectrum for black-body fitting:
1) wavelength cutting both spectra between the entered limits.
2) normalization to the mean value of the flux axis for both spectra
3) substraction of the external spectrum flux from the nuclear spectrum
flux.
4) conversion to frequency of the dispersion axis.
Parameters
----------

La documentación no esta clara en su resumen principal

"Perform operations upon nuclear and external spactra." eso no dice nada

Use Astropy API to create a Fittable1DModel

Change custom_model to Fittable1DModel to allow parallelization.

nirdust/nirdust.py

Lines 46 to 77 in 76d8591

@custom_model
def normalized_blackbody(nu, T=None):
"""Normalize blackbody model.
The equation for calculating the blackbody model is the same as in
the Astropy blackbody model except that the "scale" parameter is
eliminated, i.e. is allways equal to 1.
The normalization is performed by dividing the blackbody flux by its
numerical mean.
Parameters
----------
nu: SpectralAxis object
Frequency axis in units of Hz.
T: float, default is None
Temperature of the blackbody.
Returns
-------
out: normalized blackbody model.
"""
cv = c.value
kv = k_B.value
hv = h.value
bb = 2 * hv * nu ** 3 / (cv ** 2 * (np.exp(hv * nu / (kv * T)) - 1))
mean = np.mean(bb)
return bb / mean

test_axis_to_freq

def test_axis_to_freq(NGC4945_continuum):
    spectrum = NGC4945_continuum
    freq = spectrum.axis_to_freq
    np.testing.assert_almost_equal(
        freq.value.mean(), 138426209228521.23, decimal=1)

warmup

  • Pasar todos ipynb y el README a una carpeta draft
  • nirdust.py <<< archivo con codigo relevante
  • Agregar antes que nada el .gitignore
  • test_nirdust.py
  • Agregar LICENCE
  • tox.ini py38, style, coverage (al 80%)
  • Readme: Que operaciones vas a querer en nirdust,
class NirdustSpectrum(Spectrum1d):
    ...

spectre = NirdustSpectrum(t=...)

spectre.predict(...)

constants

import constants outside function

Pregunta sobre como funciona `_filter_internals`

en la funcion _filter_internal

nirdust/nirdust.py

Lines 66 to 75 in 03d5126

def _filter_internals(atribute, value):
"""Filter internal attributes of a class.
Used when the initialization attributes are required, but attrs.asdict(obj)
also returns internal attributes. The convention for internal attributes
here is one underscore.
"""
if atribute.name.endswith("_"):
return False
return True

La linea 73 reza if atribute.name.endswith("_"): no deberia ser:

if atribute.name.startswith("_") or atribute.name.endswith("_"): 
    ...

add docstyle in tox

  • Copy and adapt the doctstyle environment from grispy.
  • Add the environment in the [tox] envlist.
  • Add the new environment into travis.

Implement class method for smoothing spectra

Implement a class method for NirdustSpectrum that rebins or smooth spectra in order to increment the S/N. The imput could be the desired S/N (with some warning when the requeriment is too high) or the kernel to use in the smoothing.

implement correct_z parameter

In both read_table and read_fits z parameter should be None by default and a new parameter is needed to indicate if the spectrum must be redshift corrected

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.