# Path: emirdrp/core/recipe.py
# class EmirRecipe(recipes.BaseRecipe):
#     """Base clase for all EMIR Recipes
# 
# 
#     Attributes
#     ----------
#     logger :
#          recipe logger
# 
#     datamodel : EmirDataModel
# 
#     """
#     logger = logging.getLogger(__name__)
#     datamodel = emirdrp.datamodel.EmirDataModel()
# 
#     def types_getter(self):
#         imgtypes = [prods.MasterBadPixelMask,
#                     prods.MasterBias,
#                     prods.MasterDark,
#                     prods.MasterIntensityFlat,
#                     prods.MasterSpectralFlat,
#                     prods.MasterSky
#                     ]
#         getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d,
#                    [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s]
# 
#         return imgtypes, getters
# 
#     def get_filters(self):
#         import collections
#         imgtypes, getters = self.types_getter()
#         used_getters = []
#         for rtype, getter in zip(imgtypes, getters):
#             self.logger.debug('get_filters, %s  %s', rtype, getter)
#             if rtype is None:
#                 # Unconditional
#                 if isinstance(getter, collections.Iterable):
#                     used_getters.extend(getter)
#                 else:
#                     used_getters.append(getter)
#             else:
#                 # Search
#                 for key, val in self.RecipeInput.stored().items():
#                     if isinstance(val.type, rtype):
#                         if isinstance(getter, collections.Iterable):
#                             used_getters.extend(getter)
#                         else:
#                             used_getters.append(getter)
#                         break
#                 else:
#                     pass
#         return used_getters
# 
#     def init_filters_generic(self, rinput, getters, ins):
#         # with BPM, bias, dark, flat and sky
#         if numina.ext.gtc.check_gtc():
#             self.logger.debug('running in GTC environment')
#         else:
#             self.logger.debug('running outside of GTC environment')
# 
#         meta = emirdrp.processing.info.gather_info(rinput)
#         self.logger.debug('obresult info')
#         for entry in meta['obresult']:
#             self.logger.debug('frame info is %s', entry)
#         correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters]
#         flow = flowmod.SerialFlow(correctors)
#         return flow
# 
#     def init_filters(self, rinput, ins='EMIR'):
#         getters = self.get_filters()
#         return self.init_filters_generic(rinput, getters, ins)
# 
#     def aggregate_result(self, result, rinput):
#         return result
# 
# Path: emirdrp/instrument/channels.py
# QUADRANTS = [(_P2, _P1), (_P1, _P1), (_P1, _P2), (_P2, _P2)]
# 
# Path: emirdrp/instrument/channels.py
# CHANNELS = [chan for chans in [_CH1, _CH2, _CH3, _CH4] for chan in chans]
# 
# Path: emirdrp/products.py
# class MasterGainMap(DataProductType):
#     def __init__(self, mean, var, frame):
#         self.mean = mean
#         self.var = var
#         self.frame = frame
# 
#     def __getstate__(self):
#         gmean = list(map(float, self.mean.flat))
#         gvar = list(map(float, self.var.flat))
#         return {'frame': self.frame, 'mean': gmean, 'var': gvar}
# 
# class MasterRONMap(DataProductType):
#     def __init__(self, mean, var):
#         self.mean = mean
#         self.var = var
# 
#     def __getstate__(self):
#         gmean = map(float, self.mean.flat)
#         gvar = map(float, self.var.flat)
#         return {'mean': gmean, 'var': gvar}


import logging
import math
import numpy
import scipy.stats
from astropy.io import fits
from numina.core.requirements import ObservationResultRequirement
from numina.core import Parameter, DataFrame
from numina.exceptions import RecipeError
from numina.core import Result
from emirdrp.core.recipe import EmirRecipe
from emirdrp.instrument.channels import QUADRANTS
from emirdrp.instrument.channels import CHANNELS
from emirdrp.products import MasterGainMap, MasterRONMap
        _logger.debug('opening last reset image %s', last_reset)
        last_reset_data = fits.getdata(last_reset)

        for i, di in enumerate(ramps):
            with fits.open(di, mode='readonly') as fd:
                restdata = fd[0].data - last_reset_data
                for j, channel in enumerate(channels):
                    c = restdata[channel].mean()
                    _logger.debug('%f counts in channel', c)
                    counts[i, j] = c
                    v = restdata[channel].var(ddof=1)
                    _logger.debug('%f variance in channel', v)
                    variance[i, j] = v

        for j, _ in enumerate(channels):
            res = scipy.stats.linregress(counts[:, j], variance[:, j])
            slope, intercept, _r_value, _p_value, _std_err = res

            result_gain[j] = 1.0 / slope
            result_ron[j] = math.sqrt(intercept)
        cube = numpy.zeros((2, 2048, 2048))

        for gain, var, channel in zip(result_gain, result_ron, channels):
            cube[0][channel] = gain
            cube[1][channel] = var

        hdu = fits.PrimaryHDU(cube[0])
        hduvar = fits.ImageHDU(cube[1])
        hdulist = fits.HDUList([hdu, hduvar])


