def fix_dico_shape(fulldico, outdico, NPixOut):
    # dico_model = 'image_full_ampphase_di_m.NS.DicoModel'
    # save_dico = dico_model.replace('.DicoModel', '.restricted.DicoModel')
    # NPixOut = 10000

    dico = MyPickle.Load(fulldico)

    NPix = dico['ModelShape'][-1]
    NPix0, _ = EstimateNpix(float(NPix), Padding=1)
    if NPix != NPix0:
        raise ValueError("NPix != NPix0")
    logger.info("Changing image size: %i -> %i pixels" % (NPix, NPixOut))
    xc0 = NPix // 2
    xc1 = NPixOut // 2
    dx = xc0 - xc1
    DCompOut = {}
    for k, v in dico.items():
        if k == 'Comp':
            DCompOut['Comp'] = {}
            continue
        DCompOut[k] = v
    DCompOut["Type"] = "SSD"

    N, M, _, _ = dico['ModelShape']
    DCompOut['ModelShape'] = [N, M, NPixOut, NPixOut]
    for (x0, y0) in dico['Comp'].keys():
        x1 = x0 - dx
        y1 = y0 - dx
        c0 = (x1 >= 0) & (x1 < NPixOut)
        c1 = (y1 >= 0) & (y1 < NPixOut)
        if c0 & c1:
            logger.info("Mapping (%i,%i)->(%i,%i)" % (x0, y0, x1, y1))
            DCompOut['Comp'][(x1, y1)] = dico['Comp'][(x0, y0)]
    logger.info("Saving in {}".format(outdico))
    MyPickle.Save(DCompOut, outdico)
Ejemplo n.º 2
0
    def Cluster(self):

        l, m = self.radec2lm(self.Cat.ra, self.Cat.dec)
        S = self.Cat.S.copy()
        PolyList = None
        self.BigPolygon = []
        PolyList = []
        if self.AvoidPolygons != "":
            print("Reading polygon file: %s" % self.AvoidPolygons, file=log)
            PolyList += MyPickle.Load(self.AvoidPolygons)

        if len(PolyList) > 0:
            LPoly = []
            inside = np.zeros((l.size, ), np.float32)
            for iPolygon, Poly in enumerate(PolyList):
                ra, dec = Poly.T
                lp, mp = self.radec2lm(ra, dec)
                Poly[:, 0] = lp
                Poly[:, 1] = mp
                P = Polygon.Polygon(Poly)
                if P.area() > self.BigPolygonSize:
                    self.BigPolygon.append(Poly)
                for ip in range(l.size):
                    if P.isInside(l[ip], m[ip]):
                        inside[ip] = 1

            # l=l[inside==0]
            # m=m[inside==0]
            # S=S[inside==0]
            print("There are %i big polygons" % len(self.BigPolygon), file=log)

        if self.CentralRadius > 0:
            print("Create central polygon with radius %f degrees" %
                  self.CentralRadius,
                  file=log)
            Rad = self.CentralRadius * np.pi / 180
            th = np.arange(0, 2. * np.pi, 2. * np.pi / 100)
            lp = np.cos(th) * Rad
            mp = np.sin(th) * Rad
            Poly = np.zeros((lp.size, 2), np.float32)
            Poly[:, 0] = lp
            Poly[:, 1] = mp
            PolyList += [Poly]

        CC = Sky.ClassClusterDEAP.ClassCluster(l,
                                               m,
                                               S,
                                               nNode=self.NCluster,
                                               NGen=self.NGen,
                                               NPop=self.NPop,
                                               DoPlot=self.DoPlot,
                                               PolyCut=self.PolyCut,
                                               NCPU=self.NCPU,
                                               BigPolygon=self.BigPolygon)
        CC.setAvoidPolygon(PolyList)

        xyNodes, self.LPolygon = CC.Cluster()
        nNodes = xyNodes.size // 2
        xc, yc = xyNodes.reshape((2, nNodes))
        self.xcyc = xc, yc
