예제 #1
0
파일: Program.cs 프로젝트: kryssb/SySal.NET
        public static void AdjustSlopes(SySal.Scanning.Plate.IO.OPERA.LinkedZone lz)
        {
            int    i, n;
            double multx, multy, deltax, deltay;

            multx  = 1.0 / C.TopMultSlopeX;
            multy  = 1.0 / C.TopMultSlopeY;
            deltax = -C.TopDeltaSlopeX;
            deltay = -C.TopDeltaSlopeY;
            n      = lz.Top.Length;
            for (i = 0; i < n; i++)
            {
                MIPEmulsionTrack.AdjustSlopes(lz.Top[i], multx, multy, deltax, deltay);
            }

            multx  = 1.0 / C.BottomMultSlopeX;
            multy  = 1.0 / C.BottomMultSlopeY;
            deltax = -C.BottomDeltaSlopeX;
            deltay = -C.BottomDeltaSlopeY;
            n      = lz.Bottom.Length;
            for (i = 0; i < n; i++)
            {
                MIPEmulsionTrack.AdjustSlopes(lz.Bottom[i], multx, multy, deltax, deltay);
            }
        }
예제 #2
0
파일: Exe.cs 프로젝트: kryssb/SySal.NET
 public LinkedZone(SySal.Scanning.Plate.IO.OPERA.LinkedZone lz)
 {
     MyTransformation.Transform(lz.Extents.MinX, lz.Extents.MinY, ref m_Extents.MinX, ref m_Extents.MinY);
     MyTransformation.Transform(lz.Extents.MaxX, lz.Extents.MaxY, ref m_Extents.MaxX, ref m_Extents.MaxY);
     MyTransformation.Transform(lz.Center.X, lz.Center.Y, ref m_Center.X, ref m_Center.Y);
     m_Id     = lz.Id;
     m_Tracks = LinkedZone.AccessTracks(lz);
     m_Top    = lz.Top;
     m_Bottom = lz.Bottom;
     foreach (SySal.Scanning.MIPBaseTrack btk in m_Tracks)
     {
         tMIPBaseTrack.ApplyTransformation(btk);
     }
     SySal.Tracking.MIPEmulsionTrack [] mutks;
     mutks = BatchIntercalibrate.LinkedZone.Side.GetTracks(m_Top);
     foreach (SySal.Scanning.MIPIndexedEmulsionTrack mutk in mutks)
     {
         tMIPEmulsionTrack.ApplyTransformation(mutk);
     }
     mutks = BatchIntercalibrate.LinkedZone.Side.GetTracks(m_Bottom);
     foreach (SySal.Scanning.MIPIndexedEmulsionTrack mutk in mutks)
     {
         tMIPEmulsionTrack.ApplyTransformation(mutk);
     }
 }
예제 #3
0
        public void Process()
        {
            System.IO.FileStream f = new System.IO.FileStream(BaseName + ".rwc", System.IO.FileMode.Open, System.IO.FileAccess.Read);
            SySal.Scanning.Plate.IO.OPERA.RawData.Catalog Cat = new SySal.Scanning.Plate.IO.OPERA.RawData.Catalog(f);
            f.Close();
            Exe.SFL.Load = new SySal.Scanning.PostProcessing.dLoadFragment(LoadFragment);
            SySal.Scanning.Plate.IO.OPERA.LinkedZone lz = Exe.SFL.Link(Cat);
            System.IO.FileStream g = new System.IO.FileStream(BaseName + ".tlg", System.IO.FileMode.Create, System.IO.FileAccess.Write);
            lz.Save(g);
            g.Flush();
            g.Close();
            double bestdlink = STol;

            SySal.Scanning.MIPBaseTrack besttrack = null;
            int i;

            for (i = 0; i < lz.Length; i++)
            {
                if (lz[i].Info.Count >= MinPts)
                {
                    double dsx, dsy, dlink;
                    dsx   = lz[i].Info.Slope.X - Sx;
                    dsy   = lz[i].Info.Slope.Y - Sy;
                    dlink = Math.Sqrt(dsx * dsx + dsy * dsy);
                    if (dlink < bestdlink)
                    {
                        besttrack = lz[i];
                        bestdlink = dlink;
                    }
                }
            }
            if (besttrack != null)
            {
                OutF.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} 1 {10} {11} {12} {13} {14} {15} {16} {17}",
                               Id.Part0, Id.Part1, Id.Part2, Id.Part3, Px, Py, Sx, Sy, PTol, STol,
                               besttrack.Info.Intercept.X, besttrack.Info.Intercept.Y, besttrack.Info.Slope.X, besttrack.Info.Slope.Y,
                               besttrack.Info.Intercept.X - Px, besttrack.Info.Intercept.Y - Py, besttrack.Info.Slope.X - Sx, besttrack.Info.Slope.Y - Sy);
            }
            else
            {
                OutF.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} 0 0 0 0 0 0 0 0 0",
                               Id.Part0, Id.Part1, Id.Part2, Id.Part3, Px, Py, Sx, Sy, PTol, STol);
            }
        }
