示例#1
0
        public static void forma1()
        {
            /*Lectura parcial y automatica de parte de cabezera*/

            Fits f = new Fits("cubo_ing_comp.fits");

            BasicHDU[] hdus = f.Read();

            Console.WriteLine("Longitud: " + hdus.Length);

            for (int i = 0; i < hdus.Length; i += 1)
            {
                hdus[i].Info();
            }
            try {
            } catch {
            }

            ImageData datos = (ImageData)hdus[0].Kernel;

            float[,,] cubo = (float[, , ])datos.DataArray;

            Console.WriteLine("cubo: " + cubo[0, 0, 0]);

            f.Close();
        }
示例#2
0
 /// <summary>
 /// Закрытие FITS-файла
 /// </summary>
 public void Free()
 {
     if (fits != null)
     {
         fits.Close();
     }
 }
示例#3
0
        public static Image <Gray, UInt16> ReadFITSFile(String ImagePath)
        {
            try
            {
                Fits     f = new Fits(ImagePath);
                ImageHDU h = (ImageHDU)f.ReadHDU();

                System.Array[] img = (System.Array[])h.Kernel;
                f.Close();
                int Width  = img.Count();
                int Height = img.GetLength(0);

                UInt16[][]           ImgConverted   = new UInt16[Width][];
                Image <Gray, UInt16> LastestImageCV = new Image <Gray, UInt16>(Width, Height);
                Int16 MaxNumber = Int16.MaxValue;

                for (int i = 0; i < Width; i++)
                {
                    ImgConverted[i] = new UInt16[Height];
                    for (int j = 0; j < Height; j++)
                    {
                        int Data = MaxNumber + (Int16)img[i].GetValue(j) + 1;
                        ImgConverted[i][j]           = (UInt16)Data;
                        LastestImageCV.Data[i, j, 0] = (UInt16)Data;
                    }
                }

                return(LastestImageCV);
            }
            catch
            {
                return(null);
            }
        }
示例#4
0
        public FitsFileInfo(string filePath)
        {
            FilePath = filePath;
            Fits f    = new Fits(filePath);
            var  hdus = f.Read();

            var headers = hdus.Where(hdu => hdu is ImageHDU).Select(hdu => hdu.Header);

            headers.ToList().ForEach(header =>
            {
                var cur        = header.GetCursor();
                object cardPtr = null;
                // return (HeaderCard) ((DictionaryEntry) this.cursor.Current).Value;
                while ((cardPtr = cur.Current) != null)
                {
                    var card = (HeaderCard)((DictionaryEntry)cardPtr).Value;
                    cur.MoveNext();
                    IList <HeaderKeyValue> keyValues = null;
                    keyValues         = _header.ContainsKey(card.Key) ? _header[card.Key] : new List <HeaderKeyValue>();
                    _header[card.Key] = keyValues;
                    var val           = card.IsStringValue ? new HeaderKeyValue(card.Key, card.Value, card.Comment) : ConvertType(card);
                    keyValues.Add(val);
                }
            });
            f.Close();

            //FileStream s = null;
            //using (s = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            //{
            //    var md5 = MD5.Create();
            //    var hashBytes = md5.ComputeHash(s);
            //    FileHash = Convert.ToBase64String(hashBytes);
            //}
            // Instead of reading the whole file for hash (which will be slow, especially with large
            // files and there can be thousands to read per batch) we just read the headers,
            // and calculate a hash from them. We only care about the indexed headers anyway,
            // if they don't change, nothing in the index needs to change.

            var md5       = MD5.Create();
            var hashBytes = md5.ComputeHash(HeadersToBytes());

            FileHash = Convert.ToBase64String(hashBytes);
            FileInfo finfo = new FileInfo(filePath);

            FileSize = finfo.Length;
        }