Ejemplo n.º 3
0
def main(args=None, messages=[]):
    if args is None:
        args = MyPickle.Load(SaveFile)

    MSList = expandMSList(args.ms)
    MSList = [mstuple[0] for mstuple in MSList]

    D = ClassDynSpecMS(ListMSName=MSList,
                       ColName=args.data,
                       ModelName=args.model,
                       SolsName=args.sols,
                       UVRange=args.uv,
                       FileCoords=args.srclist,
                       Radius=args.rad,
                       NOff=args.noff,
                       Image=args.image,
                       SolsDir=args.SolsDir,
                       NCPU=args.NCPU)

    if D.NDirSelected == 0:
        return

    D.StackAll()

    SaveMachine = ClassSaveResults.ClassSaveResults(D)
    SaveMachine.WriteFits()
    SaveMachine.PlotSpec()
    SaveMachine.tarDirectory()
Ejemplo n.º 4
0
 def GiveMMFromFile(self,FileName=None):
     """
     Initialise a model machine from a file
     Input:
         FileName    = The file to read
     """
     if FileName is not None:
         DicoSMStacked = MyPickle.Load(FileName)
         return self.GiveMMFromDico(DicoSMStacked)
     else:
         return self.GiveMMFromDico()
Ejemplo n.º 5
0
    def GiveInitialisedMMFromFile(self, FileName):
        """
        Initialise a model machine from a file
        Input:
            FileName    = The file to read
        """

        DicoSMStacked = MyPickle.Load(FileName)
        if self.GD is None:
            self.GD = DicoSMStacked["GD"]
        MM = self.GiveMMFromDico(DicoSMStacked)
        MM.FromDico(DicoSMStacked)
        return MM
Ejemplo n.º 6
0
def testMF_DATA():
    Dico = MyPickle.Load("SaveTest")
    Dirty = Dico["Dirty"]
    PSF = Dico["PSF"]

    FreqsInfo = Dico["FreqsInfo"]

    IslandBestIndiv = Dico["IslandBestIndiv"]

    ListPixData = Dico["ListPixData"]
    ListPixParms = Dico["ListPixParms"]

    GD = Dico["GD"]
    FacetID = Dico["FacetID"]
    IdSharedMem = Dico["IdSharedMem"]
    iIsland = Dico["iIsland"]

    #GD["GAClean"]["GASolvePars"]=["S","Alpha","GSig"]
    #GD["GAClean"]["GASolvePars"]=["S","Alpha"]

    nch = FreqsInfo["MeanJonesBand"][FacetID].size
    WeightMeanJonesBand = FreqsInfo["MeanJonesBand"][FacetID].reshape(
        (nch, 1, 1, 1))
    WeightMueller = WeightMeanJonesBand.ravel()
    WeightMuellerSignal = WeightMueller * FreqsInfo["WeightChansImages"].ravel(
    )

    # IncreaseIslandMachine=ClassIncreaseIsland.ClassIncreaseIsland()
    # ListPixData=IncreaseIslandMachine.IncreaseIsland(ListPixData,dx=20)

    # IncreaseIslandMachine=ClassIncreaseIsland.ClassIncreaseIsland()
    # ListPixData=IncreaseIslandMachine.IncreaseIsland(ListPixData,dx=5)
    #IslandBestIndiv=np.zeros((len(GD["GAClean"]["GASolvePars"])*len(
    CEv = ClassEvolveGA(Dirty,
                        PSF,
                        FreqsInfo,
                        ListPixParms=ListPixParms,
                        ListPixData=ListPixData,
                        GD=GD,
                        IslandBestIndiv=IslandBestIndiv,
                        WeightFreqBands=WeightMuellerSignal,
                        iIsland=iIsland,
                        IdSharedMem=IdSharedMem)
    CEv.main()