예제 #4
0
파일: Exe.cs 프로젝트: kryssb/SySal.NET
        static void Main(string[] args)
        {
            //
            // TODO: Add code to start application here
            //
            if (args.Length != 3)
            {
                System.Xml.Serialization.XmlSerializer xmls = null;
                Console.WriteLine("BatchReconstruct - performs volume reconstruction using LinkedZones from TLG files or OPERA DB tables.");
                Console.WriteLine("usage: batchreconstruct <XML list file> <output Opera persistence path> <XML config Opera persistence path>");
                Console.WriteLine("or:    batchreconstruct <DB volume> <output Opera persistence path> <XML config Opera persistence path>");
                Console.WriteLine("or:    batchreconstruct <input OPERA persistence path> <output Opera persistence path> <XML config Opera persistence path>");
                Console.WriteLine("Full volumes are reprocessed for topological reconstruction only.");
                Console.WriteLine("---------------- DB volume example: db:\\8\\17723900.vol");
                Console.WriteLine("First number is ID_EVENTBRICK, second is ID_VOLUME");
                Console.WriteLine("---------------- XML list file example (source = filesystem):");
                Input inputlist = new Input();
                inputlist.Zones            = new Zone[3];
                inputlist.Zones[0]         = new Zone();
                inputlist.Zones[0].SheetId = 8;
                inputlist.Zones[0].Source  = @"\\myserver.mydomain\myshare\plate_08.tlg";
                inputlist.Zones[0].Z       = 0.0;
                inputlist.Zones[0].AlignmentIgnoreListPath = @"\\myserver\mydomain\myshare\alignignore_plate_08.txt";
                inputlist.Zones[1]         = new Zone();
                inputlist.Zones[1].SheetId = 9;
                inputlist.Zones[1].Source  = @"\\myserver.mydomain\myshare\plate_09.tlg";
                inputlist.Zones[1].Z       = -1300.0;
                inputlist.Zones[2]         = new Zone();
                inputlist.Zones[2].SheetId = 10;
                inputlist.Zones[2].Source  = @"\\myserver.mydomain\myshare\plate_10.tlg";
                inputlist.Zones[2].Z       = -2600.0;
                xmls = new System.Xml.Serialization.XmlSerializer(typeof(BatchReconstruct.Input));
                xmls.Serialize(Console.Out, inputlist);
                Console.WriteLine();
                Console.WriteLine("---------------- XML list file example (source = OperaDB):");
                inputlist.Zones[0].Source = @"db:\1002323.tlg";
                inputlist.Zones[1].Source = @"db:\1006326.tlg";
                inputlist.Zones[2].Source = @"db:\1009724.tlg";
                xmls.Serialize(Console.Out, inputlist);
                Console.WriteLine();
                Console.WriteLine("---------------- XML config file syntax:");
                Console.WriteLine("XML configuration syntax:");
                BatchReconstruct.Config C = new BatchReconstruct.Config();
                C.ReconstructorConfig = (Configuration) new AlphaOmegaReconstructor().Config;
                xmls = new System.Xml.Serialization.XmlSerializer(typeof(BatchReconstruct.Config));
                xmls.Serialize(Console.Out, C);
                Console.WriteLine();
                return;
            }
#if !(DEBUG)
            try
#endif
            {
                AlphaOmegaReconstructor R = new AlphaOmegaReconstructor();
                System.Xml.Serialization.XmlSerializer xmls = null;

                xmls = new System.Xml.Serialization.XmlSerializer(typeof(BatchReconstruct.Config));
                Config config = (Config)xmls.Deserialize(new System.IO.StringReader(((SySal.OperaDb.ComputingInfrastructure.ProgramSettings)SySal.OperaPersistence.Restore(args[2], typeof(SySal.OperaDb.ComputingInfrastructure.ProgramSettings))).Settings));
                R.Config   = (SySal.Management.Configuration)config.ReconstructorConfig;
                R.Progress = new SySal.TotalScan.dProgress(Progress);
                R.Report   = new SySal.TotalScan.dReport(Report);

                System.Text.RegularExpressions.Regex volrgx = new System.Text.RegularExpressions.Regex(@"db:\\(\d+)\\(\d+)\.vol");
                System.Text.RegularExpressions.Match mrgx   = volrgx.Match(args[0].ToLower());
                Input inputlist = null;
                SySal.TotalScan.Volume OldVol = null;
                if (args[0].ToLower().EndsWith(".tsr"))
                {
                    OldVol = (SySal.TotalScan.Volume)SySal.OperaPersistence.Restore(args[0], typeof(SySal.TotalScan.Volume));
                }
                else
                {
                    if (mrgx.Success && mrgx.Length == args[0].Length)
                    {
                        SySal.OperaDb.OperaDbCredentials cred = SySal.OperaDb.OperaDbCredentials.CreateFromRecord();
                        SySal.OperaDb.OperaDbConnection  conn = new SySal.OperaDb.OperaDbConnection(cred.DBServer, cred.DBUserName, cred.DBPassword);
                        conn.Open();
                        System.Data.DataSet ds = new System.Data.DataSet();
                        new SySal.OperaDb.OperaDbDataAdapter("SELECT TB_VOLUME_SLICES.ID_PLATE, TB_VOLUME_SLICES.ID_ZONE, VW_PLATES.Z FROM TB_VOLUME_SLICES INNER JOIN VW_PLATES ON (TB_VOLUME_SLICES.ID_EVENTBRICK = VW_PLATES.ID_EVENTBRICK AND TB_VOLUME_SLICES.ID_PLATE = VW_PLATES.ID) WHERE TB_VOLUME_SLICES.DAMAGED = 'N' AND TB_VOLUME_SLICES.ID_EVENTBRICK = " + mrgx.Groups[1].Value + " AND TB_VOLUME_SLICES.ID_VOLUME = " + mrgx.Groups[2].Value + " ORDER BY VW_PLATES.Z DESC", conn, null).Fill(ds);
                        inputlist       = new Input();
                        inputlist.Zones = new Zone[ds.Tables[0].Rows.Count];
                        int sli;
                        for (sli = 0; sli < ds.Tables[0].Rows.Count; sli++)
                        {
                            inputlist.Zones[sli]         = new Zone();
                            inputlist.Zones[sli].SheetId = Convert.ToInt32(ds.Tables[0].Rows[sli][0]);
                            inputlist.Zones[sli].Source  = "db:\\" + mrgx.Groups[1] + "\\" + ds.Tables[0].Rows[sli][1].ToString() + ".tlg";
                            inputlist.Zones[sli].Z       = Convert.ToDouble(ds.Tables[0].Rows[sli][2]);
                        }
                        SySal.OperaPersistence.Connection            = conn;
                        SySal.OperaPersistence.LinkedZoneDetailLevel = SySal.OperaDb.Scanning.LinkedZone.DetailLevel.BaseFull;
                    }
                    else
                    {
                        System.IO.StreamReader r = new System.IO.StreamReader(args[0]);
                        xmls      = new System.Xml.Serialization.XmlSerializer(typeof(BatchReconstruct.Input));
                        inputlist = (Input)xmls.Deserialize(r);
                        r.Close();
                    }

                    int i, j, c;
                    for (i = 0; i < inputlist.Zones.Length; i++)
                    {
                        for (j = i + 1; j < inputlist.Zones.Length; j++)
                        {
                            if (inputlist.Zones[i].SheetId == inputlist.Zones[j].SheetId)
                            {
                                Console.WriteLine("Duplicate SheetId found. Sheets will be renumbered with the default sequence.");
                                for (j = 0; j < inputlist.Zones.Length; j++)
                                {
                                    inputlist.Zones[j].SheetId = j;
                                }
                                i = inputlist.Zones.Length;
                                break;
                            }
                        }
                    }
                    for (i = 0; i < inputlist.Zones.Length; i++)
                    {
                        SySal.Scanning.Plate.IO.OPERA.LinkedZone lz = (SySal.Scanning.Plate.IO.OPERA.LinkedZone)SySal.OperaPersistence.Restore(inputlist.Zones[i].Source, typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone));
                        c = lz.Length;
                        SySal.TotalScan.Segment[] segs = new SySal.TotalScan.Segment[c];


                        double[] zcor = new double[c];
                        for (j = 0; j < c; j++)
                        {
                            zcor[j] = lz[j].Info.Intercept.Z;
                        }

                        double zmean = NumericalTools.Fitting.Average(zcor);
                        double dgap;
                        for (j = 0; j < c; j++)
                        {
                            SySal.Tracking.MIPEmulsionTrackInfo info = lz[j].Info;
                            segs[j]           = new SySal.TotalScan.Segment(info, new SySal.TotalScan.BaseTrackIndex(j));
                            dgap              = zmean - info.Intercept.Z;
                            info.Intercept.Z  = zmean;
                            info.Intercept.X += info.Slope.X * dgap;
                            info.Intercept.Y += info.Slope.Y * dgap;
                            info.TopZ        += dgap;
                            info.BottomZ     += dgap;

                            info.Intercept.Z = inputlist.Zones[i].Z;
                            double tmptopz = info.TopZ;
                            double tmpbotz = info.BottomZ;
                            dgap         = zmean - tmptopz;
                            info.TopZ    = inputlist.Zones[i].Z - dgap;
                            info.BottomZ = inputlist.Zones[i].Z - (tmptopz - tmpbotz) - dgap;
                        }

                        SySal.BasicTypes.Vector refc = new SySal.BasicTypes.Vector();
                        refc.Z = inputlist.Zones[i].Z;
                        SySal.TotalScan.Layer tmpLayer = new SySal.TotalScan.Layer(i, /*System.Convert.ToInt64(mrgx.Groups[1].Value)*/ 0, (int)inputlist.Zones[i].SheetId, 0, refc);
                        tmpLayer.AddSegments(segs);
                        R.AddLayer(tmpLayer);
                        if (inputlist.Zones[i].AlignmentIgnoreListPath != null && inputlist.Zones[i].AlignmentIgnoreListPath.Trim().Length != 0)
                        {
                            if (inputlist.Zones[i].AlignmentIgnoreListPath.ToLower().EndsWith(".tlg"))
                            {
                                R.SetAlignmentIgnoreList(i, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.BaseTrackIgnoreAlignment)SySal.OperaPersistence.Restore(inputlist.Zones[i].AlignmentIgnoreListPath, typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone.BaseTrackIgnoreAlignment))).Ids);
                            }
                            else
                            {
                                System.IO.StreamReader       r             = new System.IO.StreamReader(inputlist.Zones[i].AlignmentIgnoreListPath.Trim());
                                System.Collections.ArrayList tmpignorelist = new System.Collections.ArrayList();
                                string line;
                                while ((line = r.ReadLine()) != null)
                                {
                                    try
                                    {
                                        tmpignorelist.Add(System.Convert.ToInt32(line));
                                    }
                                    catch (Exception) { }
                                }
                                ;
                                r.Close();
                                R.SetAlignmentIgnoreList(i, (int[])tmpignorelist.ToArray(typeof(int)));
                            }
                        }

                        Console.WriteLine("Loaded sheet {0} Id {1} Tracks {2}", i, inputlist.Zones[i].SheetId, c);
                        lz = null;
                    }
                }
                SySal.TotalScan.Volume V = (OldVol == null) ? R.Reconstruct() : R.RecomputeVertices(OldVol);
                Console.WriteLine("Result written to: " + SySal.OperaPersistence.Persist(args[1], V));
            }