# Path: emirdrp/core/recipe.py
# class EmirRecipe(recipes.BaseRecipe):
#     """Base clase for all EMIR Recipes
# 
# 
#     Attributes
#     ----------
#     logger :
#          recipe logger
# 
#     datamodel : EmirDataModel
# 
#     """
#     logger = logging.getLogger(__name__)
#     datamodel = emirdrp.datamodel.EmirDataModel()
# 
#     def types_getter(self):
#         imgtypes = [prods.MasterBadPixelMask,
#                     prods.MasterBias,
#                     prods.MasterDark,
#                     prods.MasterIntensityFlat,
#                     prods.MasterSpectralFlat,
#                     prods.MasterSky
#                     ]
#         getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d,
#                    [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s]
# 
#         return imgtypes, getters
# 
#     def get_filters(self):
#         import collections
#         imgtypes, getters = self.types_getter()
#         used_getters = []
#         for rtype, getter in zip(imgtypes, getters):
#             self.logger.debug('get_filters, %s  %s', rtype, getter)
#             if rtype is None:
#                 # Unconditional
#                 if isinstance(getter, collections.Iterable):
#                     used_getters.extend(getter)
#                 else:
#                     used_getters.append(getter)
#             else:
#                 # Search
#                 for key, val in self.RecipeInput.stored().items():
#                     if isinstance(val.type, rtype):
#                         if isinstance(getter, collections.Iterable):
#                             used_getters.extend(getter)
#                         else:
#                             used_getters.append(getter)
#                         break
#                 else:
#                     pass
#         return used_getters
# 
#     def init_filters_generic(self, rinput, getters, ins):
#         # with BPM, bias, dark, flat and sky
#         if numina.ext.gtc.check_gtc():
#             self.logger.debug('running in GTC environment')
#         else:
#             self.logger.debug('running outside of GTC environment')
# 
#         meta = emirdrp.processing.info.gather_info(rinput)
#         self.logger.debug('obresult info')
#         for entry in meta['obresult']:
#             self.logger.debug('frame info is %s', entry)
#         correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters]
#         flow = flowmod.SerialFlow(correctors)
#         return flow
# 
#     def init_filters(self, rinput, ins='EMIR'):
#         getters = self.get_filters()
#         return self.init_filters_generic(rinput, getters, ins)
# 
#     def aggregate_result(self, result, rinput):
#         return result
# 
# Path: emirdrp/instrument/channels.py
# QUADRANTS = [(_P2, _P1), (_P1, _P1), (_P1, _P2), (_P2, _P2)]
# 
# Path: emirdrp/instrument/channels.py
# CHANNELS = [chan for chans in [_CH1, _CH2, _CH3, _CH4] for chan in chans]
# 
# Path: emirdrp/products.py
# class MasterGainMap(DataProductType):
#     def __init__(self, mean, var, frame):
#         self.mean = mean
#         self.var = var
#         self.frame = frame
# 
#     def __getstate__(self):
#         gmean = list(map(float, self.mean.flat))
#         gvar = list(map(float, self.var.flat))
#         return {'frame': self.frame, 'mean': gmean, 'var': gvar}
# 
# class MasterRONMap(DataProductType):
#     def __init__(self, mean, var):
#         self.mean = mean
#         self.var = var
# 
#     def __getstate__(self):
#         gmean = map(float, self.mean.flat)
#         gvar = map(float, self.var.flat)
#         return {'mean': gmean, 'var': gvar}


# Path: emirdrp/recipes/engineering/detectorgain.py
import logging
import math
import numpy
import scipy.stats
from astropy.io import fits
from numina.core.requirements import ObservationResultRequirement
from numina.core import Parameter, DataFrame
from numina.exceptions import RecipeError
from numina.core import Result
from emirdrp.core.recipe import EmirRecipe
from emirdrp.instrument.channels import QUADRANTS
from emirdrp.instrument.channels import CHANNELS
from emirdrp.products import MasterGainMap, MasterRONMap

        _logger.debug('opening last reset image %s', last_reset)
        last_reset_data = fits.getdata(last_reset)

        for i, di in enumerate(ramps):
            with fits.open(di, mode='readonly') as fd:
                restdata = fd[0].data - last_reset_data
                for j, channel in enumerate(channels):
                    c = restdata[channel].mean()
                    _logger.debug('%f counts in channel', c)
                    counts[i, j] = c
                    v = restdata[channel].var(ddof=1)
                    _logger.debug('%f variance in channel', v)
                    variance[i, j] = v

        for j, _ in enumerate(channels):
            res = scipy.stats.linregress(counts[:, j], variance[:, j])
            slope, intercept, _r_value, _p_value, _std_err = res

            result_gain[j] = 1.0 / slope
            result_ron[j] = math.sqrt(intercept)
        cube = numpy.zeros((2, 2048, 2048))

        for gain, var, channel in zip(result_gain, result_ron, channels):
            cube[0][channel] = gain
            cube[1][channel] = var

        hdu = fits.PrimaryHDU(cube[0])
        hduvar = fits.ImageHDU(cube[1])
        hdulist = fits.HDUList([hdu, hduvar])


        gain = MasterGainMap(mean=result_gain, var=numpy.array([]),