# Path: killMS/Array/NpShared.py
# def zeros(*args,**kwargs):
# def ToShared(Name,A):
# def DelArray(Name):
# def ListNames():
# def DelAll(key=None):
# def GiveArray(Name):
# def DicoToShared(Prefix,Dico,DelInput=False):
# def SharedToDico(Prefix):
#     def __init__(self,prefixName,Dico):
# def SharedObjectToDico(SObject):
# def PackListArray(Name,LArray):
# def UnPackListArray(Name):
#     T=ClassTimeIt.ClassTimeIt("   SharedToDico")
#     T=ClassTimeIt.ClassTimeIt("   SharedToDico")
#     T=ClassTimeIt.ClassTimeIt("   SharedToDico")
#     S=SharedArray.create(Name,(1+NArray+NDimTot+TotSize,),dtype=dS)
#     S[0]=NArray
#         A=LArray[i]
#         A=LArray[i]
#     S=GiveArray(Name)
#         A=S[idx:idx+size].reshape(shape)
# class SharedDicoDescriptor():
# 
# Path: killMS/Other/reformat.py
# def reformat(ssin,slash=True,LastSlash=True):
#     ss=ssin.split("/")
#     ss=filter (lambda a: a != "", ss)
#     ss="/".join(ss)+"/"
#     if ssin[0]=="/": ss="/"+ss
#     if not(slash):
#         ss=ss[1:-1]
#     if not(LastSlash):
#         if ss[-1]=="/": ss=ss[0:-1]
#     return ss
# 
# Path: killMS/Other/ModColor.py
# HEADER = '\033[95m'
# OKBLUE = '\033[94m'
# OKGREEN = '\033[92m'
# WARNING = '\033[93m'
# FAIL = '\033[91m'
# ENDC = '\033[0m'
#     HEADER = ''
#     OKBLUE = ''
#     OKGREEN = ''
#     WARNING = ''
#     FAIL = ''
#     ENDC = ''
# def Str(strin0,col="red",Bold=True):
# def Sep(strin=None,D=1):
# def Title(strin,Big=False):
# def disable():


import numpy as np
import DDFacet.Other.MyPickle
import os
import pprint
import multiprocessing
from DDFacet.Imager.ClassDeconvMachine import ClassImagerDeconv
from pyrap.images import image
from killMS.Array import NpShared
from killMS.Other import reformat
from killMS.Other import ModColor
from DDFacet.Other import logger
from DDFacet.Other.progressbar import ProgressBar
from DDFacet.ToolsDir.GiveEdges import GiveEdges
from DDFacet.Imager.ClassImToGrid import ClassImToGrid
from DDFacet.Data import ClassVisServer
from DDFacet.Imager.ModModelMachine import ClassModModelMachine
from pyrap.tables import table
        from DDFacet.Other.AsyncProcessPool import APP
        from killMS.Data import ClassBeam
        
        if Th>0:
            log.print("Compute mean beam for direction removal...")
            BeamMachine=ClassBeam.ClassBeam(self.VS.ListMS[0].MSName,self.GD["GDkMS"],self.SM)#,ColName=self.GD["Data"]["ColName"])
            AbsMeanBeam=BeamMachine.GiveMeanBeam(NTimes=10)
            AbsMeanBeamAnt=np.mean(AbsMeanBeam[:,:,0,0,0],axis=1)
        

            AppFlux=np.array([self.DicoJonesDirToFacet[iDirJones]["SumFlux"]*(AbsMeanBeamAnt[iDirJones])**2 for iDirJones in sorted(DicoJonesDirToFacet.keys())])
        else:
            AppFlux=np.array([self.DicoJonesDirToFacet[iDirJones]["SumFlux"] for iDirJones in sorted(DicoJonesDirToFacet.keys())])
            
        MaxAppFlux=AppFlux.max()

        HasRemoved=0

        for iDirJones in sorted(DicoJonesDirToFacet.keys()):
            #print(self.DicoJonesDirToFacet[iDirJones]["SumFlux"])
            #if self.DicoJonesDirToFacet[iDirJones]["SumFlux"]==0:
            
            if AppFlux[iDirJones]<=MaxAppFlux*Th:
                log.print(ModColor.Str("  Remove Jones direction %i [%f < %f Jy [Th = %f of Max %f Jy]]"%(iDirJones,AppFlux[iDirJones],MaxAppFlux*Th,Th,MaxAppFlux)))
                HasRemoved=1
                #print("  !!!!!!!!!!!!!!!!!!!!!!!")
            else:
                D[iDirNew]=self.DicoJonesDirToFacet[iDirJones]
                iDirNew+=1
                Keep[iDirJones]=1

        if not HasRemoved:

# Path: killMS/Array/NpShared.py
# def zeros(*args,**kwargs):
# def ToShared(Name,A):
# def DelArray(Name):
# def ListNames():
# def DelAll(key=None):
# def GiveArray(Name):
# def DicoToShared(Prefix,Dico,DelInput=False):
# def SharedToDico(Prefix):
#     def __init__(self,prefixName,Dico):
# def SharedObjectToDico(SObject):
# def PackListArray(Name,LArray):
# def UnPackListArray(Name):
#     T=ClassTimeIt.ClassTimeIt("   SharedToDico")
#     T=ClassTimeIt.ClassTimeIt("   SharedToDico")
#     T=ClassTimeIt.ClassTimeIt("   SharedToDico")
#     S=SharedArray.create(Name,(1+NArray+NDimTot+TotSize,),dtype=dS)
#     S[0]=NArray
#         A=LArray[i]
#         A=LArray[i]
#     S=GiveArray(Name)
#         A=S[idx:idx+size].reshape(shape)
# class SharedDicoDescriptor():
# 
# Path: killMS/Other/reformat.py
# def reformat(ssin,slash=True,LastSlash=True):
#     ss=ssin.split("/")
#     ss=filter (lambda a: a != "", ss)
#     ss="/".join(ss)+"/"
#     if ssin[0]=="/": ss="/"+ss
#     if not(slash):
#         ss=ss[1:-1]
#     if not(LastSlash):
#         if ss[-1]=="/": ss=ss[0:-1]
#     return ss
# 
# Path: killMS/Other/ModColor.py
# HEADER = '\033[95m'
# OKBLUE = '\033[94m'
# OKGREEN = '\033[92m'
# WARNING = '\033[93m'
# FAIL = '\033[91m'
# ENDC = '\033[0m'
#     HEADER = ''
#     OKBLUE = ''
#     OKGREEN = ''
#     WARNING = ''
#     FAIL = ''
#     ENDC = ''
# def Str(strin0,col="red",Bold=True):
# def Sep(strin=None,D=1):
# def Title(strin,Big=False):
# def disable():


# Path: killMS/Predict/ClassImageSM2.py
import numpy as np
import DDFacet.Other.MyPickle
import os
import pprint
import multiprocessing
from DDFacet.Imager.ClassDeconvMachine import ClassImagerDeconv
from pyrap.images import image
from killMS.Array import NpShared
from killMS.Other import reformat
from killMS.Other import ModColor
from DDFacet.Other import logger
from DDFacet.Other.progressbar import ProgressBar
from DDFacet.ToolsDir.GiveEdges import GiveEdges
from DDFacet.Imager.ClassImToGrid import ClassImToGrid
from DDFacet.Data import ClassVisServer
from DDFacet.Imager.ModModelMachine import ClassModModelMachine
from pyrap.tables import table
        from DDFacet.Other.AsyncProcessPool import APP
        from killMS.Data import ClassBeam

        
        if Th>0:
            log.print("Compute mean beam for direction removal...")
            BeamMachine=ClassBeam.ClassBeam(self.VS.ListMS[0].MSName,self.GD["GDkMS"],self.SM)#,ColName=self.GD["Data"]["ColName"])
            AbsMeanBeam=BeamMachine.GiveMeanBeam(NTimes=10)
            AbsMeanBeamAnt=np.mean(AbsMeanBeam[:,:,0,0,0],axis=1)
        

            AppFlux=np.array([self.DicoJonesDirToFacet[iDirJones]["SumFlux"]*(AbsMeanBeamAnt[iDirJones])**2 for iDirJones in sorted(DicoJonesDirToFacet.keys())])
        else:
            AppFlux=np.array([self.DicoJonesDirToFacet[iDirJones]["SumFlux"] for iDirJones in sorted(DicoJonesDirToFacet.keys())])
            
        MaxAppFlux=AppFlux.max()

        HasRemoved=0

        for iDirJones in sorted(DicoJonesDirToFacet.keys()):
            #print(self.DicoJonesDirToFacet[iDirJones]["SumFlux"])
            #if self.DicoJonesDirToFacet[iDirJones]["SumFlux"]==0:
            
            if AppFlux[iDirJones]<=MaxAppFlux*Th:
                log.print(ModColor.Str("  Remove Jones direction %i [%f < %f Jy [Th = %f of Max %f Jy]]"%(iDirJones,AppFlux[iDirJones],MaxAppFlux*Th,Th,MaxAppFlux)))
                HasRemoved=1
                #print("  !!!!!!!!!!!!!!!!!!!!!!!")
            else:
                D[iDirNew]=self.DicoJonesDirToFacet[iDirJones]
                iDirNew+=1
                Keep[iDirJones]=1

        if not HasRemoved:

            log.print(ModColor.Str("All directions have been kept in the solve"))