示例#5
0
        private void BuildCalSpecDb()
        {
            var db       = new CalSpecDatabase();
            int totalBad = 0;

            string[] lines2 = File.ReadAllLines(@"F:\WORK\tangra3\Tangra 3\VideoOperations\Spectroscopy\AbsFluxCalibration\Standards\AbsFlux-TangraStars.csv");
            for (int i = 1; i < lines2.Length; i++)
            {
                string[] tokens = lines2[i].Split(',');

                string calSpecId    = tokens[0].Trim();
                string RA_FK5_Hours = tokens[1].Trim();
                string DEG_FK5_Deg  = tokens[2].Trim();
                string pmRA         = tokens[3].Trim();
                string pmDec        = tokens[4].Trim();
                string specType     = tokens[5].Trim();
                string magV         = tokens[6].Trim();
                string magBV        = tokens[7].Trim();
                string absFluxId    = tokens[8].Trim();
                string stisFlag     = tokens[9].Trim();
                string fitsFilePath = tokens[10].Trim();
                int    stisFrom     = int.Parse(tokens[11].Trim());
                int    stisTo       = int.Parse(tokens[12].Trim());
                string tyc2         = tokens[13].Trim();
                string ucac4        = tokens[14].Trim();

                if (!string.IsNullOrEmpty(pmRA) && !string.IsNullOrEmpty(pmDec))
                {
                    var star = new CalSpecStar()
                    {
                        CalSpecStarId  = calSpecId,
                        AbsFluxStarId  = absFluxId,
                        STIS_Flag      = stisFlag,
                        FITS_File      = fitsFilePath,
                        TYC2           = tyc2,
                        U4             = ucac4,
                        pmRA           = double.Parse(pmRA),
                        pmDE           = double.Parse(pmDec),
                        MagV           = double.Parse(magV),
                        MagBV          = double.Parse(magBV),
                        SpecType       = specType,
                        RA_J2000_Hours = AstroConvert.ToRightAcsension(RA_FK5_Hours),
                        DE_J2000_Deg   = AstroConvert.ToDeclination(DEG_FK5_Deg)
                    };

                    string filePath = Path.GetFullPath(@"Z:\CALSPEC\current_calspec\" + fitsFilePath);

                    using (var bf = new BufferedFile(filePath, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var fitsFile = new Fits();
                        fitsFile.Read(bf);

                        BasicHDU imageHDU = fitsFile.GetHDU(1);

                        var      table         = (ColumnTable)imageHDU.Data.DataArray;
                        double[] wavelengths   = (double[])table.Columns[0];
                        float[]  fluxes        = (float[])table.Columns[1];
                        short[]  goodnessFlags = (short[])table.Columns[5];

                        for (int j = 0; j < fluxes.Length; j++)
                        {
                            if (wavelengths[j] < stisFrom)
                            {
                                continue;
                            }
                            if (wavelengths[j] > stisTo)
                            {
                                break;
                            }

                            if (goodnessFlags[j] != 0)
                            {
                                star.DataPoints.Add(wavelengths[j], fluxes[j]);
                            }
                            else
                            {
                                totalBad++;
                            }
                        }
                        fitsFile.Close();
                    }

                    db.Stars.Add(star);
                }
            }

            using (var compressedStream = new FileStream(@"F:\WORK\tangra3\Tangra 3\VideoOperations\Spectroscopy\AbsFluxCalibration\Standards\CalSpec.db", FileMode.CreateNew, FileAccess.Write))
                using (var deflateStream = new DeflateStream(compressedStream, CompressionMode.Compress, true))
                {
                    using (var writer = new BinaryWriter(deflateStream))
                    {
                        db.Serialize(writer);
                    }
                }

            using (var compressedStream = new FileStream(@"F:\WORK\tangra3\Tangra 3\VideoOperations\Spectroscopy\AbsFluxCalibration\Standards\CalSpec.db", FileMode.Open, FileAccess.Read))
                using (var deflateStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
                {
                    using (var reader = new BinaryReader(deflateStream))
                    {
                        var db2 = new CalSpecDatabase(reader);
                        Trace.WriteLine(db2.Stars.Count);
                    }
                }

            MessageBox.Show(totalBad.ToString() + " bad entries excluded.");

            string[] fitsFiles = Directory.GetFiles(@"Z:\CALSPEC\current_calspec", "*.fit");

            var dist = new Dictionary <int, int>();

            foreach (string filePath in fitsFiles)
            {
                using (var bf = new BufferedFile(filePath, FileAccess.Read, FileShare.ReadWrite))
                {
                    var fitsFile = new Fits();
                    fitsFile.Read(bf);

                    var bld = new StringBuilder();

                    BasicHDU headerHDU = fitsFile.GetHDU(0);
                    BasicHDU imageHDU  = fitsFile.GetHDU(1);

                    for (int i = 0; i < headerHDU.Header.NumberOfCards; i++)
                    {
                        string cardString = headerHDU.Header.GetCard(i);
                        bld.AppendFormat("# {0}\r\n", cardString);
                    }

                    for (int i = 0; i < imageHDU.Header.NumberOfCards; i++)
                    {
                        string cardString = imageHDU.Header.GetCard(i);
                        bld.AppendFormat("# {0}\r\n", cardString);
                    }

                    var table = (ColumnTable)imageHDU.Data.DataArray;
                    if (table.Columns.Length == 7 &&
                        table.Columns[0] is double[] && table.Columns[1] is float[] && table.Columns[2] is float[] && table.Columns[3] is float[] &&
                        table.Columns[4] is float[] && table.Columns[5] is short[] && table.Columns[6] is float[])
                    {
                        double[] wavelengths   = (double[])table.Columns[0];
                        float[]  fluxes        = (float[])table.Columns[1];
                        float[]  col2          = (float[])table.Columns[2];
                        float[]  col3          = (float[])table.Columns[3];
                        float[]  col4          = (float[])table.Columns[4];
                        short[]  goodnessFlags = (short[])table.Columns[5];
                        float[]  exposures     = (float[])table.Columns[6];

                        for (int i = 0; i < fluxes.Length; i++)
                        {
                            if (wavelengths[i] < 2000)
                            {
                                continue;
                            }
                            if (wavelengths[i] > 15000)
                            {
                                break;
                            }

                            bld.Append(wavelengths[i].ToString().PadLeft(20));
                            bld.Append(fluxes[i].ToString().PadLeft(20));
                            bld.Append(col2[i].ToString().PadLeft(20));
                            bld.Append(col3[i].ToString().PadLeft(20));
                            bld.Append(col4[i].ToString().PadLeft(20));
                            bld.Append(goodnessFlags[i].ToString().PadLeft(15));
                            bld.Append(exposures[i].ToString().PadLeft(15));
                            bld.AppendLine();

                            int expMS = (int)Math.Round(exposures[i] * 1000);
                            if (!dist.ContainsKey(expMS))
                            {
                                dist.Add(expMS, 0);
                            }
                            dist[expMS]++;
                        }
                    }

                    string outFileName = Path.ChangeExtension(filePath, ".txt");
                    File.WriteAllText(outFileName, bld.ToString());
                    fitsFile.Close();
                }
            }

            var output = new StringBuilder();

            foreach (int key in dist.Keys)
            {
                output.AppendFormat("{0}s = {1}\r\n", (key / 1000.0).ToString("0.0"), dist[key]);
            }
            MessageBox.Show(output.ToString());
        }
示例#6
0
        private void BuildAbsFlux()
        {
            var indexFile = new StringBuilder();

            indexFile.AppendLine("BD and HD CALSPEC stars with STIS fluxes between 3000 and 10000 Angstroms");
            indexFile.AppendLine("Name            FK5_Coordinates_J2000      Type    Mag    B-V   File_Name");

            foreach (CalSpecStar star in CalSpecDatabase.Instance.Stars)
            {
                if (star.AbsFluxStarId.StartsWith("TYC"))
                {
                    continue;
                }
                string modifiedId = star.AbsFluxStarId.Replace(" ", "_");
                if (modifiedId.Length < 10)
                {
                    modifiedId += "_";
                }
                while (modifiedId.Length < 10)
                {
                    int firstUnderScorePos = modifiedId.IndexOf("_");
                    modifiedId = modifiedId.Substring(0, firstUnderScorePos) + "_" + modifiedId.Substring(firstUnderScorePos);
                }
                string raStr        = AstroConvert.ToStringValue(star.RA_J2000_Hours, "HH MM SS.TTT");
                string deStr        = AstroConvert.ToStringValue(star.DE_J2000_Deg, "+DD MM SS.TT");
                string dataFileName = Path.GetFileNameWithoutExtension(star.FITS_File) + "_t1.txt";
                string line         = string.Format("{0}{1} {2}    {3}{4}  {5}  {6}\r\n",
                                                    modifiedId.PadRight(14), raStr, deStr,
                                                    star.SpecType.PadRight(7),
                                                    star.MagV.ToString("0.00").PadLeft(5),
                                                    star.MagBV.ToString("0.00").PadLeft(5),
                                                    dataFileName);
                indexFile.Append(line);

                string filePath = Path.GetFullPath(@"Z:\CALSPEC\current_calspec\" + star.FITS_File);

                double wavelengthFrom = star.DataPoints.Keys.Min();
                double wavelengthTo   = star.DataPoints.Keys.Max();
                using (var bf = new BufferedFile(filePath, FileAccess.Read, FileShare.ReadWrite))
                {
                    var fitsFile = new Fits();
                    fitsFile.Read(bf);

                    BasicHDU imageHDU = fitsFile.GetHDU(1);

                    var      table         = (ColumnTable)imageHDU.Data.DataArray;
                    double[] wavelengths   = (double[])table.Columns[0];
                    float[]  fluxes        = (float[])table.Columns[1];
                    float[]  col2          = (float[])table.Columns[2];
                    float[]  col3          = (float[])table.Columns[3];
                    float[]  col4          = (float[])table.Columns[4];
                    short[]  goodnessFlags = (short[])table.Columns[5];
                    float[]  exposures     = (float[])table.Columns[6];

                    var dataFile = new StringBuilder();
                    dataFile.AppendLine("      WAVELENGTH          FLUX     STATERROR      SYSERROR         FWHM     DATAQUAL      TOTEXP");
                    dataFile.AppendLine("              1D            1E            1E            1E           1E           1I          1E");
                    dataFile.AppendLine("       ANGSTROMS          FLAM          FLAM          FLAM    ANGSTROMS         NONE         SEC");

                    for (int j = 0; j < fluxes.Length; j++)
                    {
                        if (wavelengths[j] < wavelengthFrom)
                        {
                            continue;
                        }
                        if (wavelengths[j] > wavelengthTo)
                        {
                            break;
                        }

                        string dataLine = string.Format("{0}{1}{2}{3}{4}            {5}{6}",
                                                        ((int)Math.Round(wavelengths[j])).ToString().PadLeft(16),
                                                        fluxes[j].ToString("E4").PadLeft(14),
                                                        col2[j].ToString("E4").PadLeft(14),
                                                        col3[j].ToString("E4").PadLeft(14),
                                                        col4[j].ToString("#.0").PadLeft(13),
                                                        goodnessFlags[j].ToString(),
                                                        exposures[j].ToString("E1").PadLeft(12));

                        dataFile.AppendLine(dataLine);
                    }

                    fitsFile.Close();

                    File.WriteAllText(@"Z:\AbsFlux\v3\" + dataFileName, dataFile.ToString());
                }
            }
            File.WriteAllText(@"Z:\AbsFlux\v3\AbsFluxCALSPECstars.txt", indexFile.ToString());
        }
示例#7
0
        /// <summary>
        /// Corrige el nombre un archivo "fits".
        /// Dejando intacta la ruta (carpeta) original.
        ///
        /// Además si es un archivo fits, corrige el contenido del campo
        /// object en la misma lógica que la corrección del nombre del archivo.
        ///
        /// Primero se corrige el contenido del archivo y luego el nombre.
        /// </summary>
        /// <param name="archivo"></param>
        private void correctFits(FileInfo archivo)
        {
            logger.Info("correctFits:archivo=" + archivo.Name);
            String ruta;
            String oldFileName;
            String newFileName;
            String extension;
            String oldFullFilename;
            String newFullFilename;

            Boolean requiereRename; //True solo si se detecta que es pertinente un rename

            requiereRename = false;

            ruta            = archivo.DirectoryName;
            oldFileName     = archivo.Name;
            extension       = archivo.Extension;
            newFileName     = archivo.Name;
            oldFullFilename = archivo.FullName;

            if (extension == ".fts")
            {
                requiereRename = true;
                logger.Info(";.fts->.fits");
                newFileName = newFileName.Replace(".fts", ".fits");
            }
            if (oldFileName.Contains("+"))
            {
                requiereRename = true;
                logger.Info(";'+'->'p'");
                newFileName = newFileName.Replace("+", "p");
                ///////////////
                if ((extension == ".fts") || (extension == ".fits"))
                {
                    Fits   fitsFile;
                    String strObject; // El string que hay que corregir.
                    String strCorrectedObject;
                    fitsFile = new Fits(oldFullFilename);
                    BasicHDU hdu;
                    hdu = fitsFile.ReadHDU();
                    HeaderCard hcOBJECT;// Target object name  <---- Asi esta comentado en MaximDL
                    hcOBJECT  = hdu.Header.FindCard("OBJECT");
                    strObject = hcOBJECT.Value;
                    if (strObject.Contains("+"))
                    {
                        strCorrectedObject = strObject.Replace("+", "p");
                        hcOBJECT.Value     = strCorrectedObject;
                    }
                    hdu.Header.Rewrite();
                    fitsFile.Close();
                }

                ///////////////
            }
            if (requiereRename)
            {
                newFullFilename = ruta + Path.DirectorySeparatorChar + newFileName;

                logger.Info(";" + oldFullFilename + "->" + newFullFilename);
                try
                {
                    archivo.MoveTo(newFullFilename);
                }
                catch (Exception e)
                {
                    logger.Error(e.Message);
                }
            }

            //Console.WriteLine("#");
        }
示例#8
0
/// <summary>
/// Revisa las coordenadas de un archivo "fits".
/// Dejando intacta la ruta (carpeta) original.
///
/// Avisa por pantalla:
/// - Si las coordenadas del filename no coinciden con las del fits.
///
/// </summary>
/// <param name="archivo"></param>
        private void revisaRaDecFits(FileInfo archivo)
        {
            //logger.Info("correctFits:archivo=" + archivo.Name);
            String ruta;
            String shortFileName;
            String extension;
            String fullFilename;

            ruta          = archivo.DirectoryName;
            shortFileName = archivo.Name;
            extension     = archivo.Extension;
            fullFilename  = archivo.FullName;

            ///////////////
            if ((extension == ".fts") || (extension == ".fits"))
            {
                Fits   fitsFile;
                String strObject;
                String strObjectRA;
                String strObjectDEC;
                fitsFile = new Fits(fullFilename);
                BasicHDU hdu;
                hdu = fitsFile.ReadHDU();
                HeaderCard hcOBJECT;                            // Target object name  <---- Asi esta comentado en MaximDL
                HeaderCard hcOBJCTRA;                           //  [hms J2000] Target right ascension  <---- Asi esta comentado en MaximDL
                HeaderCard hcOBJCTDEC;                          //  [dms +N J2000] Target declination  <---- Asi esta comentado en MaximDL
                hcOBJECT     = hdu.Header.FindCard("OBJECT");   //OBJECT    = 'F1910178-615834'
                hcOBJCTRA    = hdu.Header.FindCard("OBJCTRA");  //OBJCTRA   = '19 10 17.80'
                hcOBJCTDEC   = hdu.Header.FindCard("OBJCTDEC"); //OBJCTDEC	= '-61 58 34.0'
                strObject    = hcOBJECT.Value;
                strObjectRA  = null;
                strObjectDEC = null;
                if (hcOBJCTRA != null)
                {
                    strObjectRA = hcOBJCTRA.Value;
                }
                if (hcOBJCTDEC != null)
                {
                    strObjectDEC = hcOBJCTDEC.Value;
                }
                fitsFile.Close();
                if ((strObjectRA != null) && (strObject.StartsWith("F")))
                {
                    StringBuilder radec;
                    //strObjectRA = EntreComillas(strObjectRA)[1];
                    radec = new StringBuilder();
                    radec.Append("F");
                    radec.Append(strObjectRA.Replace(" ", "").Replace(".", "").Substring(0, 7));
                    //if (!strObjectDEC.StartsWith("-"))
                    //{
                    //    radec.Append("p");
                    //}
                    radec.Append(strObjectDEC.Replace(" ", "").Replace(".", "").Replace("+", "p").Substring(0, 7));
                    StringBuilder comparacion;
                    comparacion = new StringBuilder();
                    comparacion.Append(strObject);
                    comparacion.Append("==");
                    comparacion.Append(radec);
                    comparacion.Append(" --> ");
                    Boolean match;
                    match = strObject.Equals(radec.ToString());
                    comparacion.Append(match);
                    Console.WriteLine(comparacion.ToString());
                    if (!match)
                    {
                        StringBuilder mensaje;
                        mensaje = new StringBuilder();
                        mensaje.Append(comparacion.ToString());
                        mensaje.Append("\trm\t");
                        mensaje.Append(shortFileName);
                        mensaje.Append("\t");
                        mensaje.Append(fullFilename);
                        Console.WriteLine(mensaje.ToString());
                    }
                }
            }

            ///////////////
        }
示例#9
0
        /// <summary>
        /// Modifica el header de un archivo .fits, previo al envio
        /// del archivo a otro servidor.        /// </summary>
        /// <param name="fitsFullPath"></param>
        /// <returns>True si consigue modificar el header del archivo</returns>
        public Boolean CompletaFitsHeader(String fitsFullPath)
        {
            this.refreshATC02XmlStatus();
            if (!this.atc02Status.IsFresh())
            {
                logger.Info("ATC02 sin datos recientes, no se actualizara Archivo fits '" + fitsFullPath + "'");
                return(false);
            }
            FileInfo archivoFitsNuevo;
            int      test;
            int      testLimit;

            test      = 1;
            testLimit = 4;

            archivoFitsNuevo = new FileInfo(fitsFullPath);
            do
            {
                test++;
                if (archivoFitsNuevo.Exists)
                {
                    break;
                }
                else
                {
                    logger.Warn(String.Format("Archivo '{0}'no existe, intento {1} de {2}, esperando 1 segundo.", fitsFullPath, test, testLimit));
                    System.Threading.Thread.Sleep(1000);
                }
            } while (test <= testLimit);
            if (!archivoFitsNuevo.Exists)
            {
                logger.Error(String.Format("Archivo '{0}'no existe.", fitsFullPath));
                return(false);
            }
            Boolean respuesta;

            respuesta = true; // Solo si ocurre alguna excepcion esta variable sera False
            DateTime Ahora;

            Ahora = DateTime.Now;
            Fits fitsFile;

            System.Threading.Thread.Sleep(1000);
            fitsFile = new Fits(fitsFullPath);

            BasicHDU hdu;

            hdu = fitsFile.ReadHDU();
            HeaderCard hcDATE_OBS; // [ISO 8601] UTC date/time of exposure start
            HeaderCard hcEXPOSURE; // [sec] Duration of exposure

            hcDATE_OBS = hdu.Header.FindCard("DATE-OBS");
            hcEXPOSURE = hdu.Header.FindCard("EXPOSURE");
            DateTime dateObs;

            dateObs = DateTime.Parse(hcDATE_OBS.Value); //// [ISO 8601] UTC date/time of exposure start
            Double exposure;                            // [sec] Duration of exposure

            exposure = Double.Parse(hcEXPOSURE.Value);

            TimeSpan vejezFits; // Tiempo Transcurrido entre termino de exposición y el presente

            vejezFits = Ahora.Subtract(dateObs);
            double vejezSegundos;

            vejezSegundos = ((vejezFits.TotalSeconds) - exposure);
            logger.Info("Vejez archivo FITS=" + vejezSegundos + "[segundos].");
            // Si la vejez del archiv Fits es menor a veinte segundos
            // entonces se modifica el encabezado del fits
            // con la información del ATC02
            if (vejezSegundos < 20)
            {
                HeaderCard hcFocStep;
                HeaderCard hcPriTemp;
                HeaderCard hcSecTemp;
                HeaderCard hcAmbTemp;
                HeaderCard hcSetFan;
                logger.Info("Actualizando archivo FITS:" + fitsFullPath);
                hcFocStep = hdu.Header.FindCard("FOCSTEP");
                hcPriTemp = hdu.Header.FindCard("PRITEMP");
                hcSecTemp = hdu.Header.FindCard("SECTEMP");
                hcAmbTemp = hdu.Header.FindCard("AMBTEMP");
                hcSetFan  = hdu.Header.FindCard("SETFAN");
                if (hcFocStep == null)
                {
                    hcFocStep = new HeaderCard("FOCSTEP");
                    hdu.Header.AddCard(hcFocStep);
                }
                if (hcPriTemp == null)
                {
                    hcPriTemp = new HeaderCard("PRITEMP");
                    hdu.Header.AddCard(hcPriTemp);
                }
                if (hcSecTemp == null)
                {
                    hcSecTemp = new HeaderCard("SECTEMP");
                    hdu.Header.AddCard(hcSecTemp);
                }
                if (hcAmbTemp == null)
                {
                    hcAmbTemp = new HeaderCard("AMBTEMP");
                    hdu.Header.AddCard(hcAmbTemp);
                }
                if (hcSetFan == null)
                {
                    hcSetFan = new HeaderCard("SETFAN");
                    hdu.Header.AddCard(hcSetFan);
                }

                hcFocStep.Value = ("" + Atc02Xml.BflToFocSetp(this.atc02Status.FocusPosition));
                hcPriTemp.Value = ("" + this.atc02Status.PrimaryTemperature);
                hcSecTemp.Value = ("" + this.atc02Status.SecondaryTemperature);
                hcAmbTemp.Value = ("" + this.atc02Status.AmbientTemperature);
                hcSetFan.Value  = ("" + this.atc02Status.FanPower);
                System.Threading.Thread.Sleep(4000);
                try
                {
                    hdu.Header.Rewrite();
                }
                catch (Exception)
                {
                    respuesta = false;
                    logger.Error("Error en: hdu.Header.Rewrite();");
                }
            }
            fitsFile.Close();
            // Permitimos al sistema que guarde los cambios en el archivo fits.
            System.Threading.Thread.Sleep(1000);
            return(respuesta);
        }
示例#10
0
        private void ImportFile(string filePath)
        {
            Fits           nomTamfits      = new Fits(filePath);
            FitsCollection foundCollection = null;
            string         fileName        = Path.GetFileNameWithoutExtension(filePath);
            string         moleculeName    = fileName.Split(splitChar)[1];
            string         name            = fileName.Split(splitChar)[0];

            bool foundName     = false;
            bool foundMolecule = false;

            foreach (FitsCollection fitsCollection in FitsCollections)
            {
                if (name.Equals(fitsCollection.Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    foundName       = true;
                    foundCollection = fitsCollection;

                    foreach (FitsFile fitsFile in fitsCollection.FitsFiles)
                    {
                        if (fitsFile.Molecule.Equals(moleculeName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            foundMolecule = true;
                            break;
                        }
                    }

                    break;
                }
            }

            if (!foundName)
            {
                foundCollection = new FitsCollection(name);
                FitsCollections.Add(foundCollection);
            }

            if (!foundMolecule && foundCollection != null)
            {
                foundCollection.AddFitsFile(new FitsFile(nomTamfits, filePath, fileName, moleculeName));
                foundCollection.AddMolecule(moleculeName);
            }

            foundMolecule = false;

            foreach (string molecule in MoleculeNames)
            {
                if (moleculeName.Equals(molecule, StringComparison.InvariantCultureIgnoreCase))
                {
                    foundMolecule = true;
                }
            }

            if (!foundMolecule)
            {
                AddMoleculeName(moleculeName);
                MoleculeCount++;
            }

            nomTamfits.Close();
        }
示例#11
0
        private FitsHeader  ReadFits(string Filename)
        {
/*            double RA;
 *          double DEC;
 *          float[][] imageData;
 *          string LocalDate;
 *          double SiteLong;
 *          double SiteLat; */
            FitsHeader fitsheader = new FitsHeader();


            try
            {
                Fits f = new Fits(Filename);

                ImageHDU h = (ImageHDU)f.ReadHDU();


                //other things we might want:
                // IMAGETYP= 'LIGHT'
                // NAXIS1  =                 7380 /
                // NAXIS2 = 4908
                // EXPTIME =                  6.0 / [s] Exposure duration
                // DATE-LOC= '2020-10-07T01:28:55.164' / Time of observation (local)
                //     GAIN    =                 1208 / Sensor gain
                //     XPIXSZ  =                 4.88 / [um] Pixel X axis size
                // YPIXSZ = 4.88 / [um] Pixel Y axis size
                //     SITELAT =     47.6077777777778 / [deg] Observation site latitude
                // SITELONG = -122.335 / [deg] Observation site longitude]

                fitsheader.ImageType = h.Header.GetStringValue("IMAGETYP");
                fitsheader.NAXIS1    = h.Header.GetIntValue("NAXIS1");
                fitsheader.NAXIS2    = h.Header.GetIntValue("NAXIS2");
                fitsheader.DecDeg    = h.Header.GetDoubleValue("DEC");
                fitsheader.RaDeg     = h.Header.GetDoubleValue("RA") / 15;
                fitsheader.Exposure  = h.Header.GetFloatValue("EXPOSURE");


                fitsheader.LocalDate = DateTime.ParseExact(h.Header.GetStringValue("DATE-LOC"), "yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture);
                fitsheader.UTCDate   = DateTime.ParseExact(h.Header.GetStringValue("DATE-OBS"), "yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture);

                fitsheader.SiteLat     = h.Header.GetDoubleValue("SITELAT");
                fitsheader.SiteLong    = h.Header.GetDoubleValue("SITELONG");
                fitsheader.PixelPitch  = h.Header.GetFloatValue("XPIXSZ");
                fitsheader.Gain        = h.Header.GetIntValue("GAIN");
                fitsheader.SensorTempC = h.Header.GetFloatValue("CCD-TEMP");
                fitsheader.FocalLength = h.Header.GetFloatValue("FOCALLEN");
                fitsheader.Object      = h.Header.GetStringValue("OBJECT");


                /*RA = h.Header.GetDoubleValue("RA") / 15;
                 * DEC = h.Header.GetDoubleValue("DEC");
                 * LocalDate = h.Header.GetStringValue("DATE-LOC");
                 * SiteLat = h.Header.GetDoubleValue("SITELAT");
                 * SiteLong = h.Header.GetDoubleValue("SITELAT");
                 *
                 *
                 * //imageData = (float[][])h.Kernel; */

                f.Close();
            }
            catch { Console.WriteLine("Error opening fits.."); return(fitsheader); }

            return(fitsheader);
        }