예제 #1
0
        private static void ReconstructRandom(MeasurementData input, GriddingConstants c, float[,] psf, int blockSize, int iterCount, string file)
        {
            var cutFactor   = 8;
            var totalSize   = new Rectangle(0, 0, c.GridSize, c.GridSize);
            var psfCut      = PSF.Cut(psf, cutFactor);
            var maxSidelobe = PSF.CalcMaxSidelobe(psf, cutFactor);

            var maxLipschitzCut = PSF.CalcMaxLipschitz(psfCut);
            var lambda          = (float)(LAMBDA * PSF.CalcMaxLipschitz(psfCut));
            var lambdaTrue      = (float)(LAMBDA * PSF.CalcMaxLipschitz(psf));
            var alpha           = ALPHA;

            ApproxFast.LAMBDA_TEST = lambdaTrue;
            ApproxFast.ALPHA_TEST  = alpha;

            var metadata = Partitioner.CreatePartition(c, input.UVW, input.Frequencies);

            var random         = new Random(123);
            var approx         = new ApproxFast(totalSize, psfCut, 8, blockSize, 0.0f, 0.0f, false, true, false);
            var bMapCalculator = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psfCut, totalSize), new Rectangle(0, 0, psfCut.GetLength(0), psfCut.GetLength(1)));
            var data           = new ApproxFast.TestingData(new StreamWriter(file + "_tmp.txt"));
            var xImage         = new float[c.GridSize, c.GridSize];
            var xCorr          = Copy(xImage);
            var residualVis    = input.Visibilities;

            var dirtyGrid  = IDG.GridW(c, metadata, residualVis, input.UVW, input.Frequencies);
            var dirtyImage = FFT.WStackIFFTFloat(dirtyGrid, c.VisibilitiesCount);

            FFT.Shift(dirtyImage);

            var maxDirty         = Residuals.GetMax(dirtyImage);
            var bMap             = bMapCalculator.Convolve(dirtyImage);
            var maxB             = Residuals.GetMax(bMap);
            var correctionFactor = Math.Max(maxB / (maxDirty * maxLipschitzCut), 1.0f);
            var currentSideLobe  = maxB * maxSidelobe * correctionFactor;
            var currentLambda    = (float)Math.Max(currentSideLobe / alpha, lambda);

            var gCorr  = new float[c.GridSize, c.GridSize];
            var shared = new ApproxFast.SharedData(currentLambda, alpha, 1, 1, 8, CountNonZero(psfCut), approx.psf2, approx.aMap, xImage, xCorr, bMap, gCorr, new Random());

            shared.ActiveSet               = ApproxFast.GetActiveSet(xImage, bMap, shared.YBlockSize, shared.XBlockSize, lambda, alpha, shared.AMap);
            shared.BlockLock               = new int[shared.ActiveSet.Count];
            shared.maxLipschitz            = (float)PSF.CalcMaxLipschitz(psfCut);
            shared.MaxConcurrentIterations = 1000;
            approx.DeconvolveConcurrentTest(data, 0, 0, 0.0, shared, 1, 1e-5f, Copy(xImage), dirtyImage, psfCut, psf);
            var output = Tools.LMC.CutN132Remnant(xImage);

            Tools.WriteToMeltCSV(output.Item1, file + "_1k.csv", output.Item2, output.Item3);
            FitsIO.Write(output.Item1, file + "_1k.fits");
            FitsIO.Write(xImage, file + "_1k2.fits");

            approx.DeconvolveConcurrentTest(data, 0, 0, 0.0, shared, iterCount, 1e-5f, Copy(xImage), dirtyImage, psfCut, psf);
            output = Tools.LMC.CutN132Remnant(xImage);
            Tools.WriteToMeltCSV(output.Item1, file + "_10k.csv", output.Item2, output.Item3);
            FitsIO.Write(output.Item1, file + "_10k.fits");
            FitsIO.Write(xImage, file + "_10k2.fits");
        }
        public ApproxFast(Rectangle totalSize, float[,] psf, int threadCount, int blockSize, float randomFraction, float searchFraction, bool useCDColdStart, bool useAcceleration = true, bool useRestarting = true)
        {
            this.totalSize = totalSize;
            this.psf       = psf;
            this.psf2      = PSF.CalcPSFSquared(psf);
            MaxLipschitz   = (float)PSF.CalcMaxLipschitz(psf);
            this.aMap      = PSF.CalcAMap(psf, totalSize);

            this.threadCount     = threadCount;
            this.blockSize       = blockSize;
            this.randomFraction  = randomFraction;
            this.searchFraction  = searchFraction;
            this.useAcceleration = useAcceleration;
            this.useRestarting   = useRestarting;
        }
        public void ISTAStep(float[,] xImage, float[,] residuals, float[,] psf, float lambda, float alpha)
        {
            var xOld       = Copy(xImage);
            var corrKernel = PSF.CalcPaddedFourierCorrelation(psf, new Rectangle(0, 0, residuals.GetLength(0), residuals.GetLength(1)));
            var gradients  = Residuals.CalcGradientMap(residuals, corrKernel, new Rectangle(0, 0, psf.GetLength(0), psf.GetLength(1)));

            var lipschitz = (float)PSF.CalcMaxLipschitz(psf) * xImage.Length;

            for (int i = 0; i < xImage.GetLength(0); i++)
            {
                for (int j = 0; j < xImage.GetLength(1); j++)
                {
                    var tmp = gradients[i, j] + xImage[i, j] * lipschitz;
                    tmp          = ElasticNet.ProximalOperator(tmp, lipschitz, lambda, alpha);
                    xImage[i, j] = tmp;
                }
            }

            //update residuals
            for (int i = 0; i < xImage.GetLength(0); i++)
            {
                for (int j = 0; j < xImage.GetLength(1); j++)
                {
                    xOld[i, j] = xImage[i, j] - xOld[i, j];
                }
            }

            var convKernel          = PSF.CalcPaddedFourierConvolution(psf, new Rectangle(0, 0, residuals.GetLength(0), residuals.GetLength(1)));
            var residualsCalculator = new PaddedConvolver(convKernel, new Rectangle(0, 0, psf.GetLength(0), psf.GetLength(1)));

            residualsCalculator.ConvolveInPlace(xOld);
            for (int i = 0; i < xImage.GetLength(0); i++)
            {
                for (int j = 0; j < xImage.GetLength(1); j++)
                {
                    residuals[i, j] -= xOld[i, j];
                }
            }
        }
        public static float[,] Reconstruct(Intracommunicator comm, DistributedData.LocalDataset local, GriddingConstants c, int maxCycle, float lambda, float alpha, int iterPerCycle = 1000, bool usePathDeconvolution = false)
        {
            var watchTotal    = new Stopwatch();
            var watchForward  = new Stopwatch();
            var watchBackward = new Stopwatch();
            var watchDeconv   = new Stopwatch();

            watchTotal.Start();

            var metadata = Partitioner.CreatePartition(c, local.UVW, local.Frequencies);

            var patchSize = CalculateLocalImageSection(comm.Rank, comm.Size, c.GridSize, c.GridSize);
            var totalSize = new Rectangle(0, 0, c.GridSize, c.GridSize);

            //calculate psf and prepare for correlation in the Fourier space
            var psf = CalculatePSF(comm, c, metadata, local.UVW, local.Flags, local.Frequencies);

            Complex[,] PsfCorrelation = null;
            var maxSidelobe = PSF.CalcMaxSidelobe(psf);

            lambda = (float)(lambda * PSF.CalcMaxLipschitz(psf));

            StreamWriter writer = null;

            if (comm.Rank == 0)
            {
                FitsIO.Write(psf, "psf.fits");
                Console.WriteLine("done PSF gridding ");
                PsfCorrelation = PSF.CalcPaddedFourierCorrelation(psf, totalSize);
                writer         = new StreamWriter(comm.Size + "runtimestats.txt");
            }

            var deconvovler = new MPIGreedyCD(comm, totalSize, patchSize, psf);

            var residualVis = local.Visibilities;
            var xLocal      = new float[patchSize.YEnd - patchSize.Y, patchSize.XEnd - patchSize.X];


            for (int cycle = 0; cycle < maxCycle; cycle++)
            {
                if (comm.Rank == 0)
                {
                    Console.WriteLine("cycle " + cycle);
                }
                var dirtyImage = ForwardCalculateB(comm, c, metadata, residualVis, local.UVW, local.Frequencies, PsfCorrelation, psf, maxSidelobe, watchForward);

                var bLocal = GetImgSection(dirtyImage.Image, patchSize);

                MPIGreedyCD.Statistics lastRun;
                if (usePathDeconvolution)
                {
                    var currentLambda = Math.Max(1.0f / alpha * dirtyImage.MaxSidelobeLevel, lambda);
                    lastRun = deconvovler.DeconvolvePath(xLocal, bLocal, currentLambda, 4.0f, alpha, 5, iterPerCycle, 2e-5f);
                }
                else
                {
                    lastRun = deconvovler.Deconvolve(xLocal, bLocal, lambda, alpha, iterPerCycle, 1e-5f);
                }

                if (comm.Rank == 0)
                {
                    WriteToFile(cycle, lastRun, writer);
                    if (lastRun.Converged)
                    {
                        Console.WriteLine("-----------------------------CONVERGED!!!!------------------------");
                    }
                    else
                    {
                        Console.WriteLine("-------------------------------not converged----------------------");
                    }
                }
                comm.Barrier();
                if (comm.Rank == 0)
                {
                    watchDeconv.Stop();
                }

                float[][,] totalX = null;
                comm.Gather(xLocal, 0, ref totalX);
                Complex[,] modelGrid = null;
                if (comm.Rank == 0)
                {
                    watchBackward.Start();
                    var x = new float[c.GridSize, c.GridSize];
                    StitchImage(totalX, x, comm.Size);
                    FitsIO.Write(x, "xImage_" + cycle + ".fits");
                    FFT.Shift(x);
                    modelGrid = FFT.Forward(x);
                }
                comm.Broadcast(ref modelGrid, 0);

                var modelVis = IDG.DeGrid(c, metadata, modelGrid, local.UVW, local.Frequencies);
                residualVis = Visibilities.Substract(local.Visibilities, modelVis, local.Flags);
            }
            writer.Close();

            float[][,] gatherX = null;
            comm.Gather(xLocal, 0, ref gatherX);
            float[,] reconstructed = null;
            if (comm.Rank == 0)
            {
                reconstructed = new float[c.GridSize, c.GridSize];;
                StitchImage(gatherX, reconstructed, comm.Size);
            }

            return(reconstructed);
        }
        private static ReconstructionInfo ReconstructGradientApprox(Data input, float[,] fullPsf, string folder, int cutFactor, int maxMajor, string dirtyPrefix, string xImagePrefix, StreamWriter writer, double objectiveCutoff, float epsilon)
        {
            var info            = new ReconstructionInfo();
            var psfCut          = PSF.Cut(fullPsf, cutFactor);
            var maxSidelobe     = PSF.CalcMaxSidelobe(fullPsf, cutFactor);
            var totalSize       = new Rectangle(0, 0, input.c.GridSize, input.c.GridSize);
            var psfBMap         = psfCut;
            var bMapCalculator  = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psfBMap, totalSize), new Rectangle(0, 0, psfBMap.GetLength(0), psfBMap.GetLength(1)));
            var bMapCalculator2 = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(fullPsf, totalSize), new Rectangle(0, 0, fullPsf.GetLength(0), fullPsf.GetLength(1)));
            var fastCD          = new FastSerialCD(totalSize, psfCut);
            var fastCD2         = new FastSerialCD(totalSize, psfCut);

            fastCD2.ResetLipschitzMap(fullPsf);
            FitsIO.Write(psfCut, folder + cutFactor + "psf.fits");

            var lambda     = LAMBDA_GLOBAL * fastCD.MaxLipschitz;
            var lambdaTrue = (float)(LAMBDA_GLOBAL * PSF.CalcMaxLipschitz(fullPsf));

            var xImage      = new float[input.c.GridSize, input.c.GridSize];
            var residualVis = input.visibilities;
            DeconvolutionResult lastResult = null;
            var firstTimeConverged         = false;
            var lastLambda = 0.0f;

            for (int cycle = 0; cycle < maxMajor; cycle++)
            {
                Console.WriteLine("cycle " + cycle);
                var dirtyGrid  = IDG.GridW(input.c, input.metadata, residualVis, input.uvw, input.frequencies);
                var dirtyImage = FFT.WStackIFFTFloat(dirtyGrid, input.c.VisibilitiesCount);
                FFT.Shift(dirtyImage);
                FitsIO.Write(dirtyImage, folder + dirtyPrefix + cycle + ".fits");

                //calc data and reg penalty
                var dataPenalty       = Residuals.CalcPenalty(dirtyImage);
                var regPenalty        = ElasticNet.CalcPenalty(xImage, lambdaTrue, alpha);
                var regPenaltyCurrent = ElasticNet.CalcPenalty(xImage, lambda, alpha);
                info.lastDataPenalty = dataPenalty;
                info.lastRegPenalty  = regPenalty;

                var maxDirty = Residuals.GetMax(dirtyImage);
                var bMap     = bMapCalculator.Convolve(dirtyImage);
                FitsIO.Write(bMap, folder + dirtyPrefix + "bmap_" + cycle + ".fits");
                var maxB             = Residuals.GetMax(bMap);
                var correctionFactor = Math.Max(maxB / (maxDirty * fastCD.MaxLipschitz), 1.0f);
                var currentSideLobe  = maxB * maxSidelobe * correctionFactor;
                var currentLambda    = Math.Max(currentSideLobe / alpha, lambda);

                writer.Write(cycle + ";" + currentLambda + ";" + currentSideLobe + ";" + ";" + fastCD2.GetAbsMaxDiff(xImage, bMap, lambdaTrue, alpha) + ";" + dataPenalty + ";" + regPenalty + ";" + regPenaltyCurrent + ";");;
                writer.Flush();

                //check wether we can minimize the objective further with the current psf
                var objectiveReached = (dataPenalty + regPenalty) < objectiveCutoff;
                var minimumReached   = (lastResult != null && lastResult.Converged && fastCD2.GetAbsMaxDiff(xImage, dirtyImage, lambdaTrue, alpha) < MAJOR_EPSILON && currentLambda == lambda);
                if (lambda == lastLambda & !firstTimeConverged)
                {
                    firstTimeConverged = true;
                    minimumReached     = false;
                }

                if (!objectiveReached & !minimumReached)
                {
                    //writer.Write(firstTimeConverged + ";");
                    //writer.Flush();
                    info.totalDeconv.Start();
                    if (!firstTimeConverged)
                    {
                        lastResult = fastCD.Deconvolve(xImage, bMap, currentLambda, alpha, 30000, epsilon);
                    }
                    else
                    {
                        bMap = bMapCalculator2.Convolve(dirtyImage);
                        //FitsIO.Write(bMap, folder + dirtyPrefix + "bmap_" + cycle + "_full.fits");
                        maxB             = Residuals.GetMax(bMap);
                        correctionFactor = Math.Max(maxB / (maxDirty * fastCD2.MaxLipschitz), 1.0f);
                        currentSideLobe  = maxB * maxSidelobe * correctionFactor;
                        currentLambda    = Math.Max(currentSideLobe / alpha, lambdaTrue);
                        info.totalDeconv.Start();
                        lastResult = fastCD.Deconvolve(xImage, bMap, currentLambda, alpha, 30000, epsilon);
                        info.totalDeconv.Stop();
                    }

                    info.totalDeconv.Stop();

                    FitsIO.Write(xImage, folder + xImagePrefix + cycle + ".fits");
                    writer.Write(lastResult.Converged + ";" + lastResult.IterationCount + ";" + lastResult.ElapsedTime.TotalSeconds + "\n");
                    writer.Flush();

                    FFT.Shift(xImage);
                    var xGrid = FFT.Forward(xImage);
                    FFT.Shift(xImage);
                    var modelVis = IDG.DeGridW(input.c, input.metadata, xGrid, input.uvw, input.frequencies);
                    residualVis = Visibilities.Substract(input.visibilities, modelVis, input.flags);
                }
                else
                {
                    writer.Write(false + ";0;0\n");
                    writer.Flush();

                    break;
                }

                lastLambda = currentLambda;
            }

            bMapCalculator.Dispose();
            bMapCalculator2.Dispose();

            return(info);
        }
        public static void RunApproximationMethods()
        {
            var folder     = @"C:\dev\GitHub\p9-data\large\fits\meerkat_tiny\";
            var data       = LMC.Load(folder);
            var rootFolder = Directory.GetCurrentDirectory();

            var maxW = 0.0;

            for (int i = 0; i < data.uvw.GetLength(0); i++)
            {
                for (int j = 0; j < data.uvw.GetLength(1); j++)
                {
                    maxW = Math.Max(maxW, Math.Abs(data.uvw[i, j, 2]));
                }
            }
            maxW = Partitioner.MetersToLambda(maxW, data.frequencies[data.frequencies.Length - 1]);

            var visCount2 = 0;

            for (int i = 0; i < data.flags.GetLength(0); i++)
            {
                for (int j = 0; j < data.flags.GetLength(1); j++)
                {
                    for (int k = 0; k < data.flags.GetLength(2); k++)
                    {
                        if (!data.flags[i, j, k])
                        {
                            visCount2++;
                        }
                    }
                }
            }
            var    visibilitiesCount = visCount2;
            int    gridSize          = 3072;
            int    subgridsize       = 32;
            int    kernelSize        = 16;
            int    max_nr_timesteps  = 1024;
            double cellSize          = 1.5 / 3600.0 * PI / 180.0;
            int    wLayerCount       = 24;
            double wStep             = maxW / (wLayerCount);

            data.c                 = new GriddingConstants(visibilitiesCount, gridSize, subgridsize, kernelSize, max_nr_timesteps, (float)cellSize, wLayerCount, wStep);
            data.metadata          = Partitioner.CreatePartition(data.c, data.uvw, data.frequencies);
            data.visibilitiesCount = visibilitiesCount;

            var psfVis = new Complex[data.uvw.GetLength(0), data.uvw.GetLength(1), data.frequencies.Length];

            for (int i = 0; i < data.visibilities.GetLength(0); i++)
            {
                for (int j = 0; j < data.visibilities.GetLength(1); j++)
                {
                    for (int k = 0; k < data.visibilities.GetLength(2); k++)
                    {
                        if (!data.flags[i, j, k])
                        {
                            psfVis[i, j, k] = new Complex(1.0, 0);
                        }
                        else
                        {
                            psfVis[i, j, k] = new Complex(0, 0);
                        }
                    }
                }
            }

            Console.WriteLine("gridding psf");
            var psfGrid = IDG.GridW(data.c, data.metadata, psfVis, data.uvw, data.frequencies);
            var psf     = FFT.WStackIFFTFloat(psfGrid, data.c.VisibilitiesCount);

            FFT.Shift(psf);

            Directory.CreateDirectory("PSFSizeExperimentLarge");
            Directory.SetCurrentDirectory("PSFSizeExperimentLarge");
            FitsIO.Write(psf, "psfFull.fits");

            Console.WriteLine(PSF.CalcMaxLipschitz(psf));
            Console.WriteLine(visCount2);

            //reconstruct with full psf and find reference objective value
            var fileHeader         = "cycle;lambda;sidelobe;maxPixel;dataPenalty;regPenalty;currentRegPenalty;converged;iterCount;ElapsedTime";
            var objectiveCutoff    = REFERENCE_L2_PENALTY + REFERENCE_ELASTIC_PENALTY;
            var recalculateFullPSF = true;

            if (recalculateFullPSF)
            {
                ReconstructionInfo referenceInfo = null;
                using (var writer = new StreamWriter("1Psf.txt", false))
                {
                    writer.WriteLine(fileHeader);
                    referenceInfo = ReconstructSimple(data, psf, "", 1, 12, "dirtyReference", "xReference", writer, 0.0, 1e-5f, false);
                    File.WriteAllText("1PsfTotal.txt", referenceInfo.totalDeconv.Elapsed.ToString());
                }
                objectiveCutoff = referenceInfo.lastDataPenalty + referenceInfo.lastRegPenalty;
            }

            //tryout with simply cutting the PSF
            ReconstructionInfo experimentInfo = null;
            var psfCuts   = new int[] { 16, 32 };
            var outFolder = "cutPsf";

            Directory.CreateDirectory(outFolder);
            outFolder += @"\";
            foreach (var cut in psfCuts)
            {
                using (var writer = new StreamWriter(outFolder + cut + "Psf.txt", false))
                {
                    writer.WriteLine(fileHeader);
                    experimentInfo = ReconstructSimple(data, psf, outFolder, cut, 12, cut + "dirty", cut + "x", writer, 0.0, 1e-5f, false);
                    File.WriteAllText(outFolder + cut + "PsfTotal.txt", experimentInfo.totalDeconv.Elapsed.ToString());
                }
            }

            //Tryout with cutting the PSF, but starting from the true bMap
            outFolder = "cutPsf2";
            Directory.CreateDirectory(outFolder);
            outFolder += @"\";
            foreach (var cut in psfCuts)
            {
                using (var writer = new StreamWriter(outFolder + cut + "Psf.txt", false))
                {
                    writer.WriteLine(fileHeader);
                    experimentInfo = ReconstructSimple(data, psf, outFolder, cut, 12, cut + "dirty", cut + "x", writer, 0.0, 1e-5f, true);
                    File.WriteAllText(outFolder + cut + "PsfTotal.txt", experimentInfo.totalDeconv.Elapsed.ToString());
                }
            }

            //combined, final solution. Cut the psf in half, optimize until convergence, and then do one more major cycle with the second method
            outFolder = "properSolution";
            Directory.CreateDirectory(outFolder);
            outFolder += @"\";
            foreach (var cut in psfCuts)
            {
                using (var writer = new StreamWriter(outFolder + cut + "Psf.txt", false))
                {
                    writer.WriteLine(fileHeader);
                    experimentInfo = ReconstructGradientApprox(data, psf, outFolder, cut, 12, cut + "dirty", cut + "x", writer, 0.0, 1e-5f);
                    File.WriteAllText(outFolder + cut + "PsfTotal.txt", experimentInfo.totalDeconv.Elapsed.ToString());
                }
            }

            Directory.SetCurrentDirectory(rootFolder);
        }
        public bool DeconvolveApprox(float[,] xImage, float[,] residuals, float[,] psf, float lambda, float alpha, Random random, int blockSize, int threadCount, int maxIteration = 100, float epsilon = 1e-4f, bool coldStart = false)
        {
            var xExplore    = Copy(xImage);
            var xCorrection = new float[xImage.GetLength(0), xImage.GetLength(1)];

            //calculate gradients for each pixel
            var PSFCorr     = PSF.CalcPaddedFourierCorrelation(psf, new Rectangle(0, 0, residuals.GetLength(0), residuals.GetLength(1)));
            var gExplore    = Residuals.CalcGradientMap(residuals, PSFCorr, new Rectangle(0, 0, psf.GetLength(0), psf.GetLength(1)));
            var gCorrection = new float[residuals.GetLength(0), residuals.GetLength(1)];
            var psf2        = PSF.CalcPSFSquared(psf);

            if (coldStart)
            {
                var rec    = new Rectangle(0, 0, xImage.GetLength(0), xImage.GetLength(1));
                var fastCD = new FastSerialCD(rec, rec, psf, psf2);
                fastCD.Deconvolve(xExplore, gExplore, lambda, alpha, xImage.GetLength(0));
            }

            yBlockSize           = blockSize;
            xBlockSize           = blockSize;
            degreeOfSeperability = CountNonZero(psf);
            tau = threadCount; //number of processors
            var maxLipschitz = (float)PSF.CalcMaxLipschitz(psf);
            var activeSet    = GetActiveSet(xExplore, gExplore, lambda, alpha, maxLipschitz);

            var theta = DeconvolveAccelerated(xExplore, xCorrection, gExplore, gCorrection, psf2, ref activeSet, maxLipschitz, lambda, alpha, random, maxIteration, epsilon);

            var theta0   = tau / (float)activeSet.Count;
            var tmpTheta = theta < 1.0f ? ((theta * theta) / (1.0f - theta)) : theta0;

            for (int i = 0; i < xImage.GetLength(0); i++)
            {
                for (int j = 0; j < xImage.GetLength(1); j++)
                {
                    xCorrection[i, j] = tmpTheta * xCorrection[i, j] + xExplore[i, j];
                }
            }

            var objectives = CalcObjectives(xImage, residuals, psf, xExplore, xCorrection, lambda, alpha);

            //decide whether we take the correction or explore version
            if (objectives.Item2 < objectives.Item1)
            {
                //correction has the lower objective than explore
                for (int i = 0; i < xImage.GetLength(0); i++)
                {
                    for (int j = 0; j < xImage.GetLength(1); j++)
                    {
                        xImage[i, j] = xCorrection[i, j];
                    }
                }
            }
            else
            {
                for (int i = 0; i < xImage.GetLength(0); i++)
                {
                    for (int j = 0; j < xImage.GetLength(1); j++)
                    {
                        xImage[i, j] = xExplore[i, j];
                    }
                }
            }

            return(objectives.Item2 < objectives.Item1);
        }
        private static void ReconstructMinorCycle(MeasurementData input, GriddingConstants c, int cutFactor, float[,] fullPsf, string folder, string file, int minorCycles, float searchPercent, bool useAccelerated = true, int blockSize = 1, int maxCycle = 6)
        {
            var metadata = Partitioner.CreatePartition(c, input.UVW, input.Frequencies);

            var totalSize    = new Rectangle(0, 0, c.GridSize, c.GridSize);
            var psfCut       = PSF.Cut(fullPsf, cutFactor);
            var maxSidelobe  = PSF.CalcMaxSidelobe(fullPsf, cutFactor);
            var sidelobeHalf = PSF.CalcMaxSidelobe(fullPsf, 2);
            var random       = new Random(123);
            var approx       = new ApproxFast(totalSize, psfCut, 8, blockSize, 0.1f, searchPercent, false, useAccelerated);

            using (var bMapCalculator = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psfCut, totalSize), new Rectangle(0, 0, psfCut.GetLength(0), psfCut.GetLength(1))))
                using (var bMapCalculator2 = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(fullPsf, totalSize), new Rectangle(0, 0, fullPsf.GetLength(0), fullPsf.GetLength(1))))
                    using (var residualsConvolver = new PaddedConvolver(totalSize, fullPsf))
                    {
                        var currentBMapCalculator = bMapCalculator;

                        var maxLipschitz = PSF.CalcMaxLipschitz(psfCut);
                        var lambda       = (float)(LAMBDA * maxLipschitz);
                        var lambdaTrue   = (float)(LAMBDA * PSF.CalcMaxLipschitz(fullPsf));
                        var alpha        = ALPHA;
                        ApproxFast.LAMBDA_TEST = lambdaTrue;
                        ApproxFast.ALPHA_TEST  = alpha;

                        var switchedToOtherPsf = false;
                        var writer             = new StreamWriter(folder + "/" + file + "_lambda.txt");
                        var data        = new ApproxFast.TestingData(new StreamWriter(folder + "/" + file + ".txt"));
                        var xImage      = new float[c.GridSize, c.GridSize];
                        var residualVis = input.Visibilities;
                        for (int cycle = 0; cycle < maxCycle; cycle++)
                        {
                            Console.WriteLine("cycle " + cycle);
                            var dirtyGrid  = IDG.GridW(c, metadata, residualVis, input.UVW, input.Frequencies);
                            var dirtyImage = FFT.WStackIFFTFloat(dirtyGrid, c.VisibilitiesCount);
                            FFT.Shift(dirtyImage);
                            FitsIO.Write(dirtyImage, folder + "/dirty" + cycle + ".fits");

                            var minLambda     = 0.0f;
                            var dirtyCopy     = Copy(dirtyImage);
                            var xCopy         = Copy(xImage);
                            var currentLambda = 0f;
                            //var residualsConvolver = new PaddedConvolver(PSF.CalcPaddedFourierConvolution(fullPsf, totalSize), new Rectangle(0, 0, fullPsf.GetLength(0), fullPsf.GetLength(1)));
                            for (int minorCycle = 0; minorCycle < minorCycles; minorCycle++)
                            {
                                FitsIO.Write(dirtyImage, folder + "/dirtyMinor_" + minorCycle + ".fits");
                                var maxDirty         = Residuals.GetMax(dirtyImage);
                                var bMap             = currentBMapCalculator.Convolve(dirtyImage);
                                var maxB             = Residuals.GetMax(bMap);
                                var correctionFactor = Math.Max(maxB / (maxDirty * maxLipschitz), 1.0f);
                                var currentSideLobe  = maxB * maxSidelobe * correctionFactor;
                                currentLambda = (float)Math.Max(currentSideLobe / alpha, lambda);

                                if (minorCycle == 0)
                                {
                                    minLambda = (float)(maxB * sidelobeHalf * correctionFactor / alpha);
                                }

                                if (currentLambda < minLambda)
                                {
                                    currentLambda = minLambda;
                                }

                                writer.WriteLine(cycle + ";" + minorCycle + ";" + currentLambda + ";" + minLambda);
                                writer.Flush();
                                approx.DeconvolveTest(data, cycle, minorCycle, xImage, dirtyImage, psfCut, fullPsf, currentLambda, alpha, random, 15, 1e-5f);
                                FitsIO.Write(xImage, folder + "/xImageMinor_" + minorCycle + ".fits");

                                if (currentLambda == lambda | currentLambda == minLambda)
                                {
                                    break;
                                }

                                Console.WriteLine("resetting residuals!!");
                                //reset dirtyImage with full PSF
                                var residualsUpdate = new float[xImage.GetLength(0), xImage.GetLength(1)];
                                Parallel.For(0, xCopy.GetLength(0), (i) =>
                                {
                                    for (int j = 0; j < xCopy.GetLength(1); j++)
                                    {
                                        residualsUpdate[i, j] = xImage[i, j] - xCopy[i, j];
                                    }
                                });
                                residualsConvolver.ConvolveInPlace(residualsUpdate);

                                Parallel.For(0, xCopy.GetLength(0), (i) =>
                                {
                                    for (int j = 0; j < xCopy.GetLength(1); j++)
                                    {
                                        dirtyImage[i, j] = dirtyCopy[i, j] - residualsUpdate[i, j];
                                    }
                                });
                            }

                            if (currentLambda == lambda & !switchedToOtherPsf)
                            {
                                approx.ResetAMap(fullPsf);
                                currentBMapCalculator = bMapCalculator2;
                                lambda             = lambdaTrue;
                                switchedToOtherPsf = true;
                                writer.WriteLine("switched");
                                writer.Flush();
                            }

                            FitsIO.Write(xImage, folder + "/xImage_" + cycle + ".fits");

                            FFT.Shift(xImage);
                            var xGrid = FFT.Forward(xImage);
                            FFT.Shift(xImage);
                            var modelVis = IDG.DeGridW(c, metadata, xGrid, input.UVW, input.Frequencies);
                            residualVis = Visibilities.Substract(input.Visibilities, modelVis, input.Flags);
                        }

                        writer.Close();
                    }
        }
        private static void Reconstruct(Data input, int cutFactor, float[,] fullPsf, string folder, string file, int threads, int blockSize, bool accelerated, float randomPercent, float searchPercent)
        {
            var totalSize      = new Rectangle(0, 0, input.c.GridSize, input.c.GridSize);
            var psfCut         = PSF.Cut(fullPsf, cutFactor);
            var maxSidelobe    = PSF.CalcMaxSidelobe(fullPsf, cutFactor);
            var bMapCalculator = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psfCut, totalSize), new Rectangle(0, 0, psfCut.GetLength(0), psfCut.GetLength(1)));
            var random         = new Random(123);
            var approx         = new ApproxFast(totalSize, psfCut, threads, blockSize, randomPercent, searchPercent, false, true);

            var maxLipschitzCut = PSF.CalcMaxLipschitz(psfCut);
            var lambda          = (float)(LAMBDA * PSF.CalcMaxLipschitz(psfCut));
            var lambdaTrue      = (float)(LAMBDA * PSF.CalcMaxLipschitz(fullPsf));
            var alpha           = ALPHA;

            ApproxFast.LAMBDA_TEST = lambdaTrue;
            ApproxFast.ALPHA_TEST  = alpha;

            var switchedToOtherPsf = false;
            var writer             = new StreamWriter(folder + "/" + file + "_lambda.txt");
            var data        = new ApproxFast.TestingData(new StreamWriter(folder + "/" + file + ".txt"));
            var xImage      = new float[input.c.GridSize, input.c.GridSize];
            var residualVis = input.visibilities;

            for (int cycle = 0; cycle < 7; cycle++)
            {
                Console.WriteLine("cycle " + cycle);
                var dirtyGrid  = IDG.GridW(input.c, input.metadata, residualVis, input.uvw, input.frequencies);
                var dirtyImage = FFT.WStackIFFTFloat(dirtyGrid, input.c.VisibilitiesCount);
                FFT.Shift(dirtyImage);
                FitsIO.Write(dirtyImage, folder + "/dirty" + cycle + ".fits");

                var maxDirty         = Residuals.GetMax(dirtyImage);
                var bMap             = bMapCalculator.Convolve(dirtyImage);
                var maxB             = Residuals.GetMax(bMap);
                var correctionFactor = Math.Max(maxB / (maxDirty * maxLipschitzCut), 1.0f);
                var currentSideLobe  = maxB * maxSidelobe * correctionFactor;
                var currentLambda    = (float)Math.Max(currentSideLobe / alpha, lambda);

                writer.WriteLine("cycle" + ";" + currentLambda);
                writer.Flush();

                approx.DeconvolveTest(data, cycle, 0, xImage, dirtyImage, psfCut, fullPsf, currentLambda, alpha, random, 15, 1e-5f);
                FitsIO.Write(xImage, folder + "/xImage_" + cycle + ".fits");

                if (currentLambda == lambda & !switchedToOtherPsf)
                {
                    approx.ResetAMap(fullPsf);
                    lambda             = lambdaTrue;
                    switchedToOtherPsf = true;
                    writer.WriteLine("switched");
                    writer.Flush();
                }

                FFT.Shift(xImage);
                var xGrid = FFT.Forward(xImage);
                FFT.Shift(xImage);
                var modelVis = IDG.DeGridW(input.c, input.metadata, xGrid, input.uvw, input.frequencies);
                residualVis = Visibilities.Substract(input.visibilities, modelVis, input.flags);
            }
            writer.Close();
        }
        public bool DeconvolveGreedy(float[,] xImage, float[,] residuals, float[,] psf, float lambda, float alpha, Random random, int blockSize, int threadCount, int maxIteration = 100, float epsilon = 1e-4f)
        {
            var xExplore    = Copy(xImage);
            var xCorrection = new float[xImage.GetLength(0), xImage.GetLength(1)];

            var PSFCorr = PSF.CalcPaddedFourierCorrelation(psf, new Rectangle(0, 0, residuals.GetLength(0), residuals.GetLength(1)));

            //calculate gradients for each pixel
            var gExplore    = Residuals.CalcGradientMap(residuals, PSFCorr, new Rectangle(0, 0, psf.GetLength(0), psf.GetLength(1)));
            var gCorrection = new float[residuals.GetLength(0), residuals.GetLength(1)];
            var psf2        = PSF.CalcPSFSquared(psf);

            FitsIO.Write(gExplore, "gExplore.fits");

            yBlockSize           = blockSize;
            xBlockSize           = blockSize;
            degreeOfSeperability = CountNonZero(psf);
            tau = threadCount; //number of processors
            var maxLipschitz = (float)PSF.CalcMaxLipschitz(psf);

            var theta = Greedy(xExplore, xCorrection, gExplore, gCorrection, psf2, maxLipschitz, lambda, alpha, random, maxIteration, epsilon);

            //decide which version should be taken#
            var CONVKernel          = PSF.CalcPaddedFourierConvolution(psf, new Rectangle(0, 0, residuals.GetLength(0), residuals.GetLength(1)));
            var residualsCalculator = new PaddedConvolver(CONVKernel, new Rectangle(0, 0, psf.GetLength(0), psf.GetLength(1)));
            var theta0   = tau / (float)(xExplore.Length / (yBlockSize * xBlockSize));
            var tmpTheta = theta < 1.0f ? ((theta * theta) / (1.0f - theta)) : theta0;

            //calculate residuals
            var residualsExplore     = Copy(xExplore);
            var residualsAccelerated = Copy(xExplore);

            for (int i = 0; i < xImage.GetLength(0); i++)
            {
                for (int j = 0; j < xImage.GetLength(1); j++)
                {
                    residualsExplore[i, j]     -= xImage[i, j];
                    residualsAccelerated[i, j] += tmpTheta * xCorrection[i, j] - xImage[i, j];
                    xCorrection[i, j]           = tmpTheta * xCorrection[i, j] + xExplore[i, j];
                }
            }

            FitsIO.Write(xExplore, "xExplore.fits");
            FitsIO.Write(xCorrection, "xAcc.fits");

            residualsCalculator.ConvolveInPlace(residualsExplore);
            residualsCalculator.ConvolveInPlace(residualsAccelerated);
            for (int i = 0; i < xImage.GetLength(0); i++)
            {
                for (int j = 0; j < xImage.GetLength(1); j++)
                {
                    residualsExplore[i, j]     -= residuals[i, j];
                    residualsAccelerated[i, j] -= residuals[i, j];
                }
            }

            var objectiveExplore = Residuals.CalcPenalty(residualsExplore) + ElasticNet.CalcPenalty(xExplore, lambda, alpha);
            var objectiveAcc     = Residuals.CalcPenalty(residualsAccelerated) + ElasticNet.CalcPenalty(xCorrection, lambda, alpha);

            if (objectiveAcc < objectiveExplore)
            {
                for (int i = 0; i < xImage.GetLength(0); i++)
                {
                    for (int j = 0; j < xImage.GetLength(1); j++)
                    {
                        xImage[i, j] = xCorrection[i, j];
                    }
                }
            }
            else
            {
                for (int i = 0; i < xImage.GetLength(0); i++)
                {
                    for (int j = 0; j < xImage.GetLength(1); j++)
                    {
                        xImage[i, j] = xExplore[i, j];
                    }
                }
            }

            return(objectiveAcc < objectiveExplore);
        }
