예제 #1
0
파일: Program.cs 프로젝트: kryssb/SySal.NET
            public GridInterpolation(RTrackCell [,] g, double cellsize, SySal.BasicTypes.Rectangle refrect, int minmatches)
            {
                m_Grid   = g;
                CellSize = cellsize;
                RefRect  = refrect;
                SySal.BasicTypes.Vector2 c = new SySal.BasicTypes.Vector2();
                c.X        = 0.5 * (refrect.MinX + RefRect.MaxX);
                c.Y        = 0.5 * (refrect.MinY + RefRect.MaxY);
                XCells     = m_Grid.GetLength(0);
                YCells     = m_Grid.GetLength(1);
                MinMatches = minmatches;
                MaxXYCells = Math.Max(XCells, YCells);
                m_Grid2    = new RTrackCell[XCells, YCells];
                int ix, iy;

                for (ix = 0; ix < XCells; ix++)
                {
                    for (iy = 0; iy < YCells; iy++)
                    {
                        RTrackCell rrc = m_Grid[ix, iy];
                        RTrackCell rtc = new RTrackCell(rrc.Extents, c);
                        m_Grid2[ix, iy]         = rtc;
                        m_Grid2[ix, iy].Average = rtc.Center;
                        rtc.Result  = NumericalTools.ComputationResult.OK;
                        rtc.Matches = Math.Max(minmatches, rrc.Matches);
                        SySal.BasicTypes.Vector v = new SySal.BasicTypes.Vector();
                        EvaluateW(rtc.Center.X, rtc.Center.Y, ref v, ref rtc.AlignInfo);
                        rtc.SlopeAlignInfo.X = v.X;
                        rtc.SlopeAlignInfo.Y = v.Y;
                    }
                }
            }
예제 #2
0
        /// <summary>
        /// Performs multiple matching.
        /// </summary>
        /// <param name="refmap">the reference map.</param>
        /// <param name="mmaps">the list of track maps to be merged.</param>
        /// <returns>the result of pattern matching with each track pattern.</returns>
        public MapResult[] Map(SySal.Tracking.MIPEmulsionTrackInfo[] refmap, params SySal.Tracking.MIPEmulsionTrackInfo[][] mmaps)
        {
            SySal.Processing.QuickMapping.Configuration qmc = (SySal.Processing.QuickMapping.Configuration)m_QM.Config;
            qmc.FullStatistics       = !m_Config.FavorSpeedOverAccuracy;
            qmc.UseAbsoluteReference = true;
            qmc.PosTol   = m_Config.PosTol;
            qmc.SlopeTol = m_Config.SlopeTol;
            MapResult[] mres = new MapResult[mmaps.Length];

            int i;

            for (i = 0; i < mmaps.Length; i++)
            {
                SySal.Scanning.PostProcessing.PatternMatching.TrackPair [] pairs = m_QM.Match(refmap, mmaps[i], 0.0, m_Config.MaxPosOffset, m_Config.MaxPosOffset);
                mres[i].Valid = (mres[i].Matches = pairs.Length) >= m_Config.MinMatches;
                if (pairs.Length <= 0)
                {
                    mres[i].Valid = false;
                    continue;
                }
                SySal.BasicTypes.Vector2 dp = new SySal.BasicTypes.Vector2();
                SySal.BasicTypes.Vector2 dp2 = new SySal.BasicTypes.Vector2();
                SySal.BasicTypes.Vector2 ds = new SySal.BasicTypes.Vector2();
                SySal.BasicTypes.Vector2 ds2 = new SySal.BasicTypes.Vector2();
                double dx, dy;
                foreach (SySal.Scanning.PostProcessing.PatternMatching.TrackPair p in pairs)
                {
                    dx     = (p.First.Info.Intercept.X - p.Second.Info.Intercept.X);
                    dy     = (p.First.Info.Intercept.Y - p.Second.Info.Intercept.Y);
                    dp.X  += dx;
                    dp.Y  += dy;
                    dp2.X += (dx * dx);
                    dp2.Y += (dy * dy);
                    dx     = (p.First.Info.Slope.X - p.Second.Info.Slope.X);
                    dy     = (p.First.Info.Slope.Y - p.Second.Info.Slope.Y);
                    ds.X  += dx;
                    ds.Y  += dy;
                    ds2.X += (dx * dx);
                    ds2.Y += (dy * dy);
                }
                dp.X                 /= pairs.Length;
                dp.Y                 /= pairs.Length;
                dp2.X                 = Math.Sqrt(dp2.X / pairs.Length - dp.X * dp.X);
                dp2.Y                 = Math.Sqrt(dp2.Y / pairs.Length - dp.Y * dp.Y);
                ds.X                 /= pairs.Length;
                ds.Y                 /= pairs.Length;
                ds2.X                 = Math.Sqrt(ds2.X / pairs.Length - ds.X * ds.X);
                ds2.Y                 = Math.Sqrt(ds2.Y / pairs.Length - ds.Y * ds.Y);
                mres[i].DeltaPos      = dp;
                mres[i].DeltaPosRMS   = dp2;
                mres[i].DeltaSlope    = ds;
                mres[i].DeltaSlopeRMS = ds2;
            }
            return(mres);
        }
예제 #3
0
 public void Copy(ImagingConfiguration c)
 {
     Name               = c.Name;
     EmptyImage         = c.EmptyImage;
     GreyTargetMedian   = c.GreyTargetMedian;
     ThresholdImage     = c.ThresholdImage;
     MaxSegmentsPerLine = c.MaxSegmentsPerLine;
     MaxClusters        = c.MaxClusters;
     ImageWidth         = c.ImageWidth;
     ImageHeight        = c.ImageHeight;
     Pixel2Micron       = c.Pixel2Micron;
     DMagDX             = c.DMagDX;
     DMagDY             = c.DMagDY;
     DMagDZ             = c.DMagDZ;
     ZCurvature         = c.ZCurvature;
     XYCurvature        = c.XYCurvature;
     CameraRotation     = c.CameraRotation;
     XSlant             = c.XSlant;
     YSlant             = c.YSlant;
 }
예제 #4
0
파일: Program.cs 프로젝트: kryssb/SySal.NET
 public RTrackCell(SySal.BasicTypes.Rectangle rect, SySal.BasicTypes.Vector2 gencenter)
 {
     Extents  = rect;
     Center.X = 0.5 * (rect.MinX + rect.MaxX);
     Center.Y = 0.5 * (rect.MinY + rect.MaxY);
     FName    = System.Environment.GetEnvironmentVariable("TEMP");
     if (FName.EndsWith("/") == false && FName.EndsWith("\\") == false)
     {
         FName += "/";
     }
     FName       += "flattentlg_" + System.Guid.NewGuid().ToString() + ".tmp";
     TempStream   = new System.IO.FileStream(FName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite);
     Count        = 0;
     TempWrite    = new System.IO.BinaryWriter(TempStream);
     TempRead     = new System.IO.BinaryReader(TempStream);
     Sum.X        = 0.0;
     Sum.Y        = 0.0;
     Average.X    = 0.0;
     Average.Y    = 0.0;
     AlignInfo.RX = Center.X; //gencenter.X;
     AlignInfo.RY = Center.Y; //gencenter.Y;
 }
