Beispiel #1
0
            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;
                    }
                }
            }
Beispiel #2
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);
            }
Beispiel #3
0
 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;
 }
Beispiel #4
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 + ".");
                }
            }
        }
Beispiel #5
0
 /// <summary>
 /// Extracts a track map from the data.
 /// </summary>
 /// <param name="data">the input data; can be an array of microtracks, a linked zone or a TotalScan volume.</param>
 /// <param name="side">the side to be used.</param>
 /// <param name="r">the rectangle that sets the bounds for the track map to be extracted.</param>
 /// <param name="flt">the track filter; leave <c>null</c> to skip filtering.</param>
 /// <param name="useoriginal">if <c>true</c>, the original (anti-transformed) tracks are used; ignored if the input data is other than a TotalScan volume.</param>
 /// <returns>the subset of tracks to be used for mapping.</returns>
 public static SySal.Tracking.MIPEmulsionTrackInfo[] ExtractMap(object data, MapSide side, SySal.BasicTypes.Rectangle r, dMapFilter flt, bool useoriginal)
 {
     if (data is SySal.Scanning.Plate.LinkedZone)
     {
         return(lzExtractMap((SySal.Scanning.Plate.LinkedZone)data, side, r, flt));
     }
     else if (data is SySal.TotalScan.Layer)
     {
         int s = ((SySal.TotalScan.Layer)data).Side;
         if (s != (int)side)
         {
             throw new Exception("Expected side = " + side + " but found " + s + ".");
         }
         return(layExtractMap((SySal.TotalScan.Layer)data, r, flt, useoriginal));
     }
     else if (data is SySal.Tracking.MIPEmulsionTrackInfo[])
     {
         return(tkExtractMap((SySal.Tracking.MIPEmulsionTrackInfo[])data, r, flt));
     }
     throw new Exception("Map extraction from type " + data.GetType() + " is not supported.");
 }
Beispiel #6
0
 static SySal.Tracking.MIPEmulsionTrackInfo[] tkExtractMap(SySal.Tracking.MIPEmulsionTrackInfo[] tks, SySal.BasicTypes.Rectangle r, dMapFilter flt)
 {
     System.Collections.ArrayList ar = new System.Collections.ArrayList();
     foreach (SySal.Tracking.MIPEmulsionTrackInfo info in tks)
     {
         if (info.Intercept.X < r.MinX || info.Intercept.X > r.MaxX || info.Intercept.Y < r.MinY || info.Intercept.Y > r.MaxY)
         {
             continue;
         }
         if (flt == null || flt(info))
         {
             ar.Add(info);
         }
     }
     return((SySal.Tracking.MIPEmulsionTrackInfo[])ar.ToArray(typeof(SySal.Tracking.MIPEmulsionTrackInfo)));
 }
Beispiel #7
0
        static SySal.Tracking.MIPEmulsionTrackInfo[] layExtractMap(SySal.TotalScan.Layer lay, SySal.BasicTypes.Rectangle r, dMapFilter flt, bool useoriginal)
        {
            System.Collections.ArrayList ar = new System.Collections.ArrayList();
            int n = lay.Length;
            int i;

            for (i = 0; i < n; i++)
            {
                SySal.Tracking.MIPEmulsionTrackInfo info = useoriginal ? lay[i].OriginalInfo : lay[i].Info;
                if (info.Intercept.X < r.MinX || info.Intercept.X > r.MaxX || info.Intercept.Y < r.MinY || info.Intercept.Y > r.MaxY)
                {
                    continue;
                }
                if (flt == null || flt(lay[i]))
                {
                    ar.Add(info);
                }
            }
            return((SySal.Tracking.MIPEmulsionTrackInfo[])ar.ToArray(typeof(SySal.Tracking.MIPEmulsionTrackInfo)));
        }
Beispiel #8
0
        static SySal.Tracking.MIPEmulsionTrackInfo[] lzExtractMap(SySal.Scanning.Plate.LinkedZone lz, MapSide side, SySal.BasicTypes.Rectangle r, dMapFilter flt)
        {
            System.Collections.ArrayList ar = new System.Collections.ArrayList();
            int n;

            switch (side)
            {
            case MapSide.Base: n = lz.Length; break;

            case MapSide.Top: n = lz.Top.Length; break;

            case MapSide.Bottom: n = lz.Bottom.Length; break;

            default: throw new Exception("Internal inconsistency: side = " + side + " is not supported.");
            }
            int i;

            for (i = 0; i < n; i++)
            {
                SySal.Tracking.MIPEmulsionTrackInfo info;
                switch (side)
                {
                case MapSide.Base: info = lz[i].Info; break;

                case MapSide.Top: info = lz.Top[i].Info; break;

                case MapSide.Bottom: info = lz.Bottom[i].Info; break;

                default: throw new Exception("Internal inconsistency: side = " + side + " is not supported.");
                }
                if (info.Intercept.X < r.MinX || info.Intercept.X > r.MaxX || info.Intercept.Y < r.MinY || info.Intercept.Y > r.MaxY)
                {
                    continue;
                }
                if (flt == null || flt(info))
                {
                    ar.Add(info);
                }
            }
            return((SySal.Tracking.MIPEmulsionTrackInfo[])ar.ToArray(typeof(SySal.Tracking.MIPEmulsionTrackInfo)));
        }
Beispiel #9
0
        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 + "\".");
        }