예제 #11
0
        /// <summary>
        /// Major cycle implementation for the Serial CD
        /// </summary>
        /// <param name="obsName"></param>
        /// <param name="data"></param>
        /// <param name="c"></param>
        /// <param name="useGPU"></param>
        /// <param name="psfCutFactor"></param>
        /// <param name="maxMajorCycle"></param>
        /// <param name="lambda"></param>
        /// <param name="alpha"></param>
        /// <param name="deconvIterations"></param>
        /// <param name="deconvEpsilon"></param>
        public static void ReconstructSerialCD(string obsName, MeasurementData data, GriddingConstants c, bool useGPU, int psfCutFactor, int maxMajorCycle, float lambda, float alpha, int deconvIterations, float deconvEpsilon)
        {
            var metadata = Partitioner.CreatePartition(c, data.UVW, data.Frequencies);
            var psfVis   = new Complex[data.UVW.GetLength(0), data.UVW.GetLength(1), data.Frequencies.Length];

            for (int i = 0; i < data.Visibilities.GetLength(0); i++)
            {
                for (int j = 0; j < data.Visibilities.GetLength(1); j++)
                {
                    for (int k = 0; k < data.Visibilities.GetLength(2); k++)
                    {
                        if (!data.Flags[i, j, k])
                        {
                            psfVis[i, j, k] = new Complex(1.0, 0);
                        }
                        else
                        {
                            psfVis[i, j, k] = new Complex(0, 0);
                        }
                    }
                }
            }

            Console.WriteLine("gridding psf");
            var psfGrid = IDG.GridW(c, metadata, psfVis, data.UVW, data.Frequencies);
            var psf     = FFT.WStackIFFTFloat(psfGrid, c.VisibilitiesCount);

            FFT.Shift(psf);

            var totalWatch   = new Stopwatch();
            var currentWatch = new Stopwatch();

            var totalSize   = new Rectangle(0, 0, c.GridSize, c.GridSize);
            var psfCut      = PSF.Cut(psf, psfCutFactor);
            var maxSidelobe = PSF.CalcMaxSidelobe(psf, psfCutFactor);

            IDeconvolver deconvolver = null;

            if (useGPU & GPUSerialCD.IsGPUSupported())
            {
                deconvolver = new GPUSerialCD(totalSize, psfCut, 1000);
            }
            else if (useGPU & !GPUSerialCD.IsGPUSupported())
            {
                Console.WriteLine("GPU not supported by library. Switching to CPU implementation");
                deconvolver = new FastSerialCD(totalSize, psfCut);
            }
            else
            {
                deconvolver = new FastSerialCD(totalSize, psfCut);
            }

            var psfBMap = psfCut;

            using (var gCalculator = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psfBMap, totalSize), new Rectangle(0, 0, psfBMap.GetLength(0), psfBMap.GetLength(1))))
                using (var gCalculator2 = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psf, totalSize), new Rectangle(0, 0, psf.GetLength(0), psf.GetLength(1))))
                {
                    var currentGCalculator = gCalculator;
                    var maxLipschitz       = PSF.CalcMaxLipschitz(psfCut);
                    var lambdaLipschitz    = (float)(lambda * maxLipschitz);
                    var lambdaTrue         = (float)(lambda * PSF.CalcMaxLipschitz(psf));
                    var switchedToOtherPsf = false;

                    var xImage      = new float[c.GridSize, c.GridSize];
                    var residualVis = data.Visibilities;
                    DeconvolutionResult lastResult = null;
                    for (int cycle = 0; cycle < maxMajorCycle; cycle++)
                    {
                        Console.WriteLine("Beginning Major cycle " + cycle);
                        var dirtyGrid  = IDG.GridW(c, metadata, residualVis, data.UVW, data.Frequencies);
                        var dirtyImage = FFT.WStackIFFTFloat(dirtyGrid, c.VisibilitiesCount);
                        FFT.Shift(dirtyImage);
                        FitsIO.Write(dirtyImage, obsName + "_dirty_serial_majorCycle" + cycle + ".fits");

                        currentWatch.Restart();
                        totalWatch.Start();
                        var maxDirty         = Residuals.GetMax(dirtyImage);
                        var gradients        = gCalculator.Convolve(dirtyImage);
                        var maxB             = Residuals.GetMax(gradients);
                        var correctionFactor = Math.Max(maxB / (maxDirty * maxLipschitz), 1.0f);
                        var currentSideLobe  = maxB * maxSidelobe * correctionFactor;
                        var currentLambda    = (float)Math.Max(currentSideLobe / alpha, lambdaLipschitz);

                        var objective = Residuals.CalcPenalty(dirtyImage) + ElasticNet.CalcPenalty(xImage, lambdaTrue, alpha);

                        var absMax = deconvolver.GetAbsMaxDiff(xImage, gradients, lambdaTrue, alpha);

                        if (absMax >= MAJOR_EPSILON)
                        {
                            lastResult = deconvolver.Deconvolve(xImage, gradients, currentLambda, alpha, deconvIterations, deconvEpsilon);
                        }

                        if (lambda == currentLambda & !switchedToOtherPsf)
                        {
                            currentGCalculator = gCalculator2;
                            lambda             = lambdaTrue;
                            maxLipschitz       = PSF.CalcMaxLipschitz(psf);
                            switchedToOtherPsf = true;
                        }

                        FitsIO.Write(xImage, obsName + "_model_serial_majorCycle" + cycle + ".fits");

                        currentWatch.Stop();
                        totalWatch.Stop();

                        if (absMax < MAJOR_EPSILON)
                        {
                            break;
                        }

                        FFT.Shift(xImage);
                        var xGrid = FFT.Forward(xImage);
                        FFT.Shift(xImage);
                        var modelVis = IDG.DeGridW(c, metadata, xGrid, data.UVW, data.Frequencies);
                        residualVis = Visibilities.Substract(data.Visibilities, modelVis, data.Flags);
                    }

                    Console.WriteLine("Reconstruction finished in (seconds): " + totalWatch.Elapsed.TotalSeconds);
                }
        }