예제 #5
0
        private void Compute(bool comp_x, bool comp_y, object btn)
        {
            m_Running = true;
            EnableButtons(btn);
            m_Stop           = false;
            pbProgress.Value = 0.0;
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
            {
                try
                {
                    SySal.Processing.QuickMapping.QuickMapper QM    = new SySal.Processing.QuickMapping.QuickMapper();
                    SySal.Processing.QuickMapping.Configuration qmc = (SySal.Processing.QuickMapping.Configuration)QM.Config;
                    qmc.FullStatistics       = false;
                    qmc.UseAbsoluteReference = true;
                    qmc.PosTol   = S.PosTolerance;
                    qmc.SlopeTol = 1.0;
                    QM.Config    = qmc;
                    System.Collections.ArrayList xconv = new System.Collections.ArrayList();
                    System.Collections.ArrayList yconv = new System.Collections.ArrayList();
                    int sfi;
                    for (sfi = 0; sfi < SummaryFiles.Length; sfi++)
                    {
                        QuasiStaticAcquisition Q = new QuasiStaticAcquisition(SummaryFiles[sfi]);
                        foreach (QuasiStaticAcquisition.Sequence seq in Q.Sequences)
                        {
                            int ly;
                            SySal.Imaging.Cluster[] prevC = FilterClusters(seq.Layers[0].ReadClusters());
                            SySal.Imaging.Cluster[] nextC = null;
                            SySal.BasicTypes.Vector prevP = seq.Layers[0].Position;
                            SySal.BasicTypes.Vector nextP = new SySal.BasicTypes.Vector();
                            for (ly = 1; ly < seq.Layers.Length; ly++)
                            {
                                if (m_Stop)
                                {
                                    throw new Exception("Stopped.");
                                }
                                nextC = FilterClusters(seq.Layers[ly].ReadClusters());
                                nextP = seq.Layers[ly].Position;
                                this.Invoke(new dSetValue(SetValue), 100.0 * (((double)seq.Id + (double)(ly - 1) / (double)(seq.Layers.Length - 1)) / (double)(Q.Sequences.Length) + sfi) / SummaryFiles.Length);
                                SySal.BasicTypes.Vector2 dp   = new SySal.BasicTypes.Vector2(seq.Layers[ly].Position - seq.Layers[ly - 1].Position);
                                SySal.BasicTypes.Vector2 dp1  = dp; dp1.X /= S.MinConv; dp1.Y /= S.MinConv;
                                SySal.BasicTypes.Vector2 dp2  = dp; dp2.X /= S.MaxConv; dp2.Y /= S.MaxConv;
                                SySal.BasicTypes.Vector2 da   = new SySal.BasicTypes.Vector2(); da.X = 0.5 * (dp1.X + dp2.X); da.Y = 0.5 * (dp1.Y + dp2.Y);
                                SySal.BasicTypes.Vector2 dext = new SySal.BasicTypes.Vector2(); dext.X = Math.Abs(dp1.X - dp2.X); dext.Y = Math.Abs(dp1.Y - dp2.Y);
                                SySal.Tracking.MIPEmulsionTrackInfo[] prevmap = new SySal.Tracking.MIPEmulsionTrackInfo[prevC.Length];
                                int i;
                                for (i = 0; i < prevC.Length; i++)
                                {
                                    SySal.Tracking.MIPEmulsionTrackInfo info = new SySal.Tracking.MIPEmulsionTrackInfo();
                                    info.Intercept.X = prevC[i].X;
                                    info.Intercept.Y = prevC[i].Y;
                                    prevmap[i]       = info;
                                }
                                SySal.Tracking.MIPEmulsionTrackInfo[] nextmap = new SySal.Tracking.MIPEmulsionTrackInfo[nextC.Length];
                                for (i = 0; i < nextC.Length; i++)
                                {
                                    nextmap[i] = new SySal.Tracking.MIPEmulsionTrackInfo();
                                }
                                double[,] convopt = new double[, ] {
                                    { 1.0, 1.0 }, { -1.0, 1.0 }, { -1.0, -1.0 }, { 1.0, -1.0 }
                                };
                                int o;
                                SySal.Scanning.PostProcessing.PatternMatching.TrackPair[] bestpairs = new SySal.Scanning.PostProcessing.PatternMatching.TrackPair[0];
                                SySal.BasicTypes.Vector2 bestda = new SySal.BasicTypes.Vector2();
                                for (o = 0; o < convopt.GetLength(0); o++)
                                {
                                    try
                                    {
                                        for (i = 0; i < nextC.Length; i++)
                                        {
                                            SySal.Tracking.MIPEmulsionTrackInfo info = nextmap[i];
                                            info.Intercept.X = nextC[i].X + da.X * convopt[o, 0];
                                            info.Intercept.Y = nextC[i].Y + da.Y * convopt[o, 1];
                                            nextmap[i]       = info;
                                        }
                                        SySal.Scanning.PostProcessing.PatternMatching.TrackPair[] prs = QM.Match(prevmap, nextmap, 0.0, dext.X, dext.Y);
                                        if (prs.Length > bestpairs.Length)
                                        {
                                            bestda.X  = da.X * convopt[o, 0];
                                            bestda.Y  = da.Y * convopt[o, 1];
                                            bestpairs = prs;
                                        }
                                    }
                                    catch (Exception xc) { }
                                }

                                if (bestpairs.Length >= S.MinMatches)
                                {
                                    double[] deltas = new double[bestpairs.Length];
                                    for (i = 0; i < bestpairs.Length; i++)
                                    {
                                        deltas[i] = bestpairs[i].First.Info.Intercept.X - nextC[bestpairs[i].Second.Index].X;
                                    }
                                    bestda.X = NumericalTools.Fitting.Quantiles(deltas, new double[] { 0.5 })[0];
                                    if (bestda.X != 0.0)
                                    {
                                        double v = dp.X / bestda.X;
                                        int pos  = xconv.BinarySearch(v);
                                        if (pos < 0)
                                        {
                                            pos = ~pos;
                                        }
                                        xconv.Insert(pos, v);
                                    }
                                    for (i = 0; i < bestpairs.Length; i++)
                                    {
                                        deltas[i] = bestpairs[i].First.Info.Intercept.Y - nextC[bestpairs[i].Second.Index].Y;
                                    }
                                    bestda.Y = NumericalTools.Fitting.Quantiles(deltas, new double[] { 0.5 })[0];
                                    if (bestda.Y != 0.0)
                                    {
                                        double v = dp.Y / bestda.Y;
                                        int pos  = yconv.BinarySearch(v);
                                        if (pos < 0)
                                        {
                                            pos = ~pos;
                                        }
                                        yconv.Insert(pos, v);
                                    }
                                    if (comp_x && xconv.Count > 0)
                                    {
                                        int bmin, bmax;
                                        bmin = (int)Math.Ceiling(xconv.Count * 0.16);
                                        bmax = (int)Math.Floor(xconv.Count * 0.84);
                                        if (bmax < bmin)
                                        {
                                            bmin = bmax;
                                        }
                                        double[] sample1s = (double[])xconv.GetRange(bmin, bmax - bmin + 1).ToArray(typeof(double));
                                        XConv             = NumericalTools.Fitting.Average(sample1s);
                                        this.Invoke(new dSetConv(SetConv), new object[] { true, XConv, 0.5 * (sample1s[sample1s.Length - 1] - sample1s[0]) / Math.Sqrt(sample1s.Length) });
                                    }
                                    if (comp_y && yconv.Count > 0)
                                    {
                                        int bmin, bmax;
                                        bmin = (int)Math.Ceiling(yconv.Count * 0.16);
                                        bmax = (int)Math.Floor(yconv.Count * 0.84);
                                        if (bmax < bmin)
                                        {
                                            bmin = bmax;
                                        }
                                        double[] sample1s = (double[])yconv.GetRange(bmin, bmax - bmin + 1).ToArray(typeof(double));
                                        YConv             = NumericalTools.Fitting.Average(sample1s);
                                        this.Invoke(new dSetConv(SetConv), new object[] { false, YConv, 0.5 * (sample1s[sample1s.Length - 1] - sample1s[0]) / Math.Sqrt(sample1s.Length) });
                                    }
                                }
                                prevP = nextP;
                                prevC = nextC;
                            }
                        }
                    }
                }
                catch (Exception xc1)
                {
                    iLog.Log("Compute", xc1.ToString());
                }
                m_Running = false;
                this.Invoke(new dEnableButtons(EnableButtons), btn);
            }));
            thread.Start();
        }