Ejemplo n.º 7
0
    def Cluster(self):
        
        l,m=self.radec2lm(self.Cat.ra,self.Cat.dec)
        S=self.Cat.S.copy()
        PolyList=None
        if self.AvoidPolygons!="":
            print>>log,"Reading polygon file: %s"%self.AvoidPolygons
            self.BigPolygon=[]
            PolyList=MyPickle.Load(self.AvoidPolygons)
            LPoly=[]
            inside=np.zeros((l.size,),np.float32)
            for iPolygon,Poly in enumerate(PolyList):
                ra,dec=Poly.T
                lp,mp=self.radec2lm(ra,dec)
                Poly[:,0]=lp
                Poly[:,1]=mp
                P=Polygon.Polygon(Poly)
                if P.area()>self.BigPolygonSize:
                    self.BigPolygon.append(Poly)
                for ip in range(l.size):
                    if P.isInside(l[ip],m[ip]):
                        inside[ip]=1

            l=l[inside==0]
            m=m[inside==0]
            S=S[inside==0]
            print>>log,"There are %i big polygons"%len(self.BigPolygon)
            
        CC=Sky.ClassClusterDEAP.ClassCluster(l,m,S,nNode=self.NCluster,
                                             NGen=self.NGen,
                                             NPop=self.NPop,
                                             DoPlot=self.DoPlot,
                                             PolyCut=self.PolyCut,
                                             NCPU=self.NCPU,
                                             BigPolygon=self.BigPolygon)
        CC.setAvoidPolygon(PolyList)
            
        xyNodes,self.LPolygon=CC.Cluster()
        nNodes=xyNodes.size/2
        xc,yc=xyNodes.reshape((2,nNodes))
        self.xcyc=xc,yc
Ejemplo n.º 8
0
def test():
    P = ClassPrint.ClassPrint()
    Obj, ValObj = MyPickle.Load("test")
    #return Obj
    #ValObj,_=Obj.parse_args()
    #return ValObj
    LGroups = Obj.option_groups
    for Group in LGroups:
        print(Group.title)

        option_list = Group.option_list
        for o in option_list:
            lopt = o._long_opts[0]
            oname = lopt.split("--")[-1]
            V = getattr(ValObj, oname)
            if V != "":

                P.Print(oname, V)
                # strName=%s
                # print "       "oname,V
        print()
Ejemplo n.º 9
0
def main(args=None, messages=[]):
    if args is None:
        args = MyPickle.Load(SaveFile)

    MSList=None
    if args.ms:
        MSList=expandMSList(args.ms)
        MSList=[mstuple[0] for mstuple in MSList]

    D = ClassDynSpecMS(ListMSName=MSList, 
                       ColName=args.data, ModelName=args.model, 
                       SolsName=args.sols,
                       ColWeights=args.WeightCol,
                       UVRange=args.uv,
                       FileCoords=args.srclist,
                       Radius=args.rad,
                       NOff=args.noff,
                       ImageI=args.imageI,
                       ImageV=args.imageV,
                       SolsDir=args.SolsDir,NCPU=args.NCPU,
                       BaseDirSpecs=args.BaseDirSpecs,
                       BeamModel=args.BeamModel,
                       BeamNBand=args.BeamNBand)

    if D.NDirSelected==0:
        return

    if D.Mode=="Spec": D.StackAll()

    SaveMachine=ClassSaveResults.ClassSaveResults(D)
    if D.Mode=="Spec":
        SaveMachine.WriteFits()
        SaveMachine.PlotSpec()
        SaveMachine.SaveCatalog()
        SaveMachine.tarDirectory()
    else:
        SaveMachine.SaveCatalog()
        SaveMachine.PlotSpec(Prefix="_replot")
Ejemplo n.º 10
0
 def FromFile(self,FileName):
     print>>log, "Reading dico model from file %s"%FileName
     self.DicoModel=MyPickle.Load(FileName)
     self.FromDico(self.DicoModel)
Ejemplo n.º 11
0
 def FromFile(self, FileName):
     print >> log, "Reading dico model from %s" % FileName
     self.DicoSMStacked = MyPickle.Load(FileName)
     self.FromDico(self.DicoSMStacked)