예제 #12
0
        /// <summary>
        /// Major cycle implemnentation for the parallel coordinate descent algorithm
        /// </summary>
        /// <param name="data"></param>
        /// <param name="c"></param>
        /// <param name="psfCutFactor"></param>
        /// <param name="maxMajorCycle"></param>
        /// <param name="maxMinorCycle"></param>
        /// <param name="lambda"></param>
        /// <param name="alpha"></param>
        /// <param name="deconvIterations"></param>
        /// <param name="deconvEpsilon"></param>
        public static void ReconstructPCDM(string obsName, MeasurementData data, GriddingConstants c, int psfCutFactor, int maxMajorCycle, int maxMinorCycle, float lambda, float alpha, int deconvIterations, float deconvEpsilon)
        {
            var metadata = Partitioner.CreatePartition(c, data.UVW, data.Frequencies);
            var psfVis   = new Complex[data.UVW.GetLength(0), data.UVW.GetLength(1), data.Frequencies.Length];

            for (int i = 0; i < data.Visibilities.GetLength(0); i++)
            {
                for (int j = 0; j < data.Visibilities.GetLength(1); j++)
                {
                    for (int k = 0; k < data.Visibilities.GetLength(2); k++)
                    {
                        if (!data.Flags[i, j, k])
                        {
                            psfVis[i, j, k] = new Complex(1.0, 0);
                        }
                        else
                        {
                            psfVis[i, j, k] = new Complex(0, 0);
                        }
                    }
                }
            }

            Console.WriteLine("gridding psf");
            var psfGrid = IDG.Grid(c, metadata, psfVis, data.UVW, data.Frequencies);
            var psf     = FFT.BackwardFloat(psfGrid, c.VisibilitiesCount);

            FFT.Shift(psf);

            var totalWatch   = new Stopwatch();
            var currentWatch = new Stopwatch();

            var totalSize    = new Rectangle(0, 0, c.GridSize, c.GridSize);
            var psfCut       = PSF.Cut(psf, psfCutFactor);
            var maxSidelobe  = PSF.CalcMaxSidelobe(psf, psfCutFactor);
            var sidelobeHalf = PSF.CalcMaxSidelobe(psf, 2);

            var pcdm = new ParallelCoordinateDescent(totalSize, psfCut, Environment.ProcessorCount, 1000);

            using (var gCalculator = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psfCut, totalSize), new Rectangle(0, 0, psfCut.GetLength(0), psfCut.GetLength(1))))
                using (var gCalculator2 = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psf, totalSize), new Rectangle(0, 0, psf.GetLength(0), psf.GetLength(1))))
                    using (var residualsConvolver = new PaddedConvolver(totalSize, psf))
                    {
                        var currentGCalculator = gCalculator;

                        var maxLipschitz    = PSF.CalcMaxLipschitz(psfCut);
                        var lambdaLipschitz = (float)(lambda * maxLipschitz);
                        var lambdaTrue      = (float)(lambda * PSF.CalcMaxLipschitz(psf));

                        var switchedToOtherPsf = false;
                        var xImage             = new float[c.GridSize, c.GridSize];
                        var residualVis        = data.Visibilities;
                        ParallelCoordinateDescent.PCDMStatistics lastResult = null;
                        for (int cycle = 0; cycle < maxMajorCycle; cycle++)
                        {
                            Console.WriteLine("Beginning Major cycle " + cycle);
                            var dirtyGrid  = IDG.GridW(c, metadata, residualVis, data.UVW, data.Frequencies);
                            var dirtyImage = FFT.WStackIFFTFloat(dirtyGrid, c.VisibilitiesCount);
                            FFT.Shift(dirtyImage);
                            FitsIO.Write(dirtyImage, obsName + "_dirty_pcdm_majorCycle" + cycle + ".fits");

                            currentWatch.Restart();
                            totalWatch.Start();

                            var breakMajor       = false;
                            var minLambda        = 0.0f;
                            var dirtyCopy        = Copy(dirtyImage);
                            var xCopy            = Copy(xImage);
                            var currentLambda    = 0f;
                            var currentObjective = 0.0;
                            var absMax           = 0.0f;
                            for (int minorCycle = 0; minorCycle < maxMinorCycle; minorCycle++)
                            {
                                Console.WriteLine("Beginning Minor Cycle " + minorCycle);
                                var maxDirty         = Residuals.GetMax(dirtyImage);
                                var bMap             = currentGCalculator.Convolve(dirtyImage);
                                var maxB             = Residuals.GetMax(bMap);
                                var correctionFactor = Math.Max(maxB / (maxDirty * maxLipschitz), 1.0f);
                                var currentSideLobe  = maxB * maxSidelobe * correctionFactor;
                                currentLambda = (float)Math.Max(currentSideLobe / alpha, lambdaLipschitz);

                                if (minorCycle == 0)
                                {
                                    minLambda = (float)(maxB * sidelobeHalf * correctionFactor / alpha);
                                }
                                if (currentLambda < minLambda)
                                {
                                    currentLambda = minLambda;
                                }
                                currentObjective = Residuals.CalcPenalty(dirtyImage) + ElasticNet.CalcPenalty(xImage, lambdaTrue, alpha);
                                absMax           = pcdm.GetAbsMax(xImage, bMap, lambdaTrue, alpha);
                                if (absMax < MAJOR_EPSILON)
                                {
                                    breakMajor = true;
                                    break;
                                }

                                lastResult = pcdm.Deconvolve(xImage, bMap, currentLambda, alpha, 40, deconvEpsilon);

                                if (currentLambda == lambda | currentLambda == minLambda)
                                {
                                    break;
                                }

                                var residualsUpdate = new float[xImage.GetLength(0), xImage.GetLength(1)];
                                Parallel.For(0, xCopy.GetLength(0), (i) =>
                                {
                                    for (int j = 0; j < xCopy.GetLength(1); j++)
                                    {
                                        residualsUpdate[i, j] = xImage[i, j] - xCopy[i, j];
                                    }
                                });
                                residualsConvolver.ConvolveInPlace(residualsUpdate);
                                Parallel.For(0, xCopy.GetLength(0), (i) =>
                                {
                                    for (int j = 0; j < xCopy.GetLength(1); j++)
                                    {
                                        dirtyImage[i, j] = dirtyCopy[i, j] - residualsUpdate[i, j];
                                    }
                                });
                            }

                            currentWatch.Stop();
                            totalWatch.Stop();

                            if (breakMajor)
                            {
                                break;
                            }
                            if (currentLambda == lambda & !switchedToOtherPsf)
                            {
                                pcdm.ResetAMap(psf);
                                currentGCalculator = gCalculator2;
                                lambda             = lambdaTrue;
                                switchedToOtherPsf = true;
                            }

                            FitsIO.Write(xImage, obsName + "_model_pcdm_majorCycle" + cycle + ".fits");

                            FFT.Shift(xImage);
                            var xGrid = FFT.Forward(xImage);
                            FFT.Shift(xImage);
                            var modelVis = IDG.DeGridW(c, metadata, xGrid, data.UVW, data.Frequencies);
                            residualVis = Visibilities.Substract(data.Visibilities, modelVis, data.Flags);
                        }

                        Console.WriteLine("Reconstruction finished in (seconds): " + totalWatch.Elapsed.TotalSeconds);
                    }
        }