예제 #6
0
        public static void EllipseParametersVector(ref Cluster c, out double axismax, out double axismin, out SySal.BasicTypes.Vector2 axismaxv)
        {
            double delta   = c.Inertia.IXX - c.Inertia.IYY;
            double discQ   = Math.Sqrt(delta * delta + 4.0 * c.Inertia.IXY * c.Inertia.IXY);
            double dQ      = c.Inertia.IXX + c.Inertia.IYY;
            double lambda1 = 0.5 * (dQ + discQ);

            axismax    = 4.0 * Math.Sqrt(lambda1 / c.Area);
            axismin    = 4.0 * Math.Sqrt(0.5 * (dQ - discQ) / c.Area);
            axismaxv.Y = c.Inertia.IXX - lambda1;
            axismaxv.X = -c.Inertia.IXY;
            double axnorm = 1.0 / Math.Sqrt(axismaxv.X * axismaxv.X + axismaxv.Y * axismaxv.Y);

            axismaxv.X += axnorm;
            axismaxv.Y += axnorm;
        }
예제 #7
0
        /// <summary>
        /// Maps a pattern of tracks onto another one.
        /// </summary>
        /// <param name="refpattern">the reference pattern.</param>
        /// <param name="mappattern">the pattern to be mapped.</param>
        /// <param name="flt">the filter function for mapping.</param>
        /// <param name="logstrw">the output stream where logging information is written; set to <c>null</c> to disable logging.</param>
        /// <returns>the transformation obtained.</returns>
        public SySal.DAQSystem.Scanning.IntercalibrationInfo MapTransform(SySal.Tracking.MIPEmulsionTrackInfo[] refpattern, SySal.Tracking.MIPEmulsionTrackInfo[] mappattern, MapManager.dMapFilter flt, System.IO.TextWriter logstrw)
        {
            SySal.DAQSystem.Scanning.IntercalibrationInfo calinfo = new SySal.DAQSystem.Scanning.IntercalibrationInfo();
            try
            {
                if (logstrw != null)
                {
                    logstrw.WriteLine("Begin pattern mapping.");
                }
                calinfo.MXX = calinfo.MYY = 1.0;
                calinfo.MXY = calinfo.MYX = 0.0;
                calinfo.RX  = calinfo.RY = calinfo.TX = calinfo.TY = calinfo.TZ = 0.0;
                int nr = refpattern.Length;
                int na = mappattern.Length;
                if (logstrw != null)
                {
                    logstrw.WriteLine("Ref tracks: " + nr);
                    logstrw.WriteLine("Add tracks: " + na);
                }
                if (nr == 0 || na == 0)
                {
                    return(calinfo);
                }
                SySal.BasicTypes.Rectangle          refrect = new SySal.BasicTypes.Rectangle();
                SySal.BasicTypes.Rectangle          addrect = new SySal.BasicTypes.Rectangle();
                SySal.Tracking.MIPEmulsionTrackInfo refinfo = refpattern[0];
                SySal.Tracking.MIPEmulsionTrackInfo addinfo = mappattern[0];
                refrect.MinX = refrect.MaxX = refinfo.Intercept.X;
                refrect.MinY = refrect.MaxY = refinfo.Intercept.Y;
                addrect.MinX = addrect.MaxX = addinfo.Intercept.X;
                addrect.MinY = addrect.MaxY = addinfo.Intercept.Y;
                int i;
                for (i = 1; i < nr; i++)
                {
                    refinfo = refpattern[i];
                    if (refinfo.Intercept.X < refrect.MinX)
                    {
                        refrect.MinX = refinfo.Intercept.X;
                    }
                    else if (refinfo.Intercept.X > refrect.MaxX)
                    {
                        refrect.MaxX = refinfo.Intercept.X;
                    }
                    if (refinfo.Intercept.Y < refrect.MinY)
                    {
                        refrect.MinY = refinfo.Intercept.Y;
                    }
                    else if (refinfo.Intercept.Y > refrect.MaxY)
                    {
                        refrect.MaxY = refinfo.Intercept.Y;
                    }
                }
                for (i = 1; i < na; i++)
                {
                    addinfo = mappattern[i];
                    if (addinfo.Intercept.X < addrect.MinX)
                    {
                        addrect.MinX = addinfo.Intercept.X;
                    }
                    else if (addinfo.Intercept.X > addrect.MaxX)
                    {
                        addrect.MaxX = addinfo.Intercept.X;
                    }
                    if (addinfo.Intercept.Y < addrect.MinY)
                    {
                        addrect.MinY = addinfo.Intercept.Y;
                    }
                    else if (addinfo.Intercept.Y > addrect.MaxY)
                    {
                        addrect.MaxY = addinfo.Intercept.Y;
                    }
                }
                SySal.BasicTypes.Rectangle maprect = new SySal.BasicTypes.Rectangle();
                maprect.MinX = Math.Max(refrect.MinX, addrect.MinX);
                maprect.MaxX = Math.Min(refrect.MaxX, addrect.MaxX);
                maprect.MinY = Math.Max(refrect.MinY, addrect.MinY);
                maprect.MaxY = Math.Min(refrect.MaxY, addrect.MaxY);
                int xcells = (int)Math.Ceiling((maprect.MaxX - maprect.MinX) / m_Config.MapSize);
                int ycells = (int)Math.Ceiling((maprect.MaxY - maprect.MinY) / m_Config.MapSize);
                if (logstrw != null)
                {
                    logstrw.WriteLine("Ref rect: " + refrect.MinX + " " + refrect.MaxX + " " + refrect.MinY + " " + refrect.MaxY);
                    logstrw.WriteLine("Map rect: " + addrect.MinX + " " + addrect.MaxX + " " + addrect.MinY + " " + addrect.MaxY);
                    logstrw.WriteLine("Common rect: " + maprect.MinX + " " + maprect.MaxX + " " + maprect.MinY + " " + maprect.MaxY);
                    logstrw.WriteLine("X cells: " + xcells + " Y cells: " + ycells);
                }
                if (xcells <= 0 || ycells <= 0)
                {
                    return(calinfo);
                }
                int ix, iy;
                System.Collections.ArrayList[,] rmaps = new System.Collections.ArrayList[ycells, xcells];
                System.Collections.ArrayList[,] amaps = new System.Collections.ArrayList[ycells, xcells];
                for (ix = 0; ix < xcells; ix++)
                {
                    for (iy = 0; iy < ycells; iy++)
                    {
                        rmaps[iy, ix] = new System.Collections.ArrayList();
                        amaps[iy, ix] = new System.Collections.ArrayList();
                    }
                }
                for (i = 0; i < nr; i++)
                {
                    refinfo = refpattern[i];
                    ix      = (int)((refinfo.Intercept.X - maprect.MinX) / m_Config.MapSize);
                    if (ix < 0 || ix >= xcells)
                    {
                        continue;
                    }
                    iy = (int)((refinfo.Intercept.Y - maprect.MinY) / m_Config.MapSize);
                    if (iy < 0 || iy >= ycells)
                    {
                        continue;
                    }
                    if (flt == null || flt(refinfo))
                    {
                        rmaps[iy, ix].Add(refinfo);
                    }
                }
                for (i = 0; i < na; i++)
                {
                    addinfo = mappattern[i];
                    ix      = (int)((addinfo.Intercept.X - maprect.MinX) / m_Config.MapSize);
                    if (ix < 0 || ix >= xcells)
                    {
                        continue;
                    }
                    iy = (int)((addinfo.Intercept.Y - maprect.MinY) / m_Config.MapSize);
                    if (iy < 0 || iy >= ycells)
                    {
                        continue;
                    }
                    if (flt == null || flt(addinfo))
                    {
                        amaps[iy, ix].Add(addinfo);
                    }
                }
                System.Collections.ArrayList mres = new System.Collections.ArrayList();
                for (ix = 0; ix < xcells; ix++)
                {
                    for (iy = 0; iy < ycells; iy++)
                    {
                        SySal.Tracking.MIPEmulsionTrackInfo[] ri = (SySal.Tracking.MIPEmulsionTrackInfo[])rmaps[iy, ix].ToArray(typeof(SySal.Tracking.MIPEmulsionTrackInfo));
                        if (ri.Length <= 0)
                        {
                            continue;
                        }
                        SySal.Tracking.MIPEmulsionTrackInfo[] ai = (SySal.Tracking.MIPEmulsionTrackInfo[])amaps[iy, ix].ToArray(typeof(SySal.Tracking.MIPEmulsionTrackInfo));
                        if (ai.Length <= 0)
                        {
                            continue;
                        }
                        MapResult mr = Map(ri, ai)[0];
                        if (mr.Valid)
                        {
                            SySal.BasicTypes.Vector2 p = new SySal.BasicTypes.Vector2();
                            p.X = maprect.MinX + m_Config.MapSize * (ix + 0.5);
                            p.Y = maprect.MinY + m_Config.MapSize * (iy + 0.5);
                            mres.Add(new object[] { p, mr });
                            logstrw.WriteLine("Z ix " + ix + " iy " + iy + " matches " + mr.Matches + " X " + p.X + " Y " + p.Y + " DeltaX/Y " + mr.DeltaPos.X + "/" + mr.DeltaPos.Y + " RMSX/Y " + mr.DeltaPosRMS.X + "/" + mr.DeltaPosRMS.Y + " DeltaSX/Y " + mr.DeltaSlope.X + "/" + mr.DeltaSlope.Y + " RMSX/Y " + mr.DeltaSlopeRMS.X + "/" + mr.DeltaSlopeRMS.Y);
                        }
                        else if (logstrw != null)
                        {
                            logstrw.WriteLine("Z ix " + ix + " iy " + iy + " matches " + mr.Matches);
                        }
                    }
                }
                double[,] inXY = new double[mres.Count, 2];
                double[,] dXY  = new double[mres.Count, 2];
                for (i = 0; i < mres.Count; i++)
                {
                    object[] o = (object[])mres[i];
                    inXY[i, 0] = ((SySal.BasicTypes.Vector2)o[0]).X;
                    inXY[i, 1] = ((SySal.BasicTypes.Vector2)o[0]).Y;
                    dXY[i, 0]  = -((MapResult)o[1]).DeltaPos.X;
                    dXY[i, 1]  = -((MapResult)o[1]).DeltaPos.Y;
                    if (logstrw != null)
                    {
                        logstrw.WriteLine("Zone " + i + " matches " + ((MapResult)o[1]).Matches + " " + inXY[i, 0] + " " + inXY[i, 1] + " " + dXY[i, 0] + " " + dXY[i, 1]);
                    }
                }
                switch (mres.Count)
                {
                case 0: return(calinfo);

                case 1: return(calinfo = TransformFitter.FindTranslation(inXY, dXY));

                case 2: return(calinfo = TransformFitter.FindRototranslation(inXY, dXY));

                default:
                    try
                    {
                        return(calinfo = TransformFitter.FindAffineTransformation(inXY, dXY));
                    }
                    catch (Exception)
                    {
                        return(calinfo = TransformFitter.FindRototranslation(inXY, dXY));
                    }
                }
            }
            finally
            {
                if (logstrw != null)
                {
                    logstrw.WriteLine("End mapping with RX/Y " + calinfo.RX + "/" + calinfo.RY + " MXX/XY/YX/YY " + calinfo.MXX + "/" + calinfo.MXY + "/" + calinfo.MYX + "/" + calinfo.MYY + " TX/Y " + calinfo.TX + "/" + calinfo.TY + ".");
                }
            }
        }