Ejemplo n.º 12
0
def main(OP=None, messages=[]):
    if OP is None:
        OP = MyPickle.Load(SaveFile)
        print("Using settings from %s, then command line."%SaveFile)

    DicoConfig = OP.DicoConfig

    ImageName = DicoConfig["Output"]["Name"]
    if not ImageName:
        raise Exceptions.UserInputError("--Output-Name not specified, can't continue.")
    if not DicoConfig["Data"]["MS"]:
        raise Exceptions.UserInputError("--Data-MS not specified, can't continue.")

    # create directory if it exists
    dirname = os.path.dirname(ImageName)
    if not os.path.exists(dirname) and not dirname == "":
        os.mkdir(dirname)

    # setup logging
    logger.logToFile(ImageName + ".log", append=DicoConfig["Log"]["Append"])
    global log
    log = logger.getLogger("DDFacet")

    # disable colors and progressbars if requested
    ModColor.silent = SkyModel.Other.ModColor.silent = \
                      progressbar.ProgressBar.silent = \
                      DicoConfig["Log"]["Boring"]

    if messages:
        if not DicoConfig["Log"]["Boring"]:
            #os.system('clear')
            logo.print_logo()
        for msg in messages:
            print(msg, file=log)

    print("Checking system configuration:", file=log)
    # check for SHM size
    ram_size = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES')
    shm_stats = os.statvfs('/dev/shm')
    shm_size = shm_stats.f_bsize * shm_stats.f_blocks
    shm_relsize = shm_size / float(ram_size)
    shm_avail = shm_stats.f_bsize * shm_stats.f_bavail / float(ram_size)

    if shm_relsize < 0.6:
        print(ModColor.Str("""WARNING: max shared memory size is only {:.0%} of total RAM size.
            This can cause problems for large imaging jobs. A setting of 90% is recommended for 
            DDFacet and killMS. If your processes keep failing with SIGBUS or "bus error" messages,
            it is most likely for this reason. You can change the memory size by running
                $ sudo mount -o remount,size=90% /dev/shm
            To make the change permanent, edit /etc/defaults/tmps, and add a line saying "SHM_SIZE=90%".
            """.format(shm_relsize)), file=log)
    else:
        print("  Max shared memory size is {:.0%} of total RAM size; {:.0%} currently available".format(shm_relsize, shm_avail), file=log)

    try:
        output = subprocess.check_output(["/sbin/sysctl", "vm.max_map_count"],universal_newlines=True)
    except Exception:
        print(ModColor.Str("""WARNING: /sbin/sysctl vm.max_map_count failed. Unable to check this setting."""), file=log)
        max_map_count = None
    else:
        max_map_count = int(output.strip().rsplit(" ", 1)[-1])

    if max_map_count is not None:
        if max_map_count < 500000:
            print(ModColor.Str("""WARNING: sysctl vm.max_map_count = {}. 
            This may be too little for large DDFacet and killMS jobs. If you get strange "file exists" 
            errors on /dev/shm, them try to bribe, beg or threaten your friendly local sysadmin into 
            setting vm.max_map_count=1000000 in /etc/sysctl.conf.
                """.format(max_map_count)), file=log)
        else:
            print("  sysctl vm.max_map_count = {}".format(max_map_count), file=log)

    # check for memory lock limits
    import resource
    msoft, mhard = resource.getrlimit(resource.RLIMIT_MEMLOCK)
    if msoft >=0 or mhard >=0:
        print(ModColor.Str("""WARNING: your system has a limit on memory locks configured.
            This may possibly slow down DDFacet performance. You can try removing the limit by running
                $ ulimit -l unlimited
            If this gives an "operation not permitted" error, you can try to bribe, beg or threaten 
            your friendly local sysadmin into doing
                # echo "*        -   memlock     unlimited" >> /etc/security/limits.conf
        """), file=log)


    if DicoConfig["Debug"]["Pdb"] == "always":
        print("--Debug-Pdb=always: unexpected errors will be dropped into pdb", file=log)
        Exceptions.enable_pdb_on_error(ModColor.Str("DDFacet has encountered an unexpected error. Dropping you into pdb for a post-mortem.\n" +
                                           "(This is because you're running with --Debug-Pdb set to 'always'.)"))
    elif DicoConfig["Debug"]["Pdb"] == "auto" and not DicoConfig["Log"]["Boring"]:
        print("--Debug-Pdb=auto and not --Log-Boring: unexpected errors will be dropped into pdb", file=log)
        Exceptions.enable_pdb_on_error(ModColor.Str("DDFacet has encountered an unexpected error. Dropping you into pdb for a post-mortem.\n" +
            "(This is because you're running with --Debug-Pdb set to 'auto' and --Log-Boring is off.)"))

    # print current options
    OP.Print(dest=log)

    # enable memory logging
    logger.enableMemoryLogging(DicoConfig["Log"]["Memory"])

    # get rid of old shm arrays from previous runs
    Multiprocessing.cleanupStaleShm()

    # initialize random seed from config if set, or else from system time
    if DicoConfig["Misc"]["RandomSeed"] is not None:
        DicoConfig["Misc"]["RandomSeed"]=int(DicoConfig["Misc"]["RandomSeed"])
        print("random seed=%d (explicit)" % DicoConfig["Misc"]["RandomSeed"], file=log)
    else:
        DicoConfig["Misc"]["RandomSeed"] = int(time.time())
        print("random seed=%d (automatic)" % DicoConfig["Misc"]["RandomSeed"], file=log)
    np.random.seed(DicoConfig["Misc"]["RandomSeed"])

    # init NCPU for different bits of parallelism
    ncpu = int(DicoConfig["Parallel"]["NCPU"] or psutil.cpu_count())
    DicoConfig["Parallel"]["NCPU"]=ncpu
    _pyArrays.pySetOMPNumThreads(ncpu)
    NpParallel.NCPU_global = ModFFTW.NCPU_global = ncpu
    numexpr.set_num_threads(ncpu)
    print("using up to %d CPUs for parallelism" % ncpu, file=log)

    # write parset
    OP.ToParset("%s.parset"%ImageName)

    Mode = DicoConfig["Output"]["Mode"]

    # init semaphores, as they're needed for weight calculation too
    ClassFacetMachine.ClassFacetMachine.setup_semaphores(DicoConfig)

    # data machine initialized for all cases except PSF-only mode
    # psf machine initialized for all cases except Predict-only mode
    Imager = ClassDeconvMachine.ClassImagerDeconv(GD=DicoConfig,
                                                  BaseName=ImageName,
                                                  predict_only=(Mode == "Predict" or Mode == "Subtract"),
                                                  data=(Mode != "PSF"),
                                                  psf=(Mode != "Predict" and Mode != "Dirty" and Mode != "Subtract"),
                                                  readcol=(Mode != "Predict" and Mode != "PSF"),
                                                  deconvolve=("Clean" in Mode))

    Imager.Init()

    # Imager.testDegrid()
    # stop
    if "Predict" in Mode or "Subtract" in Mode:
        Imager.GivePredict()
    if "Clean" in Mode:
        Imager.main()
    elif "Dirty" in Mode:
        sparsify = DicoConfig["Comp"]["Sparsification"]
        if sparsify and isinstance(sparsify, list):
            sparsify = sparsify[0]
        Imager.GiveDirty(psf="PSF" in Mode, sparsify=sparsify)
    elif "PSF" in Mode:
        sparsify = DicoConfig["Comp"]["Sparsification"]
        if sparsify and isinstance(sparsify, list):
            sparsify = sparsify[0]
        Imager.MakePSF(sparsify=sparsify)
    elif "RestoreAndShift" == Mode:
        Imager.RestoreAndShift()