#if !(DEBUG)
            catch (Exception x)
            {
                Console.Error.WriteLine(x.ToString());
            }
#endif
        }
예제 #5
0
파일: Program.cs 프로젝트: kryssb/SySal.NET
        static void Main(string[] args)
        {
            if (args.Length > 0 && String.Compare(args[0], "/fulldump", true) == 0)
            {
                FullZoneDump = true;

                string[] oldargs = args;
                int      i;
                args = new string[oldargs.Length - 1];
                for (i = 0; i < args.Length; i++)
                {
                    args[i] = oldargs[i + 1];
                }
                oldargs = null;
            }

            System.Xml.Serialization.XmlSerializer xmls = null;
            if (args.Length == 5)
            {
                MakeSlopeAdjustment = true;

                try
                {
                    xmls = new System.Xml.Serialization.XmlSerializer(typeof(AdjustTrackParameterSet));
                    C    = new AdjustTrackParameterSet();
                    C    = (AdjustTrackParameterSet)xmls.Deserialize(new System.IO.StreamReader(args[4]));
                    xmls = null;
                    C    = null;
                }
                catch
                {
                    try
                    {
                        xmls = new System.Xml.Serialization.XmlSerializer(typeof(SySal.Executables.BatchLink.Config));
                        SySal.Executables.BatchLink.Config config = (SySal.Executables.BatchLink.Config)xmls.Deserialize(new System.IO.StreamReader(args[4]));
                        xmls = null;
                        C    = new AdjustTrackParameterSet();
                        C.BottomDeltaSlopeX = config.BottomDeltaSlopeX;
                        C.BottomDeltaSlopeY = config.BottomDeltaSlopeY;
                        C.BottomMultSlopeX  = config.BottomMultSlopeX;
                        C.BottomMultSlopeY  = config.BottomMultSlopeY;
                        C.TopDeltaSlopeX    = config.TopDeltaSlopeX;
                        C.TopDeltaSlopeY    = config.TopDeltaSlopeY;
                        C.TopMultSlopeX     = config.TopMultSlopeX;
                        C.TopMultSlopeY     = config.TopMultSlopeY;
                    }
                    catch
                    {
                        throw new Exception("correction path non correct");
                    }
                }
                string[] oldargs = args;
                int      i;
                args = new string[oldargs.Length - 1];
                for (i = 0; i < args.Length; i++)
                {
                    args[i] = oldargs[i];
                }
                oldargs = null;
            }

            if (args.Length != 4)
            {
                Console.WriteLine("usage: DumpZone [/fulldump] <StartupFile path> <RWC path> <TLG path> <series> [XML correction path]");
                Console.WriteLine("XML correction syntax could be the batchlink configuration, otherwise");
                Console.WriteLine("XML correction syntax:");
                xmls = new System.Xml.Serialization.XmlSerializer(typeof(AdjustTrackParameterSet));
                System.IO.StringWriter ss = new System.IO.StringWriter();
                xmls.Serialize(ss, C);
                Console.WriteLine(ss.ToString());
                ss.Close();
                return;
            }

            string startupfile = args[0];
            string rwcpath     = args[1];
            string tlgpath     = args[2];
            int    series      = System.Convert.ToInt32(args[3]);

            xmls        = new System.Xml.Serialization.XmlSerializer(typeof(SySal.DAQSystem.Drivers.ScanningStartupInfo));
            StartupInfo = (SySal.DAQSystem.Drivers.ScanningStartupInfo)xmls.Deserialize(new System.IO.StreamReader(startupfile));
            xmls        = null;

            Conn = new SySal.OperaDb.OperaDbConnection(StartupInfo.DBServers, StartupInfo.DBUserName, StartupInfo.DBPassword);
            Conn.Open();
            SySal.OperaDb.Schema.DB = Conn;

            Trans = Conn.BeginTransaction();

            SySal.Scanning.Plate.IO.OPERA.LinkedZone lz = null;
            try
            {
                lz = (SySal.Scanning.Plate.IO.OPERA.LinkedZone)SySal.OperaPersistence.Restore(tlgpath, typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone));

                if (MakeSlopeAdjustment == true && C != null)
                {
                    AdjustSlopes(lz);
                }

                DumpZone(tlgpath, lz, StartupInfo.Plate.BrickId, StartupInfo.Plate.PlateId, StartupInfo.ProcessOperationId, series, StartupInfo.RawDataPath, System.IO.File.GetCreationTime(rwcpath), System.DateTime.Now, Conn, Trans);

                Trans.Commit();
            }
            catch (Exception x)
            {
                if (Trans != null)
                {
                    Trans.Rollback();
                }
                Console.WriteLine(x.Message);
            }
            Conn.Close();
        }
