import logging
_log = logging.getLogger(__name__)

import numpy as np

from devsup.dset import AsyncOffload

class Dev(AsyncOffload):
    inputs = {
        'A':'threshold',
        'B':'wftime1',
        'C':'wfamp1',
        'D':'wfpha1',
        'E':'wftime2',
        'F':'wfamp2',
        'G':'wfpha2',
    }
    outputs = {
        'VALA':'detune',
        'VALB':'error',
        'VALC':'fitted',
        'VALD':'diff',
        'VALE':'weight',
    }
    def inThread(self, threshold=None,
                 wftime1=None, wfamp1=None, wfpha1=None,
                 wftime2=None, wfamp2=None, wfpha2=None):

        # validate that inputs have matching non-zero sizes
        ok = wftime1.size>0 and wftime2.size>0
        ok &= wftime1.shape==wftime2.shape
        ok &= wftime1.shape==wfamp1.shape and wftime1.shape==wfpha1.shape
        ok &= wftime1.shape==wfamp2.shape and wftime1.shape==wfpha2.shape
        # avoid divide by zero
        ok &= wfamp1.max()>0.0 and wfamp2.max()>0.0

        if not ok:
            return {
                'detune':0.0,
                'error':-1,
                'fitted':np.zeros(len(wftime1)),
                'diff':np.zeros(len(wftime1)),
                'weight':np.zeros(len(wftime1)),
            }

        T = wftime1
        pha = wfpha2-wfpha1
        # weight by normalized amplitudes of both (difference only valid where both are non-zero)
        W  = wfamp1/wfamp1.max()
        W *= wfamp2/wfamp2.max()

        # linear fix weighted by normalized amplitude
        param = np.polyfit(T, pha, 1, w=W)
        slope, offset = param

        wffit = np.polyval(param, T)
        # compute residual also weighted by normalized amplitude
        delta = np.abs(wffit-pha) * W

        return {
            'detune':slope,
            'error':delta.mean(),
            'fitted':wffit,
            'diff':pha,
            'weight':W,
        }

build = Dev