예제 #8
0
            public Writer(string filepath, SySal.BasicTypes.Identifier id, SySal.BasicTypes.Rectangle extents, SySal.BasicTypes.Vector2 center, SySal.DAQSystem.Scanning.IntercalibrationInfo transform)
            {
                guid       = System.Environment.ExpandEnvironmentVariables("%TEMP%\\" + System.Guid.NewGuid().ToString() + ".tlgs.");
                m_FilePath = filepath;
                w_tlg      = new System.IO.BinaryWriter(new System.IO.FileStream(filepath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None));
                b_toptk    = new System.IO.BinaryWriter(t_toptk = new System.IO.FileStream(guid + "ttk", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None));
                b_bottk    = new System.IO.BinaryWriter(t_bottk = new System.IO.FileStream(guid + "btk", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None));
                b_topvw    = new System.IO.BinaryWriter(t_topvw = new System.IO.FileStream(guid + "tvw", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None));
                b_botvw    = new System.IO.BinaryWriter(t_botvw = new System.IO.FileStream(guid + "bvw", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None));
                b_topix    = new System.IO.BinaryWriter(t_topix = new System.IO.FileStream(guid + "tix", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None));
                b_botix    = new System.IO.BinaryWriter(t_botix = new System.IO.FileStream(guid + "bix", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None));
                b_linked   = new System.IO.BinaryWriter(t_linked = new System.IO.FileStream(guid + "lk", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None));

                w_tlg.Write((byte)0x41);
                w_tlg.Write((ushort)0x7);
                w_tlg.Write(SectionTag);
                Section_Tracks_pos = w_tlg.BaseStream.Position;
                w_tlg.Write((long)0);

                w_tlg.Write(id.Part0);
                w_tlg.Write(id.Part1);
                w_tlg.Write(id.Part2);
                w_tlg.Write(id.Part3);

                w_tlg.Write(center.X);
                w_tlg.Write(center.Y);

                w_tlg.Write(extents.MinX);
                w_tlg.Write(extents.MaxX);
                w_tlg.Write(extents.MinY);
                w_tlg.Write(extents.MaxY);

                w_tlg.Write(transform.MXX);
                w_tlg.Write(transform.MXY);
                w_tlg.Write(transform.MYX);
                w_tlg.Write(transform.MYY);
                w_tlg.Write(transform.TX);
                w_tlg.Write(transform.TY);
                w_tlg.Write(transform.RX);
                w_tlg.Write(transform.RY);
            }