예제 #6
0
파일: Program.cs 프로젝트: kryssb/SySal.NET
        private static long DumpZone(string tlgpath, SySal.Scanning.Plate.IO.OPERA.LinkedZone lz, long db_brick_id, long db_plate_id, long db_procop_id, long series, string rawdatapath, DateTime starttime, DateTime endtime, SySal.OperaDb.OperaDbConnection conn, SySal.OperaDb.OperaDbTransaction trans)
        {
            try
            {
                long db_id_zone = 0;

                int    s, i, n;
                double dz, basez;
                SySal.Scanning.Plate.Side side;

                SySal.DAQSystem.Scanning.IntercalibrationInfo transform = lz.Transform;
                double TDX = transform.TX - transform.MXX * transform.RX - transform.MXY * transform.RY;
                double TDY = transform.TY - transform.MYX * transform.RX - transform.MYY * transform.RY;

                //zone
                db_id_zone = SySal.OperaDb.Schema.TB_ZONES.Insert(db_brick_id, db_plate_id, db_procop_id, db_id_zone,
                                                                  lz.Extents.MinX, lz.Extents.MaxX, lz.Extents.MinY, lz.Extents.MaxY,
                                                                  tlgpath, starttime, endtime, series,
                                                                  transform.MXX, transform.MXY, transform.MYX, transform.MYY, TDX, TDY);

                if (FullZoneDump == false)
                {
                    return(db_id_zone);
                }

                //views
                for (s = 0; s < 2; s++)
                {
                    if (s == 0)
                    {
                        side  = lz.Top;
                        basez = lz.Top.BottomZ;
                    }
                    else
                    {
                        side  = lz.Bottom;
                        basez = lz.Bottom.TopZ;
                    }
                    n = ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.Side)side).ViewCount;
                    for (i = 0; i < n; i++)
                    {
                        SySal.Scanning.Plate.IO.OPERA.LinkedZone.View vw = ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.Side)side).View(i);
                        SySal.OperaDb.Schema.TB_VIEWS.Insert(db_brick_id, db_id_zone, s + 1,
                                                             //i + 1,
                                                             vw.Id + 1,
                                                             vw.TopZ, vw.BottomZ, vw.Position.X, vw.Position.Y);
                    }
                }
                SySal.OperaDb.Schema.TB_VIEWS.Flush();

                int TrackId     = 0;
                int UpTrackId   = 0;
                int DownTrackId = 0;

                SySal.Tracking.MIPEmulsionTrackInfo info  = null;
                SySal.Tracking.MIPEmulsionTrackInfo tinfo = null;
                SySal.Tracking.MIPEmulsionTrackInfo binfo = null;

                //Basetracks
                for (i = 0; i < lz.Length; i++)
                {
                    if (lz[i].Info.Sigma >= 0)
                    {
                        info  = lz[i].Info;
                        tinfo = lz[i].Top.Info;
                        binfo = lz[i].Bottom.Info;
                    }
                    else
                    {
                        continue;
                    }

                    DownTrackId++;
                    basez = lz.Top.BottomZ;
                    dz    = (basez - tinfo.Intercept.Z);
                    SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Insert(db_brick_id, db_id_zone,
                                                                  1, DownTrackId,
                                                                  tinfo.Intercept.X + tinfo.Slope.X * dz,
                                                                  tinfo.Intercept.Y + tinfo.Slope.Y * dz,
                                                                  tinfo.Slope.X,
                                                                  tinfo.Slope.Y,
                                                                  tinfo.Count,
                                                                  tinfo.AreaSum,
                                                                  System.DBNull.Value,
                                                                  tinfo.Sigma, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz.Top[i])).View.Id + 1);

                    UpTrackId++;
                    basez = lz.Bottom.TopZ;
                    dz    = (basez - binfo.Intercept.Z);
                    SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Insert(db_brick_id, db_id_zone,
                                                                  2, UpTrackId,
                                                                  binfo.Intercept.X + binfo.Slope.X * dz,
                                                                  binfo.Intercept.Y + binfo.Slope.Y * dz,
                                                                  binfo.Slope.X,
                                                                  binfo.Slope.Y,
                                                                  binfo.Count,
                                                                  binfo.AreaSum,
                                                                  System.DBNull.Value,
                                                                  binfo.Sigma, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz.Bottom[i])).View.Id + 1);

                    TrackId++;
                    basez = ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz[i].Top)).View.BottomZ;
                    dz    = 0; //TODO (basez - info.Intercept.Z);
                    SySal.OperaDb.Schema.TB_MIPBASETRACKS.Insert(db_brick_id, db_id_zone,
                                                                 TrackId,
                                                                 info.Intercept.X + info.Slope.X * dz,
                                                                 info.Intercept.Y + info.Slope.Y * dz,
                                                                 info.Slope.X,
                                                                 info.Slope.Y,
                                                                 info.Count,
                                                                 info.AreaSum, System.DBNull.Value, info.Sigma,
                                                                 1, DownTrackId, 2, UpTrackId);
                }

                //Microtracks
                for (i = 0; i < lz.Length; i++)
                {
                    if (lz[i].Info.Sigma >= 0)
                    {
                        continue;
                    }
                    else if (lz[i].Top.Info.Sigma >= 0)
                    {
                        tinfo = lz[i].Top.Info;

                        DownTrackId++;
                        basez = lz.Top.BottomZ;
                        dz    = (basez - tinfo.Intercept.Z);
                        SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Insert(db_brick_id, db_id_zone,
                                                                      1, DownTrackId,
                                                                      tinfo.Intercept.X + tinfo.Slope.X * dz,
                                                                      tinfo.Intercept.Y + tinfo.Slope.Y * dz,
                                                                      tinfo.Slope.X,
                                                                      tinfo.Slope.Y,
                                                                      tinfo.Count,
                                                                      tinfo.AreaSum,
                                                                      System.DBNull.Value,
                                                                      tinfo.Sigma, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz.Top[i])).View.Id + 1);
                    }
                    else if (lz[i].Bottom.Info.Sigma >= 0)
                    {
                        binfo = lz[i].Bottom.Info;
                        UpTrackId++;
                        basez = lz.Bottom.TopZ;
                        dz    = (basez - binfo.Intercept.Z);
                        SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Insert(db_brick_id, db_id_zone,
                                                                      2, UpTrackId,
                                                                      binfo.Intercept.X + binfo.Slope.X * dz,
                                                                      binfo.Intercept.Y + binfo.Slope.Y * dz,
                                                                      binfo.Slope.X,
                                                                      binfo.Slope.Y,
                                                                      binfo.Count,
                                                                      binfo.AreaSum,
                                                                      System.DBNull.Value,
                                                                      binfo.Sigma, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz.Bottom[i])).View.Id + 1);
                    }
                }

                SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Flush();
                SySal.OperaDb.Schema.TB_MIPBASETRACKS.Flush();

                return(db_id_zone);
            }
            catch (Exception x)
            {
                throw x;
            }
        }