Ejemplo n.º 13
0
def testMO_DATA():
    Dico= MyPickle.Load("SaveTest")
    Dirty=Dico["Dirty"]
    PSF=Dico["PSF"]
    PSF2=np.squeeze(PSF)
    ListPixData=Dico["ListPixData"]
    FreqsInfo=Dico["FreqsInfo"]
    FreqsInfo=Dico["FreqsInfo"]
    IslandBestIndiv=Dico["IslandBestIndiv"]
    ListPixParms=ListPixData
    ListSquarePix=Dico["ListSquarePix"]
    ThisPixList=ListPixData
    ThisSquarePixList=ListSquarePix
    GD=Dico["GD"]
    FacetID=Dico["FacetID"]

    nch=FreqsInfo["MeanJonesBand"][FacetID].size
    WeightMeanJonesBand=FreqsInfo["MeanJonesBand"][FacetID].reshape((nch,1,1,1))
    WeightMueller=WeightMeanJonesBand.ravel()
    WeightMuellerSignal=WeightMueller*FreqsInfo["WeightChansImages"].ravel()

    #IncreaseIslandMachine=ClassIncreaseIsland.ClassIncreaseIsland()
    #ListPixData=IncreaseIslandMachine.IncreaseIsland(ListPixData,dx=5)

    # 0) Load Island info (center and square data)

    ListSquarePix_Center=ListSquarePix['IslandCenter']
    ListSquarePix_Data=ListSquarePix['IslandSquareData']
    ListSquarePix_Mask=ListSquarePix['IslandSquareMask']
    orixisland,oriyisland=ListSquarePix_Data.shape # size of the square postage stamp around island

    ListSquarePix_Data=PSF2

    xisland,yisland=ListSquarePix_Data.shape # size of the square postage stamp around island
    print(xisland)

    # 1) Shape PSF and Dirty to have even number of pixels (required by Moresane)
    # DEAL WITH SQUARE DATA OF ISLAND IF UNEVEN

    # Crop PSF to the island postage stamp
    #PSFCrop=CropPSF(PSF,xisland)
    #PSF2=CropPSF(PSF2,71)
    # MORESANE requires even sized images ==> Padding by one row and one column
    cropped_square_data_to_even = False
    if xisland % 2 != 0:
        #    PSFCrop_even = np.zeros((xisland+1, xisland+1))
        #    PSFCrop_even[:-1, :-1] = np.squeeze(PSFCrop)
        Dirty_even = np.zeros((xisland - 1, xisland - 1))
        Dirty_even[:, :] = ListSquarePix_Data[:-1, :-1]
        cropped_square_data_to_even = True
    else:
        Dirty_even = ListSquarePix_Data
    # make it even by removing one line and one column (usually outside of the interesting island region)


    # xbigdirty,ybigdirty=np.squeeze(Dirty).shape
    # if xbigdirty % 2 != 0:
    #     Dirty_even=np.zeros((xbigdirty-1,xbigdirty-1))
    #     Dirty_even[:,:]=np.squeeze(Dirty)[:-1,:-1]

    xbigpsf,ybigpsf=PSF2.shape
    cropped_square_psf_to_even = False
    if xbigpsf % 2 != 0:
        PSF2_even=np.zeros((xbigpsf-1,xbigpsf-1))
        PSF2_even[:,:]=PSF2[:-1,:-1]
        cropped_square_data_to_even = True
    else:
        PSF2_even=PSF2

    # 2) Run the actual MinorCycle algo
    DictMoresaneParms=GD['MORESANE']
    Moresane=ClassMoresane(Dirty_even,PSF2_even,DictMoresaneParms,GD=GD)

    Model_Square=Moresane.main()

    # 3) Apply Island mask to model to get rid of regions outside the island.

    cropped_square_to_even = False
    if cropped_square_data_to_even:  # then restore the model to its original uneven dimension
        Model_Square_uneven = np.zeros((xisland, xisland))
        Model_Square_uneven[:-1, :-1] = Model_Square
        Model_Square = Model_Square_uneven

    if cropped_square_psf_to_even: # restore original PSF size
        PSF_uneven=PSF2

    Model_Square=CropPSF(Model_Square, orixisland)
    Model_Square *= ListSquarePix_Mask  # masking outside the island

    # 4) Convert back to Island format ( "S" and ThisPixList )
    NewModel, NewThisPixList = SquareIslandtoIsland(Model_Square, ThisSquarePixList, ThisPixList)

    Model = NewModel
    ThisPixList = NewThisPixList

    return Model