예제 #13
0
        public static void Run()
        {
            var folder     = @"C:\dev\GitHub\p9-data\large\fits\meerkat_tiny\";
            var data       = LMC.Load(folder);
            var rootFolder = Directory.GetCurrentDirectory();

            var maxW = 0.0;

            for (int i = 0; i < data.uvw.GetLength(0); i++)
            {
                for (int j = 0; j < data.uvw.GetLength(1); j++)
                {
                    maxW = Math.Max(maxW, Math.Abs(data.uvw[i, j, 2]));
                }
            }
            maxW = Partitioner.MetersToLambda(maxW, data.frequencies[data.frequencies.Length - 1]);

            var visCount2 = 0;

            for (int i = 0; i < data.flags.GetLength(0); i++)
            {
                for (int j = 0; j < data.flags.GetLength(1); j++)
                {
                    for (int k = 0; k < data.flags.GetLength(2); k++)
                    {
                        if (!data.flags[i, j, k])
                        {
                            visCount2++;
                        }
                    }
                }
            }
            var    visibilitiesCount = visCount2;
            int    gridSize          = 2048;
            int    subgridsize       = 32;
            int    kernelSize        = 16;
            int    max_nr_timesteps  = 1024;
            double cellSize          = 2.0 / 3600.0 * PI / 180.0;
            int    wLayerCount       = 32;
            double wStep             = maxW / (wLayerCount);

            data.c                 = new GriddingConstants(visibilitiesCount, gridSize, subgridsize, kernelSize, max_nr_timesteps, (float)cellSize, wLayerCount, wStep);
            data.metadata          = Partitioner.CreatePartition(data.c, data.uvw, data.frequencies);
            data.visibilitiesCount = visibilitiesCount;

            var psfVis = new Complex[data.uvw.GetLength(0), data.uvw.GetLength(1), data.frequencies.Length];

            for (int i = 0; i < data.visibilities.GetLength(0); i++)
            {
                for (int j = 0; j < data.visibilities.GetLength(1); j++)
                {
                    for (int k = 0; k < data.visibilities.GetLength(2); k++)
                    {
                        if (!data.flags[i, j, k])
                        {
                            psfVis[i, j, k] = new Complex(1.0, 0);
                        }
                        else
                        {
                            psfVis[i, j, k] = new Complex(0, 0);
                        }
                    }
                }
            }

            Console.WriteLine("gridding psf");
            var psfGrid = IDG.GridW(data.c, data.metadata, psfVis, data.uvw, data.frequencies);
            var psf     = FFT.WStackIFFTFloat(psfGrid, data.c.VisibilitiesCount);

            FFT.Shift(psf);
            var objectiveCutoff = REFERENCE_L2_PENALTY + REFERENCE_ELASTIC_PENALTY;
            var actualLipschitz = (float)PSF.CalcMaxLipschitz(psf);

            Console.WriteLine("Calc Histogram");
            var histPsf     = GetHistogram(psf, 256, 0.05f);
            var experiments = new float[] { 0.5f, /*0.4f, 0.2f, 0.1f, 0.05f*/ };

            Console.WriteLine("Done Histogram");

            Directory.CreateDirectory("PSFMask");
            Directory.SetCurrentDirectory("PSFMask");
            FitsIO.Write(psf, "psfFull.fits");

            //reconstruct with full psf and find reference objective value
            ReconstructionInfo experimentInfo = null;
            var outFolder  = "";
            var fileHeader = "cycle;lambda;sidelobe;dataPenalty;regPenalty;currentRegPenalty;converged;iterCount;ElapsedTime";

            foreach (var maskPercent in experiments)
            {
                using (var writer = new StreamWriter(outFolder + maskPercent + "Psf.txt", false))
                {
                    var maskedPSF    = Common.Copy(psf);
                    var maskedPixels = MaskPSF(maskedPSF, histPsf, maskPercent);
                    writer.WriteLine(maskedPixels + ";" + maskedPixels / (double)maskedPSF.Length);
                    FitsIO.Write(maskedPSF, outFolder + maskPercent + "Psf.fits");

                    writer.WriteLine(fileHeader);
                    writer.Flush();
                    experimentInfo = Reconstruct(data, actualLipschitz, maskedPSF, outFolder, 1, 10, maskPercent + "dirty", maskPercent + "x", writer, objectiveCutoff, 1e-5f, false);
                    File.WriteAllText(outFolder + maskPercent + "PsfTotal.txt", experimentInfo.totalDeconv.Elapsed.ToString());
                }
            }

            Directory.SetCurrentDirectory(rootFolder);
        }
        private static void ReconstructPCDM(MeasurementData input, GriddingConstants c, float[,] fullPsf, string folder, string file, int minorCycles, float searchPercent, int processorCount)
        {
            var totalWatch   = new Stopwatch();
            var currentWatch = new Stopwatch();

            var totalSize    = new Rectangle(0, 0, c.GridSize, c.GridSize);
            var psfCut       = PSF.Cut(fullPsf, CUT_FACTOR_PCDM);
            var maxSidelobe  = PSF.CalcMaxSidelobe(fullPsf, CUT_FACTOR_PCDM);
            var sidelobeHalf = PSF.CalcMaxSidelobe(fullPsf, 2);
            var random       = new Random(123);
            var pcdm         = new ParallelCoordinateDescent(totalSize, psfCut, 1, 1000, searchPercent);

            var metadata = Partitioner.CreatePartition(c, input.UVW, input.Frequencies);

            using (var bMapCalculator = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psfCut, totalSize), new Rectangle(0, 0, psfCut.GetLength(0), psfCut.GetLength(1))))
                using (var bMapCalculator2 = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(fullPsf, totalSize), new Rectangle(0, 0, fullPsf.GetLength(0), fullPsf.GetLength(1))))
                    using (var residualsConvolver = new PaddedConvolver(totalSize, fullPsf))
                    {
                        var currentBMapCalculator = bMapCalculator;

                        var maxLipschitz = PSF.CalcMaxLipschitz(psfCut);
                        var lambda       = (float)(LAMBDA * maxLipschitz);
                        var lambdaTrue   = (float)(LAMBDA * PSF.CalcMaxLipschitz(fullPsf));
                        var alpha        = ALPHA;

                        var switchedToOtherPsf = false;
                        var writer             = new StreamWriter(folder + "/" + file + ".txt");
                        var xImage             = new float[c.GridSize, c.GridSize];
                        var residualVis        = input.Visibilities;
                        ParallelCoordinateDescent.PCDMStatistics lastResult = null;
                        for (int cycle = 0; cycle < 6; cycle++)
                        {
                            Console.WriteLine("Beginning Major cycle " + cycle);
                            var dirtyGrid  = IDG.GridW(c, metadata, residualVis, input.UVW, input.Frequencies);
                            var dirtyImage = FFT.WStackIFFTFloat(dirtyGrid, c.VisibilitiesCount);
                            FFT.Shift(dirtyImage);
                            FitsIO.Write(dirtyImage, folder + "/dirty" + cycle + ".fits");

                            currentWatch.Restart();
                            totalWatch.Start();

                            var breakMajor       = false;
                            var minLambda        = 0.0f;
                            var dirtyCopy        = Copy(dirtyImage);
                            var xCopy            = Copy(xImage);
                            var currentLambda    = 0f;
                            var currentObjective = 0.0;
                            var absMax           = 0.0f;
                            for (int minorCycle = 0; minorCycle < minorCycles; minorCycle++)
                            {
                                Console.WriteLine("Beginning Minor Cycle " + minorCycle);
                                var maxDirty         = Residuals.GetMax(dirtyImage);
                                var bMap             = currentBMapCalculator.Convolve(dirtyImage);
                                var maxB             = Residuals.GetMax(bMap);
                                var correctionFactor = Math.Max(maxB / (maxDirty * maxLipschitz), 1.0f);
                                var currentSideLobe  = maxB * maxSidelobe * correctionFactor;
                                currentLambda = (float)Math.Max(currentSideLobe / alpha, lambda);

                                if (minorCycle == 0)
                                {
                                    minLambda = (float)(maxB * sidelobeHalf * correctionFactor / alpha);
                                }
                                if (currentLambda < minLambda)
                                {
                                    currentLambda = minLambda;
                                }
                                currentObjective = Residuals.CalcPenalty(dirtyImage) + ElasticNet.CalcPenalty(xImage, lambdaTrue, alpha);
                                absMax           = pcdm.GetAbsMax(xImage, bMap, lambdaTrue, alpha);
                                if (absMax < MAJOR_STOP)
                                {
                                    breakMajor = true;
                                    break;
                                }

                                lastResult = pcdm.Deconvolve(xImage, bMap, currentLambda, alpha, 100, 1e-5f);

                                if (currentLambda == lambda | currentLambda == minLambda)
                                {
                                    break;
                                }

                                var residualsUpdate = new float[xImage.GetLength(0), xImage.GetLength(1)];
                                Parallel.For(0, xCopy.GetLength(0), (i) =>
                                {
                                    for (int j = 0; j < xCopy.GetLength(1); j++)
                                    {
                                        residualsUpdate[i, j] = xImage[i, j] - xCopy[i, j];
                                    }
                                });
                                residualsConvolver.ConvolveInPlace(residualsUpdate);
                                Parallel.For(0, xCopy.GetLength(0), (i) =>
                                {
                                    for (int j = 0; j < xCopy.GetLength(1); j++)
                                    {
                                        dirtyImage[i, j] = dirtyCopy[i, j] - residualsUpdate[i, j];
                                    }
                                });
                            }

                            currentWatch.Stop();
                            totalWatch.Stop();
                            writer.WriteLine(cycle + ";" + currentLambda + ";" + currentObjective + ";" + absMax + ";" + lastResult.IterationCount + ";" + totalWatch.Elapsed.TotalSeconds + ";" + currentWatch.Elapsed.TotalSeconds);
                            writer.Flush();

                            FitsIO.Write(xImage, folder + "/xImage_pcdm_" + cycle + ".fits");

                            if (breakMajor)
                            {
                                break;
                            }
                            if (currentLambda == lambda & !switchedToOtherPsf)
                            {
                                pcdm.ResetAMap(fullPsf);
                                currentBMapCalculator = bMapCalculator2;
                                lambda             = lambdaTrue;
                                switchedToOtherPsf = true;
                                writer.WriteLine("switched");
                                writer.Flush();
                            }

                            FFT.Shift(xImage);
                            var xGrid = FFT.Forward(xImage);
                            FFT.Shift(xImage);
                            var modelVis = IDG.DeGridW(c, metadata, xGrid, input.UVW, input.Frequencies);
                            residualVis = Visibilities.Substract(input.Visibilities, modelVis, input.Flags);
                        }

                        writer.Close();
                    }
        }
        private static void ReconstructSerial(MeasurementData input, GriddingConstants c, float[,] fullPsf, string folder, string file, int processorCount)
        {
            var totalWatch   = new Stopwatch();
            var currentWatch = new Stopwatch();

            var totalSize   = new Rectangle(0, 0, c.GridSize, c.GridSize);
            var psfCut      = PSF.Cut(fullPsf, CUT_FACTOR_SERIAL);
            var maxSidelobe = PSF.CalcMaxSidelobe(fullPsf, CUT_FACTOR_SERIAL);
            var fastCD      = new FastSerialCD(totalSize, psfCut, processorCount);
            var metadata    = Partitioner.CreatePartition(c, input.UVW, input.Frequencies);

            var writer  = new StreamWriter(folder + "/" + file + ".txt");
            var psfBMap = psfCut;

            using (var bMapCalculator = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(psfBMap, totalSize), new Rectangle(0, 0, psfBMap.GetLength(0), psfBMap.GetLength(1))))
                using (var bMapCalculator2 = new PaddedConvolver(PSF.CalcPaddedFourierCorrelation(fullPsf, totalSize), new Rectangle(0, 0, fullPsf.GetLength(0), fullPsf.GetLength(1))))
                {
                    var currentBMapCalculator = bMapCalculator;

                    var maxLipschitz = PSF.CalcMaxLipschitz(psfCut);
                    var lambda       = (float)(LAMBDA * maxLipschitz);
                    var lambdaTrue   = (float)(LAMBDA * PSF.CalcMaxLipschitz(fullPsf));
                    var alpha        = ALPHA;

                    var switchedToOtherPsf         = false;
                    var xImage                     = new float[c.GridSize, c.GridSize];
                    var residualVis                = input.Visibilities;
                    DeconvolutionResult lastResult = null;
                    for (int cycle = 0; cycle < 6; cycle++)
                    {
                        Console.WriteLine("cycle " + cycle);
                        var dirtyGrid  = IDG.GridW(c, metadata, residualVis, input.UVW, input.Frequencies);
                        var dirtyImage = FFT.WStackIFFTFloat(dirtyGrid, c.VisibilitiesCount);
                        FFT.Shift(dirtyImage);
                        FitsIO.Write(dirtyImage, folder + "/dirty" + cycle + ".fits");

                        currentWatch.Restart();
                        totalWatch.Start();
                        var maxDirty         = Residuals.GetMax(dirtyImage);
                        var bMap             = bMapCalculator.Convolve(dirtyImage);
                        var maxB             = Residuals.GetMax(bMap);
                        var correctionFactor = Math.Max(maxB / (maxDirty * fastCD.MaxLipschitz), 1.0f);
                        var currentSideLobe  = maxB * maxSidelobe * correctionFactor;
                        var currentLambda    = Math.Max(currentSideLobe / alpha, lambda);


                        var objective = Residuals.CalcPenalty(dirtyImage) + ElasticNet.CalcPenalty(xImage, lambdaTrue, alpha);

                        var absMax = fastCD.GetAbsMaxDiff(xImage, bMap, lambdaTrue, alpha);

                        if (absMax >= MAJOR_STOP)
                        {
                            lastResult = fastCD.Deconvolve(xImage, bMap, currentLambda, alpha, 30000, 1e-5f);
                        }

                        if (lambda == currentLambda & !switchedToOtherPsf)
                        {
                            currentBMapCalculator = bMapCalculator2;
                            lambda             = lambdaTrue;
                            switchedToOtherPsf = true;
                        }

                        currentWatch.Stop();
                        totalWatch.Stop();
                        writer.WriteLine(cycle + ";" + currentLambda + ";" + objective + ";" + absMax + ";" + lastResult.IterationCount + ";" + totalWatch.Elapsed.TotalSeconds + ";" + currentWatch.Elapsed.TotalSeconds);
                        writer.Flush();

                        if (absMax < MAJOR_STOP)
                        {
                            break;
                        }

                        FFT.Shift(xImage);
                        var xGrid = FFT.Forward(xImage);
                        FFT.Shift(xImage);
                        var modelVis = IDG.DeGridW(c, metadata, xGrid, input.UVW, input.Frequencies);
                        residualVis = Visibilities.Substract(input.Visibilities, modelVis, input.Flags);
                    }
                }
        }