예제 #7
0
파일: Exe.cs 프로젝트: kryssb/SySal.NET
        private static void OneZoneIntercalibration(string [] args, ref SySal.DAQSystem.Scanning.IntercalibrationInfo intercal, bool rewrite)
        {
            int i, j, n;
            int MinMatches = Convert.ToInt32(args[8]);

            SySal.Scanning.Plate.IO.OPERA.LinkedZone reflz   = (SySal.Scanning.Plate.IO.OPERA.LinkedZone)SySal.OperaPersistence.Restore(args[1], typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone));
            SySal.Tracking.MIPEmulsionTrackInfo []   refzone = new SySal.Tracking.MIPEmulsionTrackInfo[reflz.Length];
            for (i = 0; i < refzone.Length; i++)
            {
                refzone[i] = reflz[i].Info;
            }
            reflz = null;
            GC.Collect();
            SySal.Scanning.Plate.IO.OPERA.LinkedZone caliblz   = (SySal.Scanning.Plate.IO.OPERA.LinkedZone)SySal.OperaPersistence.Restore(args[2], typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone));
            SySal.Tracking.MIPEmulsionTrackInfo []   calibzone = new SySal.Tracking.MIPEmulsionTrackInfo[caliblz.Length];
            for (i = 0; i < calibzone.Length; i++)
            {
                calibzone[i] = caliblz[i].Info;
            }
            if (!rewrite)
            {
                caliblz = null;
            }
            GC.Collect();
            SySal.Processing.QuickMapping.QuickMapper   QMap = new SySal.Processing.QuickMapping.QuickMapper();
            SySal.Processing.QuickMapping.Configuration C    = (SySal.Processing.QuickMapping.Configuration)QMap.Config;
            double postol   = Convert.ToDouble(args[4], System.Globalization.CultureInfo.InvariantCulture);
            double leverarm = Convert.ToDouble(args[6], System.Globalization.CultureInfo.InvariantCulture);

            C.PosTol    = postol + leverarm;
            C.SlopeTol  = Convert.ToDouble(args[5], System.Globalization.CultureInfo.InvariantCulture);
            QMap.Config = C;
            double ZProj     = Convert.ToDouble(args[3], System.Globalization.CultureInfo.InvariantCulture);
            double maxoffset = Convert.ToDouble(args[7], System.Globalization.CultureInfo.InvariantCulture);

            SySal.Scanning.PostProcessing.PatternMatching.TrackPair [] pairs = QMap.Match(refzone, calibzone, ZProj, maxoffset, maxoffset);
            if (pairs.Length < MinMatches)
            {
                Console.Error.WriteLine("Too few matching tracks: " + MinMatches.ToString() + " required, " + pairs.Length + " obtained. Aborting.");
                return;
            }
            Console.WriteLine("Matches: " + pairs.Length);

            n = pairs.Length;
            double [,] indep = new double[2, n];
            double [] dep   = new double[n];
            double [] res   = new double[3];
            double    dummy = 0.0;

            for (i = 0; i < n; i++)
            {
                indep[0, i] = ((SySal.Tracking.MIPEmulsionTrackInfo)(pairs[i].Second.Track)).Intercept.X - intercal.RX;
                indep[1, i] = ((SySal.Tracking.MIPEmulsionTrackInfo)(pairs[i].Second.Track)).Intercept.Y - intercal.RY;
                dep[i]      = pairs[i].First.Info.Intercept.X - intercal.RX;
            }
            NumericalTools.Fitting.MultipleLinearRegression(indep, dep, ref res, ref dummy);
            Console.WriteLine("{0}\t{1}\t{2}\t{3}", res[0], res[1], res[2], dummy);
            intercal.TX = res[0]; intercal.MXX = res[1]; intercal.MXY = res[2];
            for (i = 0; i < n; i++)
            {
                indep[0, i] = ((SySal.Tracking.MIPEmulsionTrackInfo)(pairs[i].Second.Track)).Intercept.X - intercal.RX;
                indep[1, i] = ((SySal.Tracking.MIPEmulsionTrackInfo)(pairs[i].Second.Track)).Intercept.Y - intercal.RY;
                dep[i]      = pairs[i].First.Info.Intercept.Y - intercal.RY;
            }
            NumericalTools.Fitting.MultipleLinearRegression(indep, dep, ref res, ref dummy);
            Console.WriteLine("{0}\t{1}\t{2}\t{3}", res[0], res[1], res[2], dummy);
            intercal.TY = res[0]; intercal.MYX = res[1]; intercal.MYY = res[2];

            System.Collections.ArrayList a_goodpairs = new System.Collections.ArrayList();
            foreach (SySal.Scanning.PostProcessing.PatternMatching.TrackPair p in pairs)
            {
                dummy = Math.Abs(intercal.TX + intercal.MXX * (p.Second.Info.Intercept.X - intercal.RX) + intercal.MXY * (p.Second.Info.Intercept.Y - intercal.RY) - p.First.Info.Intercept.X + intercal.RX);
                if (dummy > postol)
                {
                    continue;
                }
                dummy = Math.Abs(intercal.TY + intercal.MYX * (p.Second.Info.Intercept.X - intercal.RX) + intercal.MYY * (p.Second.Info.Intercept.Y - intercal.RY) - p.First.Info.Intercept.Y + intercal.RY);
                if (dummy > postol)
                {
                    continue;
                }
                a_goodpairs.Add(p);
            }
            Console.WriteLine("remaining " + a_goodpairs.Count);

            SySal.Scanning.PostProcessing.PatternMatching.TrackPair [] goodpairs = (SySal.Scanning.PostProcessing.PatternMatching.TrackPair [])a_goodpairs.ToArray(typeof(SySal.Scanning.PostProcessing.PatternMatching.TrackPair));
            n     = goodpairs.Length;
            indep = new double[2, n];
            dep   = new double[n];
            for (i = 0; i < n; i++)
            {
                indep[0, i] = ((SySal.Tracking.MIPEmulsionTrackInfo)(goodpairs[i].Second.Track)).Intercept.X - intercal.RX;
                indep[1, i] = ((SySal.Tracking.MIPEmulsionTrackInfo)(goodpairs[i].Second.Track)).Intercept.Y - intercal.RY;
                dep[i]      = goodpairs[i].First.Info.Intercept.X - intercal.RX;
            }
            NumericalTools.Fitting.MultipleLinearRegression(indep, dep, ref res, ref dummy);
            Console.WriteLine("{0}\t{1}\t{2}\t{3}", res[0], res[1], res[2], dummy);
            intercal.TX = res[0]; intercal.MXX = res[1]; intercal.MXY = res[2];
            for (i = 0; i < n; i++)
            {
                indep[0, i] = ((SySal.Tracking.MIPEmulsionTrackInfo)(goodpairs[i].Second.Track)).Intercept.X - intercal.RX;
                indep[1, i] = ((SySal.Tracking.MIPEmulsionTrackInfo)(goodpairs[i].Second.Track)).Intercept.Y - intercal.RY;
                dep[i]      = goodpairs[i].First.Info.Intercept.Y - intercal.RY;
            }
            NumericalTools.Fitting.MultipleLinearRegression(indep, dep, ref res, ref dummy);
            Console.WriteLine("{0}\t{1}\t{2}\t{3}", res[0], res[1], res[2], dummy);
            intercal.TY = res[0]; intercal.MYX = res[1]; intercal.MYY = res[2];
            CheckIntercalibration(intercal);
            if (rewrite)
            {
                MyTransformation.Transformation = intercal;
                SySal.OperaPersistence.Persist(args[2], new LinkedZone(caliblz));
            }
        }