Ejemplo n.º 14
0
def main(OP=None, messages=[]):
    if OP is None:
        OP = MyPickle.Load(SaveFile)
        print "Using settings from %s, then command line." % SaveFile

    DicoConfig = OP.DicoConfig

    ImageName = DicoConfig["Output"]["Name"]
    if not ImageName:
        raise Exceptions.UserInputError(
            "--Output-Name not specified, can't continue.")
    if not DicoConfig["Data"]["MS"]:
        raise Exceptions.UserInputError(
            "--Data-MS not specified, can't continue.")

    # create directory if it exists
    dirname = os.path.dirname(ImageName)
    if not os.path.exists(dirname) and not dirname == "":
        os.mkdir(dirname)

    # setup logging
    MyLogger.logToFile(ImageName + ".log", append=DicoConfig["Log"]["Append"])
    global log
    log = MyLogger.getLogger("DDFacet")

    # disable colors and progressbars if requested
    ModColor.silent = SkyModel.Other.ModColor.silent = \
                      progressbar.ProgressBar.silent = \
                      DicoConfig["Log"]["Boring"]

    if messages:
        if not DicoConfig["Log"]["Boring"]:
            #os.system('clear')
            logo.print_logo()
        for msg in messages:
            print >> log, msg

    if DicoConfig["Debug"]["Pdb"] == "always":
        print >> log, "--Debug-Pdb=always: unexpected errors will be dropped into pdb"
        Exceptions.enable_pdb_on_error(
            ModColor.Str(
                "DDFacet has encountered an unexpected error. Dropping you into pdb for a post-mortem.\n"
                +
                "(This is because you're running with --Debug-Pdb set to 'always'.)"
            ))
    elif DicoConfig["Debug"][
            "Pdb"] == "auto" and not DicoConfig["Log"]["Boring"]:
        print >> log, "--Debug-Pdb=auto and not --Log-Boring: unexpected errors will be dropped into pdb"
        Exceptions.enable_pdb_on_error(
            ModColor.Str(
                "DDFacet has encountered an unexpected error. Dropping you into pdb for a post-mortem.\n"
                +
                "(This is because you're running with --Debug-Pdb set to 'auto' and --Log-Boring is off.)"
            ))

    # print current options
    OP.Print(dest=log)

    # enable memory logging
    MyLogger.enableMemoryLogging(DicoConfig["Log"]["Memory"])

    # get rid of old shm arrays from previous runs
    Multiprocessing.cleanupStaleShm()

    # initialize random seed from config if set, or else from system time
    if DicoConfig["Misc"]["RandomSeed"] is not None:
        print >> log, "random seed=%d (explicit)" % DicoConfig["Misc"][
            "RandomSeed"]
    else:
        DicoConfig["Misc"]["RandomSeed"] = int(time.time())
        print >> log, "random seed=%d (automatic)" % DicoConfig["Misc"][
            "RandomSeed"]
    np.random.seed(DicoConfig["Misc"]["RandomSeed"])

    # init NCPU for different bits of parallelism
    ncpu = DicoConfig["Parallel"]["NCPU"] or psutil.cpu_count()
    DicoConfig["Parallel"]["NCPU"] = ncpu
    _pyArrays.pySetOMPNumThreads(ncpu)
    NpParallel.NCPU_global = ModFFTW.NCPU_global = ncpu
    numexpr.set_num_threads(ncpu)
    print >> log, "using up to %d CPUs for parallelism" % ncpu

    # write parset
    OP.ToParset("%s.parset" % ImageName)

    Mode = DicoConfig["Output"]["Mode"]

    # init semaphores, as they're needed for weight calculation too
    ClassFacetMachine.ClassFacetMachine.setup_semaphores(DicoConfig)

    # data machine initialized for all cases except PSF-only mode
    # psf machine initialized for all cases except Predict-only mode
    Imager = ClassDeconvMachine.ClassImagerDeconv(
        GD=DicoConfig,
        BaseName=ImageName,
        predict_only=(Mode == "Predict" or Mode == "Subtract"),
        data=(Mode != "PSF"),
        psf=(Mode != "Predict" and Mode != "Dirty" and Mode != "Subtract"),
        readcol=(Mode != "Predict" and Mode != "PSF"),
        deconvolve=("Clean" in Mode))

    Imager.Init()

    # Imager.testDegrid()
    # stop
    if "Predict" in Mode or "Subtract" in Mode:
        Imager.GivePredict()
    if "Clean" in Mode:
        Imager.main()
    elif "Dirty" in Mode:
        sparsify = DicoConfig["Comp"]["Sparsification"]
        if sparsify and isinstance(sparsify, list):
            sparsify = sparsify[0]
        Imager.GiveDirty(psf="PSF" in Mode, sparsify=sparsify)
    elif "PSF" in Mode:
        sparsify = DicoConfig["Comp"]["Sparsification"]
        if sparsify and isinstance(sparsify, list):
            sparsify = sparsify[0]
        Imager.MakePSF(sparsify=sparsify)
    elif "RestoreAndShift" == Mode:
        Imager.RestoreAndShift()
Ejemplo n.º 15
0
def test2():
    Obj, ValObj = MyPickle.Load("test")
    PrintOptParse(Obj, ValObj, RejectGroup=["CohJones"])
Ejemplo n.º 16
0
 def FromFile(self,FileName):
     print("Reading dico model from file %s"%FileName, file=log)
     self.DicoSMStacked=MyPickle.Load(FileName)
     self.FromDico(self.DicoSMStacked)