예제 #9
0
파일: Program.cs 프로젝트: kryssb/SySal.NET
        static void Main(string[] args)
        {
            if (args.Length != 13 && args.Length != 4 && args.Length != 2)
            {
                Console.WriteLine("usage: FlattenTLG.exe <cell map> <TLG to be flattened> <output TLG> <min matches>");
                Console.WriteLine("   or");
                Console.WriteLine("usage: FlattenTLG.exe <cell map> <min matches>");
                Console.WriteLine("           (opens a console to query the transformation map generator)");
                Console.WriteLine("   or");
                Console.WriteLine("usage: FlattenTLG.exe <reference TLG (supposed flat)> <TLG to be flattened> <output TLG> <cell size> <slope tol> <pos tol> <pos sweep> <z projection> <selection string> <min matches> <z adjust> <z step> <parallel (true|false)>");
                Console.WriteLine("Selection function variables:");
                foreach (SelFunc sf in KnownFunctions)
                {
                    Console.WriteLine(sf.Name + " -> " + sf.Desc);
                }
                return;
            }
            bool   usereadymap = (args.Length < 13);
            bool   useconsole = (args.Length == 2);
            string reftlg = args[0];
            string worktlg = useconsole ? "" : args[1];
            string outtlg = useconsole ? "" : args[2];
            uint   MinMatches = 0;
            int    xcells = 0;
            int    ycells = 0;
            double cellsize = 0.0;
            int    ix, iy;
            int    i, j, k;

            SySal.BasicTypes.Vector2   Center  = new SySal.BasicTypes.Vector2();
            SySal.BasicTypes.Rectangle WorkRect;
            SySal.Scanning.Plate.IO.OPERA.LinkedZone worklz = null;
            if (useconsole == false)
            {
                worklz   = SySal.DataStreams.OPERALinkedZone.FromFile(worktlg);
                WorkRect = worklz.Extents;
            }
            else
            {
                WorkRect = new SySal.BasicTypes.Rectangle();
            }
            SySal.BasicTypes.Rectangle RefRect = new SySal.BasicTypes.Rectangle();
            RTrackCell[,] WorkCells;
            if (usereadymap)
            {
                MinMatches = Convert.ToUInt32(args[useconsole ? 1 : 3]);
                System.IO.StreamReader cr = new System.IO.StreamReader(args[0]);
                while (cr.EndOfStream == false)
                {
                    System.Text.RegularExpressions.Match m = rx_CellMap.Match(cr.ReadLine());
                    if (m.Success)
                    {
                        RefRect.MinX = Convert.ToDouble(m.Groups[1].Value);
                        RefRect.MaxX = Convert.ToDouble(m.Groups[2].Value);
                        RefRect.MinY = Convert.ToDouble(m.Groups[3].Value);
                        RefRect.MaxY = Convert.ToDouble(m.Groups[4].Value);
                        cellsize     = Convert.ToDouble(m.Groups[5].Value);
                        xcells       = Convert.ToInt32(m.Groups[6].Value);
                        ycells       = Convert.ToInt32(m.Groups[7].Value);
                        break;
                    }
                }
                Center.X  = 0.5 * (RefRect.MinX + RefRect.MaxX);
                Center.Y  = 0.5 * (RefRect.MinY + RefRect.MaxY);
                WorkCells = new RTrackCell[xcells, ycells];
                for (ix = 0; ix < xcells; ix++)
                {
                    for (iy = 0; iy < ycells; iy++)
                    {
                        SySal.BasicTypes.Rectangle rect = new SySal.BasicTypes.Rectangle();
                        rect.MinX                = RefRect.MinX + ix * cellsize;
                        rect.MaxX                = rect.MinX + cellsize;
                        rect.MinY                = RefRect.MinY + iy * cellsize;
                        rect.MaxY                = rect.MinY + cellsize;
                        WorkCells[ix, iy]        = new RTrackCell(rect, Center);
                        WorkCells[ix, iy].Result = NumericalTools.ComputationResult.InvalidInput;
                    }
                }
                while (cr.EndOfStream == false)
                {
                    System.Text.RegularExpressions.Match m = rx_Cell.Match(cr.ReadLine());
                    if (m.Success)
                    {
                        ix = Convert.ToInt32(m.Groups[1].Value);
                        iy = Convert.ToInt32(m.Groups[2].Value);
                        WorkCells[ix, iy].Result           = NumericalTools.ComputationResult.OK;
                        WorkCells[ix, iy].Matches          = Convert.ToInt32(m.Groups[3].Value);
                        WorkCells[ix, iy].Average.X        = Convert.ToDouble(m.Groups[4].Value);
                        WorkCells[ix, iy].Average.Y        = Convert.ToDouble(m.Groups[5].Value);
                        WorkCells[ix, iy].AlignInfo.MXX    = Convert.ToDouble(m.Groups[6].Value);
                        WorkCells[ix, iy].AlignInfo.MXY    = Convert.ToDouble(m.Groups[7].Value);
                        WorkCells[ix, iy].AlignInfo.MYX    = Convert.ToDouble(m.Groups[8].Value);
                        WorkCells[ix, iy].AlignInfo.MYY    = Convert.ToDouble(m.Groups[9].Value);
                        WorkCells[ix, iy].AlignInfo.TX     = Convert.ToDouble(m.Groups[10].Value);
                        WorkCells[ix, iy].AlignInfo.TY     = Convert.ToDouble(m.Groups[11].Value);
                        WorkCells[ix, iy].AlignInfo.TZ     = Convert.ToDouble(m.Groups[12].Value);
                        WorkCells[ix, iy].SlopeAlignInfo.X = Convert.ToDouble(m.Groups[13].Value);
                        WorkCells[ix, iy].SlopeAlignInfo.Y = Convert.ToDouble(m.Groups[14].Value);
                    }
                }
                cr.Close();
                if (useconsole)
                {
                    GridInterpolation G1 = new GridInterpolation(WorkCells, cellsize, RefRect, (int)MinMatches);
                    Console.WriteLine("Type a pair of coordinates ( X Y ) to get the transformation map.\r\nEOF (CTRL+Z to exit).");
                    double x, y;
                    string line;
                    while ((line = Console.ReadLine()) != null)
                    {
                        System.Text.RegularExpressions.Match m = rx_XY.Match(line);
                        x = Convert.ToDouble(m.Groups[1].Value);
                        y = Convert.ToDouble(m.Groups[2].Value);
                        SySal.BasicTypes.Vector dslope = new SySal.BasicTypes.Vector();
                        SySal.DAQSystem.Scanning.IntercalibrationInfo dpos = new SySal.DAQSystem.Scanning.IntercalibrationInfo();
                        bool result = G1.Evaluate(x, y, ref dslope, ref dpos);
                        Console.WriteLine(x + " " + y + " -> " + (result ? "OK" : "FAILED") + " " + dpos.RX + " " + dpos.RY + " " + dpos.MXX + " " + dpos.MXY + " " + dpos.MYX + " " + dpos.MYY + " " + dpos.TX + " " + dpos.TY + " " + dpos.TZ + " " + dslope.X + " " + dslope.Y);
                    }
                    return;
                }
            }
            else
            {
                cellsize = Convert.ToDouble(args[3]);
                double slopetol  = Convert.ToDouble(args[4]);
                double postol    = Convert.ToDouble(args[5]);
                double possweep  = Convert.ToDouble(args[6]);
                double DZ        = Convert.ToDouble(args[7]);
                string selstring = args[8];
                MinMatches = Convert.ToUInt32(args[9]);
                double ZAdj       = Convert.ToDouble(args[10]);
                double ZStep      = Convert.ToDouble(args[11]);
                bool   IsParallel = Convert.ToBoolean(args[12]);
                NumericalTools.CStyleParsedFunction S = new NumericalTools.CStyleParsedFunction(selstring);
                dSel[] pMap = new dSel[S.ParameterList.Length];
                for (j = 0; j < S.ParameterList.Length; j++)
                {
                    string sp = S.ParameterList[j];
                    for (i = 0; i < KnownFunctions.Length && String.Compare(sp, KnownFunctions[i].Name, true) != 0; i++)
                    {
                        ;
                    }
                    if (i == KnownFunctions.Length)
                    {
                        throw new Exception("Unknown parameter \"" + sp + "\".");
                    }
                    pMap[j] = KnownFunctions[i].Evaluate;
                }
                SySal.Scanning.Plate.IO.OPERA.LinkedZone reflz = SySal.DataStreams.OPERALinkedZone.FromFile(reftlg);
                RefRect = reflz.Extents;
                if (WorkRect.MinX > RefRect.MinX)
                {
                    RefRect.MinX = WorkRect.MinX;
                }
                if (WorkRect.MaxX < RefRect.MaxX)
                {
                    RefRect.MaxX = WorkRect.MaxX;
                }
                if (WorkRect.MinY > RefRect.MinY)
                {
                    RefRect.MinY = WorkRect.MinY;
                }
                if (WorkRect.MaxY < RefRect.MaxY)
                {
                    RefRect.MaxY = WorkRect.MaxY;
                }
                Center.X = 0.5 * (RefRect.MinX + RefRect.MaxX);
                Center.Y = 0.5 * (RefRect.MinY + RefRect.MaxY);
                xcells   = (int)Math.Ceiling((RefRect.MaxX - RefRect.MinX) / cellsize);
                ycells   = (int)Math.Ceiling((RefRect.MaxY - RefRect.MinY) / cellsize);
                Console.WriteLine("X/Y Cells: " + xcells + "/" + ycells);
                if (xcells <= 0 || ycells <= 0)
                {
                    throw new Exception("Null working area.");
                }
                RTrackCell[,] RefCells = new RTrackCell[xcells, ycells];
                WorkCells = new RTrackCell[xcells, ycells];
                for (ix = 0; ix < xcells; ix++)
                {
                    for (iy = 0; iy < ycells; iy++)
                    {
                        SySal.BasicTypes.Rectangle rect = new SySal.BasicTypes.Rectangle();
                        rect.MinX         = RefRect.MinX + ix * cellsize;
                        rect.MaxX         = rect.MinX + cellsize;
                        rect.MinY         = RefRect.MinY + iy * cellsize;
                        rect.MaxY         = rect.MinY + cellsize;
                        RefCells[ix, iy]  = new RTrackCell(rect, Center);
                        WorkCells[ix, iy] = new RTrackCell(rect, Center);
                    }
                }
                SySal.Scanning.Plate.IO.OPERA.LinkedZone lz;
                RTrackCell[,] rtc;
                for (i = 0; i < 2; i++)
                {
                    if (i == 0)
                    {
                        lz  = reflz;
                        rtc = RefCells;
                    }
                    else
                    {
                        lz  = worklz;
                        rtc = WorkCells;
                    }
                    for (j = 0; j < lz.Length; j++)
                    {
                        SySal.Scanning.MIPBaseTrack tk = lz[j] as SySal.Scanning.MIPBaseTrack;
                        for (k = 0; k < pMap.Length; k++)
                        {
                            S[k] = pMap[k](tk);
                        }
                        if (S.Evaluate() != 0.0)
                        {
                            ix = (int)((tk.Info.Intercept.X - RefRect.MinX) / cellsize);
                            iy = (int)((tk.Info.Intercept.Y - RefRect.MinY) / cellsize);
                            if (ix >= 0 && ix < xcells && iy >= 0 && iy < ycells)
                            {
                                RTrack rtr = new RTrack();
                                rtr.Slope.X    = tk.Info.Slope.X;
                                rtr.Slope.Y    = tk.Info.Slope.Y;
                                rtr.Position.X = tk.Info.Intercept.X;
                                rtr.Position.Y = tk.Info.Intercept.Y;
                                rtc[ix, iy].Add(rtr);
                            }
                        }
                    }
                }
                for (ix = 0; ix < xcells; ix++)
                {
                    for (iy = 0; iy < ycells; iy++)
                    {
                        Console.WriteLine("Ref " + RefCells[ix, iy].Average.X + " " + RefCells[ix, iy].Average.Y + " " + RefCells[ix, iy].Count);
                        Console.WriteLine("Work " + WorkCells[ix, iy].Average.X + " " + WorkCells[ix, iy].Average.Y + " " + WorkCells[ix, iy].Count);
                    }
                }
                SySal.Processing.QuickMapping.QuickMapper   QM  = new SySal.Processing.QuickMapping.QuickMapper();
                SySal.Processing.QuickMapping.Configuration qmc = QM.Config as SySal.Processing.QuickMapping.Configuration;
                qmc.FullStatistics       = false;
                qmc.UseAbsoluteReference = true;
                qmc.PosTol   = postol;
                qmc.SlopeTol = slopetol;
                for (ix = 0; ix < xcells; ix++)
                {
                    for (iy = 0; iy < ycells; iy++)
                    {
                        SySal.Tracking.MIPEmulsionTrackInfo[] rinfo = new SySal.Tracking.MIPEmulsionTrackInfo[RefCells[ix, iy].Count];
                        SySal.Tracking.MIPEmulsionTrackInfo[] winfo = new SySal.Tracking.MIPEmulsionTrackInfo[WorkCells[ix, iy].Count];
                        for (i = 0; i < 2; i++)
                        {
                            SySal.Tracking.MIPEmulsionTrackInfo[] inf = (i == 0) ? rinfo : winfo;
                            RTrackCell[,] cells = (i == 0) ? RefCells : WorkCells;
                            double dz = (i == 0) ? 0.0 : DZ;
                            for (j = 0; j < inf.Length; j++)
                            {
                                RTrack r = cells[ix, iy].Get(j);
                                inf[j]             = new SySal.Tracking.MIPEmulsionTrackInfo();
                                inf[j].Slope.X     = r.Slope.X;
                                inf[j].Slope.Y     = r.Slope.Y;
                                inf[j].Intercept.X = r.Position.X;
                                inf[j].Intercept.Y = r.Position.Y;
                                inf[j].Intercept.Z = dz;
                            }
                        }
                        SySal.Scanning.PostProcessing.PatternMatching.TrackPair[] pairs = new SySal.Scanning.PostProcessing.PatternMatching.TrackPair[0];
                        double bestdz = 0.0;
                        if (rinfo.Length >= 2 && winfo.Length >= 2)
                        {
                            double dz1;
                            if (IsParallel)
                            {
                                System.Collections.ArrayList thrarr = new System.Collections.ArrayList();
                                for (dz1 = -ZAdj; dz1 <= ZAdj; dz1 += ZStep)
                                {
                                    MapThread mthr = new MapThread();
                                    mthr.m_rinfo    = rinfo;
                                    mthr.m_winfo    = winfo;
                                    mthr.m_DZ       = DZ + dz1;
                                    mthr.m_PosSweep = possweep;
                                    mthr.m_PosTol   = postol;
                                    mthr.m_SlopeTol = slopetol;
                                    mthr.m_Thread   = new System.Threading.Thread(new System.Threading.ThreadStart(mthr.Execute));
                                    mthr.m_Thread.Start();
                                    thrarr.Add(mthr);
                                }
                                foreach (MapThread mt in thrarr)
                                {
                                    mt.m_Thread.Join();
                                    if (mt.m_Pairs.Length > pairs.Length)
                                    {
                                        bestdz = mt.m_DZ - DZ;
                                        pairs  = mt.m_Pairs;
                                    }
                                }
                            }
                            else
                            {
                                for (dz1 = -ZAdj; dz1 <= ZAdj; dz1 += ZStep)
                                {
                                    SySal.Scanning.PostProcessing.PatternMatching.TrackPair[] qairs = QM.Match(rinfo, winfo, DZ + dz1, possweep, possweep);
                                    if (qairs.Length > pairs.Length)
                                    {
                                        bestdz = dz1;
                                        pairs  = qairs;
                                    }
                                }
                            }
                        }
                        double[] alignpars = new double[7];
                        SySal.BasicTypes.Vector2 slopedelta = new SySal.BasicTypes.Vector2();
                        SySal.BasicTypes.Vector2 slopetolv  = new SySal.BasicTypes.Vector2();
                        double[] dslx = new double[pairs.Length];
                        double[] dsly = new double[pairs.Length];
                        for (j = 0; j < pairs.Length; j++)
                        {
                            dslx[j] = pairs[j].First.Info.Slope.X - pairs[j].Second.Info.Slope.X;
                        }
                        PeakFit(dslx, slopetol, out slopedelta.X, out slopetolv.X);
                        for (j = 0; j < pairs.Length; j++)
                        {
                            dsly[j] = pairs[j].First.Info.Slope.Y - pairs[j].Second.Info.Slope.Y;
                        }
                        PeakFit(dsly, slopetol, out slopedelta.Y, out slopetolv.Y);
                        int gooddslopes = 0;
                        for (j = 0; j < pairs.Length; j++)
                        {
                            if ((slopedelta.X - slopetolv.X) < dslx[j] && dslx[j] < (slopedelta.X + slopetolv.X) && (slopedelta.Y - slopetolv.Y) < dsly[j] && dsly[j] < (slopedelta.Y + slopetolv.Y))
                            {
                                gooddslopes++;
                            }
                        }
                        if (gooddslopes > 0)
                        {
                            double[] DX = new double[gooddslopes];
                            double[] DY = new double[gooddslopes];
                            double[] X  = new double[gooddslopes];
                            double[] Y  = new double[gooddslopes];
                            double[] SX = new double[gooddslopes];
                            double[] SY = new double[gooddslopes];
                            for (j = i = 0; j < pairs.Length; j++)
                            {
                                if ((slopedelta.X - slopetolv.X) < dslx[j] && dslx[j] < (slopedelta.X + slopetolv.X) && (slopedelta.Y - slopetolv.Y) < dsly[j] && dsly[j] < (slopedelta.Y + slopetolv.Y))
                                {
                                    X[i]  = pairs[j].Second.Info.Intercept.X - WorkCells[ix, iy].AlignInfo.RX;
                                    Y[i]  = pairs[j].Second.Info.Intercept.Y - WorkCells[ix, iy].AlignInfo.RY;
                                    SX[i] = pairs[j].Second.Info.Slope.X;
                                    SY[i] = pairs[j].Second.Info.Slope.Y;
                                    DX[i] = pairs[j].First.Info.Intercept.X - pairs[j].Second.Info.Intercept.X;
                                    DY[i] = pairs[j].First.Info.Intercept.Y - pairs[j].Second.Info.Intercept.Y;
                                    //System.IO.File.AppendAllText(@"c:\flattentlg.txt", "\r\n" + ix + " " + iy + " " + i + " " + j + " " + pairs.Length + " " + gooddslopes + " " + WorkCells[ix, iy].AlignInfo.RX + " " + WorkCells[ix, iy].AlignInfo.RY + " " + X[i] + " " + Y[i] + " " + SX[i] + " " + SY[i] + "  " + DX[i] + " " + DY[i] + " " + bestdz);
                                    i++;
                                }
                            }
                            WorkCells[ix, iy].Result = IteratedAffineFocusing(DX, DY, X, Y, SX, SY, postol, ref alignpars);
                        }
                        else
                        {
                            WorkCells[ix, iy].Result = NumericalTools.ComputationResult.InvalidInput;
                        }
                        WorkCells[ix, iy].Matches        = pairs.Length;
                        WorkCells[ix, iy].AlignInfo.TZ   = alignpars[6] + bestdz;
                        WorkCells[ix, iy].AlignInfo.TX   = alignpars[4];
                        WorkCells[ix, iy].AlignInfo.TY   = alignpars[5];
                        WorkCells[ix, iy].AlignInfo.MXX  = 1.0 + alignpars[0];
                        WorkCells[ix, iy].AlignInfo.MXY  = 0.0 + alignpars[1];
                        WorkCells[ix, iy].AlignInfo.MYX  = 0.0 + alignpars[2];
                        WorkCells[ix, iy].AlignInfo.MYY  = 1.0 + alignpars[3];
                        WorkCells[ix, iy].SlopeAlignInfo = slopedelta;
                        Console.WriteLine("Fit " + WorkCells[ix, iy].Result + " " + WorkCells[ix, iy].AlignInfo.MXX + " " + WorkCells[ix, iy].AlignInfo.MXY + " " + WorkCells[ix, iy].AlignInfo.MYX + " " + WorkCells[ix, iy].AlignInfo.MYY + " " + WorkCells[ix, iy].AlignInfo.TX + " " + WorkCells[ix, iy].AlignInfo.TY + " " + WorkCells[ix, iy].AlignInfo.TZ + " " + WorkCells[ix, iy].SlopeAlignInfo.X + " " + WorkCells[ix, iy].SlopeAlignInfo.Y);
                    }
                }
                int goodcells = 0;
                for (ix = 0; ix < xcells; ix++)
                {
                    for (iy = 0; iy < ycells; iy++)
                    {
                        if (WorkCells[ix, iy].Result == NumericalTools.ComputationResult.OK && WorkCells[ix, iy].Matches >= MinMatches)
                        {
                            goodcells++;
                        }
                    }
                }
                Console.WriteLine("Good cells: " + goodcells);

                Console.WriteLine("--------CELLS");
                Console.WriteLine("CELLMAP " + RefRect.MinX + " " + RefRect.MaxX + " " + RefRect.MinY + " " + RefRect.MaxY + " " + cellsize + " " + xcells + " " + ycells);
                Console.WriteLine("IX\tIY\tN\tX\tY\tMXX\tMXY\tMYX\tMYY\tTX\tTY\tTZ\tTDSX\tTDSY");
                for (ix = 0; ix < xcells; ix++)
                {
                    for (iy = 0; iy < ycells; iy++)
                    {
                        if (WorkCells[ix, iy].Result == NumericalTools.ComputationResult.OK && WorkCells[ix, iy].Matches >= MinMatches)
                        {
                            Console.WriteLine(ix + "\t" + iy + "\t" + WorkCells[ix, iy].Matches + "\t" + WorkCells[ix, iy].Average.X + "\t" + WorkCells[ix, iy].Average.Y + "\t" + WorkCells[ix, iy].AlignInfo.MXX + "\t" + WorkCells[ix, iy].AlignInfo.MXY + "\t" + WorkCells[ix, iy].AlignInfo.MYX + "\t" + WorkCells[ix, iy].AlignInfo.MYY + "\t" + WorkCells[ix, iy].AlignInfo.TX + "\t" + WorkCells[ix, iy].AlignInfo.TY + "\t" + WorkCells[ix, iy].AlignInfo.TZ + "\t" + WorkCells[ix, iy].SlopeAlignInfo.X + "\t" + WorkCells[ix, iy].SlopeAlignInfo.Y);
                        }
                    }
                }
                Console.WriteLine("--------ENDCELLS");
            }
            SySal.DataStreams.OPERALinkedZone.Writer outlzw = new SySal.DataStreams.OPERALinkedZone.Writer(outtlg, worklz.Id, worklz.Extents, worklz.Center, worklz.Transform);
            outlzw.SetZInfo(worklz.Top.TopZ, worklz.Top.BottomZ, worklz.Bottom.TopZ, worklz.Bottom.BottomZ);
            for (i = 0; i < ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.Side)worklz.Top).ViewCount; i++)
            {
                outlzw.AddView(((SySal.Scanning.Plate.IO.OPERA.LinkedZone.Side)worklz.Top).View(i), true);
            }
            for (i = 0; i < ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.Side)worklz.Bottom).ViewCount; i++)
            {
                outlzw.AddView(((SySal.Scanning.Plate.IO.OPERA.LinkedZone.Side)worklz.Bottom).View(i), false);
            }
            SySal.BasicTypes.Vector proj       = new SySal.BasicTypes.Vector();
            Console.WriteLine("Writing flattened TLG...");
            GridInterpolation G = new GridInterpolation(WorkCells, cellsize, RefRect, (int)MinMatches);

            System.DateTime start = System.DateTime.Now;
            for (i = 0; i < worklz.Length; i++)
            {
                if (i % 1000 == 0)
                {
                    System.DateTime nw = System.DateTime.Now;
                    if ((nw - start).TotalMilliseconds >= 10000)
                    {
                        Console.WriteLine((i * 100 / worklz.Length) + "%");
                        start = nw;
                    }
                }
                SySal.Tracking.MIPEmulsionTrackInfo           baseinfo      = worklz[i].Info;
                SySal.DAQSystem.Scanning.IntercalibrationInfo transforminfo = new SySal.DAQSystem.Scanning.IntercalibrationInfo();
                transforminfo.RX = Center.X;
                transforminfo.RY = Center.Y;
                SySal.BasicTypes.Vector tds = new SySal.BasicTypes.Vector();

                G.Evaluate(baseinfo.Intercept.X, baseinfo.Intercept.Y, ref tds, ref transforminfo);

                proj.X             = -baseinfo.Slope.X * transforminfo.TZ;
                proj.Y             = -baseinfo.Slope.Y * transforminfo.TZ;
                proj.Z             = 0.0;
                baseinfo.Intercept = transforminfo.Transform(baseinfo.Intercept) + proj;
                baseinfo.Slope     = transforminfo.Deform(baseinfo.Slope) + tds;
                SySal.Scanning.MIPIndexedEmulsionTrack toptk      = worklz[i].Top;
                SySal.Tracking.MIPEmulsionTrackInfo    topinfo    = toptk.Info;
                SySal.Scanning.MIPIndexedEmulsionTrack bottomtk   = worklz[i].Bottom;
                SySal.Tracking.MIPEmulsionTrackInfo    bottominfo = bottomtk.Info;
                topinfo.Intercept    = transforminfo.Transform(topinfo.Intercept) + proj;
                topinfo.Slope        = transforminfo.Deform(topinfo.Slope) + tds;
                bottominfo.Intercept = transforminfo.Transform(bottominfo.Intercept) + proj;
                bottominfo.Slope     = transforminfo.Deform(bottominfo.Slope) + tds;
                outlzw.AddMIPEmulsionTrack(topinfo, i, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)toptk).View.Id, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)toptk).OriginalRawData, true);
                outlzw.AddMIPEmulsionTrack(bottominfo, i, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)bottomtk).View.Id, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)bottomtk).OriginalRawData, false);
                outlzw.AddMIPBasetrack(baseinfo, i, i, i);
            }
            outlzw.Complete();
            Console.WriteLine("Written \"" + outtlg + "\".");
        }