예제 #8
0
파일: Exe.cs 프로젝트: kryssb/SySal.NET
        private static void ThreeZoneIntercalibration(string [] args, ref SySal.DAQSystem.Scanning.IntercalibrationInfo intercal, bool rewrite)
        {
            int i, n;
            int MinMatches = Convert.ToInt32(args[11]);

            SySal.Processing.QuickMapping.QuickMapper   QMap = new SySal.Processing.QuickMapping.QuickMapper();
            SySal.Processing.QuickMapping.Configuration C    = (SySal.Processing.QuickMapping.Configuration)QMap.Config;
            C.PosTol    = Convert.ToDouble(args[8], System.Globalization.CultureInfo.InvariantCulture);
            C.SlopeTol  = Convert.ToDouble(args[9], System.Globalization.CultureInfo.InvariantCulture);
            QMap.Config = C;
            double ZProj     = Convert.ToDouble(args[7], System.Globalization.CultureInfo.InvariantCulture);
            double maxoffset = Convert.ToDouble(args[10], System.Globalization.CultureInfo.InvariantCulture);

            MapPos [] mappositions = new MapPos[3];

            SySal.Scanning.Plate.IO.OPERA.LinkedZone [] savezones = new SySal.Scanning.Plate.IO.OPERA.LinkedZone[3];
            for (n = 0; n < 3; n++)
            {
                SySal.Scanning.Plate.IO.OPERA.LinkedZone reflz   = (SySal.Scanning.Plate.IO.OPERA.LinkedZone)SySal.OperaPersistence.Restore(args[1 + n * 2], typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone));
                SySal.Tracking.MIPEmulsionTrackInfo []   refzone = new SySal.Tracking.MIPEmulsionTrackInfo[reflz.Length];
                for (i = 0; i < refzone.Length; i++)
                {
                    refzone[i] = reflz[i].Info;
                }
                reflz = null;
                SySal.Scanning.Plate.IO.OPERA.LinkedZone caliblz = (SySal.Scanning.Plate.IO.OPERA.LinkedZone)SySal.OperaPersistence.Restore(args[2 + n * 2], typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone));
                if (rewrite)
                {
                    savezones[n] = caliblz;
                }
                SySal.Tracking.MIPEmulsionTrackInfo [] calibzone = new SySal.Tracking.MIPEmulsionTrackInfo[caliblz.Length];
                for (i = 0; i < calibzone.Length; i++)
                {
                    calibzone[i] = caliblz[i].Info;
                }
                caliblz = null;
                GC.Collect();
                Console.Write("Zone #" + n.ToString() + " ");
                SySal.Scanning.PostProcessing.PatternMatching.TrackPair [] pairs = QMap.Match(refzone, calibzone, ZProj, maxoffset, maxoffset);
                if (pairs.Length < MinMatches)
                {
                    Console.Error.WriteLine("Too few matching tracks: " + MinMatches.ToString() + " required, " + pairs.Length + " obtained. Aborting.");
                    return;
                }
                Console.WriteLine("Matches: " + pairs.Length);
                mappositions[n].SetFromPairs(pairs);
                mappositions[n].X -= intercal.RX;
                mappositions[n].Y -= intercal.RY;
            }
            double x20 = mappositions[2].X - mappositions[0].X;
            double x10 = mappositions[1].X - mappositions[0].X;
            double y20 = mappositions[2].Y - mappositions[0].Y;
            double y10 = mappositions[1].Y - mappositions[0].Y;
            double det = 1.0 / (x10 * y20 - x20 * y10);
            double u20 = mappositions[2].DX - mappositions[0].DX;
            double v20 = mappositions[2].DY - mappositions[0].DY;
            double u10 = mappositions[1].DX - mappositions[0].DX;
            double v10 = mappositions[1].DY - mappositions[0].DY;

            intercal.MXX  = (u10 * y20 - u20 * y10) * det;
            intercal.MXY  = (u20 * x10 - u10 * x20) * det;
            intercal.MYX  = (v10 * y20 - v20 * y10) * det;
            intercal.MYY  = (v20 * x10 - v10 * x20) * det;
            intercal.TX   = mappositions[0].DX - intercal.MXX * mappositions[0].X - intercal.MXY * mappositions[0].Y;
            intercal.TY   = mappositions[0].DY - intercal.MYX * mappositions[0].X - intercal.MYY * mappositions[0].Y;
            intercal.MXX += 1.0;
            intercal.MYY += 1.0;
            CheckIntercalibration(intercal);
            if (rewrite)
            {
                MyTransformation.Transformation = intercal;
                for (n = 0; n < 3; n++)
                {
                    SySal.OperaPersistence.Persist(args[2 + n * 2], new LinkedZone(savezones[n]));
                }
            }
        }
예제 #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 + "\".");
        }