/// <summary>Create a tiler.</summary>
 /// <param name="f">The random access device from which image data may be read.
 /// This may be null if the tile information is available from memory.</param>
 /// <param name="fileOffset">The file offset within the RandomAccess device at which
 /// the data begins.</param>
 /// <param name="dims">The actual dimensions of the image.</param>
 /// <param name="base_Renamed">base class (should be a primitive type) of the image.</param>
 public ImageTiler(RandomAccess f, long fileOffset, int[] dims, Type base_Renamed)
 {
     this.f = f;
     this.fileOffset = fileOffset;
     this.dims = dims;
     this.base_Renamed = base_Renamed;
 }
Exemple #2
0
        /// <summary>Create a header by reading the information from the input stream.</summary>
        /// <param name="dis">The input stream to read the data from.</param>
        /// <returns> <CODE>null</CODE> if there was a problem with the header;
        /// otherwise return the header read from the input stream.</returns>
        public static Header ReadHeader(ArrayDataIO dis)
        {
            Header myHeader = new Header();
              try
              {
            myHeader.Read(dis);
              }
              catch(EndOfStreamException)
              {
            // An EOF exception is thrown only if the EOF was detected
            // when reading the first card.  In this case we want
            // to return a null.
            return null;
              }

              return myHeader;
        }
Exemple #3
0
        /// <summary>Read a stream for header data.</summary>
        /// <param name="dis">The input stream to read the data from.</param>
        /// <returns> <CODE>null</CODE> if there was a problem with the header;
        /// otherwise return the header read from the input stream.</returns>
        /// <exception cref="TruncatedFileException"> </exception>"
        public virtual void Read(ArrayDataIO dis)
        {
            if (dis is RandomAccess)
              {
            fileOffset = FitsUtil.FindOffset(dis);
              }
              else
              {
            fileOffset = - 1;
              }

              byte[] buffer = new byte[80];
              bool firstCard = true;
              int count = 0;
              bool notEnd = true;

              while(notEnd)
              {
            int need = 80;

            //				try
            //				{
            for(int len = 1; need > 0 && len > 0;)
            {
              len = dis.Read(buffer, 80 - need, need);
              count += 1;
              if(firstCard && len == 0 && need == 80)
              {
            throw new EndOfStreamException();
              }
              need -= len;
            }
            //				}
            //				catch(EndOfStreamException e)
            //				{
            //					// Rethrow the EOF if we are at the beginning of the header,
            //					// otherwise we have a FITS error.
            //					if(firstCard && need == 80)
            //					{
            //						throw e;
            //					}
            //					throw new TruncatedFileException(e.Message);
            //				}

            String cbuf = new String(SupportClass.ToCharArray(buffer));
            HeaderCard fcard = new HeaderCard(cbuf);

            if(firstCard)
            {
              String key = fcard.Key;
              //Console.Out.WriteLine("key = '" + key + "'");
              if(key == null || (!key.Equals("SIMPLE") && !key.Equals("XTENSION")))
              {
            throw new IOException("Not FITS format at " + fileOffset + ":" + cbuf);
              }

              firstCard = false;
            }

            String key2 = fcard.Key;
            if(key2 != null && cards.ContainsKey(key2))
            {
              Console.Error.WriteLine("Warning: multiple occurrences of key:" + key2);
            }
            // save card
            AddLine(fcard);
            if (cbuf.Substring(0, (8) - (0)).Equals("END     "))
            {
              notEnd = false;
            }
              }

              if (fileOffset >= 0)
              {
            oldSize = cards.Count;
            input = dis;
              }

              // Read to the end of the current FITS block.
              try
              {
            if(dis.CanSeek)
            {
              dis.Seek(FitsUtil.Padding(count * 80));
            }
            else
            {
              int pad = FitsUtil.Padding(count * 80);
              for (int len = dis.Read(buffer, 0, Math.Min(pad, buffer.Length));
              pad > 0 && len != -1; )
              {
            pad -= len;
            len = dis.Read(buffer, 0, Math.Min(pad, buffer.Length));
              }
            }
              }
              catch(IOException e)
              {
            throw new TruncatedFileException(e.Message);
              }
        }
        /// <summary>
        /// Method to read data
        /// </summary>
        /// <param name="i"></param>
        public override void Read(ArrayDataIO i)
        {
            // Don't need to read null data (noted by Jens Knudstrup)
            if (byteSize == 0)
            {
                return ;
            }
            SetFileOffset(i);

            //if(i is RandomAccess)
            if(i.CanSeek)
            {
                //tiler = new ImageDataTiler(this, (RandomAccess) i, ((RandomAccess) i).FilePointer, dataDescription);
                tiler = new ImageDataTiler(this, (RandomAccess) i, ((Stream)i).Position, dataDescription);
                try
                {
                    double pos = i.Position;
                    //pos = i.Seek((int)byteSize) - pos;
                    i.Seek((int)byteSize);
                }
                catch(IOException e)
                {
                    throw new FitsException("Unable to skip over data:" + e);
                }
            }
            else
            {
                dataArray = ArrayFuncs.NewInstance(dataDescription.type, dataDescription.dims);
                try
                {
                    i.ReadArray(dataArray);
                }
                catch(IOException e)
                {
                    throw new FitsException("Unable to read image data:" + e);
                }

                tiler = new ImageDataTiler(this, null, 0, dataDescription);
            }

            int pad = FitsUtil.Padding(TrueSize);
            try
            {
                long pos = i.Seek(pad);
                if(pos != pad)
                {
                    throw new FitsException("Error skipping padding");
                }
            }
            catch(IOException e)
            {
                throw new FitsException("Error reading image padding:" + e);
            }
        }
        /// <summary>Read the RandomGroupsData.</summary>
        public override void Read(ArrayDataIO str)
        {
            SetFileOffset(str);

            try
            {
                str.ReadArray(dataArray);
            }
            catch(IOException e)
            {
                throw new FitsException("IO error reading Random Groups data " + e);
            }
            int pad = FitsUtil.Padding(TrueSize);
            try
            {
                //System.IO.BinaryReader temp_BinaryReader;
                System.Int64 temp_Int64;
                //temp_BinaryReader = str;
                temp_Int64 = str.Position;  //temp_BinaryReader.BaseStream.Position;
                temp_Int64 = str.Seek(pad) - temp_Int64;  //temp_BinaryReader.BaseStream.Seek(pad, System.IO.SeekOrigin.Current) - temp_Int64;
                int generatedAux = (int)temp_Int64;
            }
            catch(IOException)
            {
                throw new FitsException("IO error reading padding.");
            }
        }
Exemple #6
0
        /// <summary>Write the table, heap and padding</summary>
        public override void Write(ArrayDataIO os)
        {
            object data = DataArray;
            int len;
            try
            {
                // First write the table.
                len = table.Write(os);
                if (heapOffset > 0)
                {
                    os.Write(new byte[heapOffset]);
                }
                if (heap.Size > 0)
                {
                    heap.Write(os);
                }

                os.Write(new byte[FitsUtil.Padding(TrueSize)]);
            }
            catch(IOException e)
            {
                throw new FitsException("Unable to write table:" + e);
            }
        }
Exemple #7
0
        /// <summary>Read table, heap and padding</summary>
        protected internal void ReadTrueData(ArrayDataIO i)
        {
            int len;

            try
            {
                len = table.Read(i);
            //				IO.BinaryReader temp_BinaryReader;
                Int64 temp_Int64;
                //temp_BinaryReader = i;
                temp_Int64 = i.Position; //temp_BinaryReader.BaseStream.Position;
                temp_Int64 = i.Seek(heapOffset, SeekOrigin.Current) - temp_Int64; //temp_BinaryReader.BaseStream.Seek(heapOffset, IO.SeekOrigin.Current) - temp_Int64;
                int generatedAux = (int)temp_Int64;
                heap.Read(i);
                //IO.BinaryReader temp_BinaryReader2;
                Int64 temp_Int65;
                //temp_BinaryReader2 = i;
                temp_Int65 = i.Position; //temp_BinaryReader2.BaseStream.Position;
                temp_Int65 = i.Seek(FitsUtil.Padding(TrueSize), SeekOrigin.Current) - temp_Int65;  //temp_BinaryReader2.BaseStream.Seek(FitsUtil.padding(TrueSize), IO.SeekOrigin.Current) - temp_Int65;
                int generatedAux2 = (int)temp_Int65;
            }
            catch(IOException e)
            {
                throw new FitsException("Error reading binary table data:" + e);
            }
        }
Exemple #8
0
 /// <summary>Read a data array into the current object and if needed position
 /// to the beginning of the next FITS block.</summary>
 /// <param name="i">The input data stream</param>
 public abstract void Read(ArrayDataIO i);
        /// <summary>
        ///   Writes this binary table with data first going
        ///   to a temp file (and heap file if necessary),
        ///   then with header going to destination stream,
        ///   then merging heap with table data if necessary
        ///   and copying these to destination stream.
        /// </summary>
        /// <param name="s">The destination stream.</param>
        /// steps:
        /// 1) write the table to a tempfile
        ///    byterenderers write data to the heap if necessary
        ///    byterenderers return heap positions and lengths if necessary
        ///    these are returned as a byte sequence like any other data
        ///    and are written to the table like any other data
        /// 2) fix the header
        ///    write the header to the main stream
        /// 3) write the table tempfile to the main stream, merging heap if necessary
        /// what a pain
        protected void WritePadOutput(ArrayDataIO s)
        {
            String tempFilename = CreateTempFilename() + "temp.tmp";
              String heapFilename = CreateTempFilename() + "heap.tmp";
              Stream tempS = new ActualBufferedStream(new FileStream(tempFilename, FileMode.Create));
              Stream heapS = null;
              //Stream tempS = new BufferedStream(new FileStream(tempFilename, FileMode.Create), 4096);
              int[] maxColWidths = null;
              int[] stringIndices = GetStringIndices(_rs.ModelRow);
              int[] byteWidths = ComputeByteWidths(CopyModelRowStripUnknowns(ReplaceTroolean(_rs.ModelRow), new byte[1]));
              int nRows = 0;
              int maxColWidth = 0;

              if(_hasStrings)
              {
            maxColWidths = new int[_byteRenderers.Length];
            heapS = new HeapStream(new FileStream(heapFilename, FileMode.Create));
            //heapS = new BufferedStream(new FileStream(heapFilename, FileMode.Create));
            for(int col = 0; col < _byteRenderers.Length; ++col)
            {
              _byteRenderers[col].Heap = heapS;
              maxColWidths[col] = -1;
            }
              }

              #region 1) write the table
              for(Array[] els = _rs.GetNextRow(ref _row); els != null;)
              {
            ++nRows;
            for(int col = 0; col < _byteRenderers.Length; ++col)
            {
              _byteRenderers[col].Write(els[col], tempS);
              if(els[col] is String[] && maxColWidths[col] < ((String[])els[col])[0].Length)
              {
                maxColWidths[col] = ((String[])els[col])[0].Length;

                if(maxColWidth < maxColWidths[col])
                {
                  maxColWidth = maxColWidths[col];
                }
              }
            }

            els = _rs.GetNextRow(ref _row);
              }
              tempS.Flush();
              heapS.Flush();
              #endregion

              #region 2) fix the header and write it to the main stream
              if(_hasStrings)
              {
            // fix NAXIS1, NAXIS2
            Array[] modelRow2 = CopyModelRowReplaceStrings(ReplaceTroolean(_rs.ModelRow), null);
            //modelRow2 = CopyModelRowStripUnknowns(modelRow2, new byte[1]);
            for(int i = 0; i < modelRow2.Length; ++i)
            {
              if(modelRow2[i] == null)
              {
                modelRow2[i] = new String[]{new String(' ', maxColWidths[i])};
                myHeader.RemoveCard("TFORM" + (i + 1));
                myHeader.InsertValue("TFORM" + (i + 1), maxColWidths[i] + "A", null, "TDIM" + (i + 1));
              }
            }
            modelRow2 = CopyModelRowStripUnknowns(modelRow2, new byte[1]);
            myHeader.RemoveCard("NAXIS1");
            myHeader.InsertValue("NAXIS1", ArrayFuncs.ComputeSize(modelRow2), "row width in bytes", "NAXIS2");
            myHeader.RemoveCard("NAXIS2");
            myHeader.InsertValue("NAXIS2", nRows, "number of rows", "PCOUNT");
            myHeader.RemoveCard("THEAP");
              }
              myHeader.Write(s);
              #endregion

              #region 3) write the table tempfile to the main stream
              tempS.Seek(0, SeekOrigin.Begin);
              heapS.Seek(0, SeekOrigin.Begin);
              // man, if you can't even fit a row into memory, I give up
              byte[] row = new byte[_rowSizeInBytes]; // this is the old size
              byte[] padBuf = SupportClass.ToByteArray(new String(_padChar, maxColWidth));
              int len = 0;
              int off = 0;
              for(int nRead = tempS.Read(row, 0, row.Length), rowOffset = 0; nRead > 0; rowOffset = 0)
              {
            for(int i = 0; i < byteWidths.Length; ++i)
            {
              if(stringIndices[i] != -1)
              {
                Array.Reverse(row, stringIndices[i], 4); // fix the length bytes
                Array.Reverse(row, stringIndices[i] + 4, 4); // fix the pos bytes
                len = BitConverter.ToInt32(row, stringIndices[i]);
                off = BitConverter.ToInt32(row, stringIndices[i] + 4);
                if(_padLeft)
                {
                  s.Write(padBuf, 0, maxColWidths[i] - len);
                  heapS.Seek(off, SeekOrigin.Begin);
                  int bufread = heapS.Read(_buf, 0, len);
                  s.Write(_buf, 0, len);
                }
                else
                {
                  heapS.Seek(off, SeekOrigin.Begin);
                  heapS.Read(_buf, 0, len);
                  s.Write(_buf, 0, len);
                  s.Write(padBuf, 0, maxColWidths[i] - len);
                }
                rowOffset += 8; // advance 2 ints into the row
              }
              else
              {
                // s better be buffered, or this is going to be slow.  But since s is ArrayDataIO,
                // and the only current concrete ArrayDataIO implementations are buffered,
                // I think we're good.
                // **** MAKE SURE BUFFEREDSTREAM USED BY BUFFEREDDATASTREAM IS GOOD *****
                s.Write(row, rowOffset, byteWidths[i]);
                rowOffset += byteWidths[i];
              }
            }
            nRead = tempS.Read(row, 0, row.Length);
              }
              tempS.Close();
              heapS.Close();
              File.Delete(tempFilename);
              File.Delete(heapFilename);

              // pad the table
              int tableWidth = 0;
              for(int i = 0; i < byteWidths.Length; ++i)
              {
            if(stringIndices[i] != -1)
            {
              tableWidth += maxColWidths[i];
            }
            else
            {
              tableWidth += byteWidths[i];
            }
              }
              int pad = FitsUtil.Padding((long)nRows * (long)tableWidth);
              s.Write(new byte[pad], 0, pad);
              #endregion
        }
 /// <summary>
 ///   Writes this binary table in one pass.
 ///   Requires foreknowledge of nRows and
 ///   either no strings or truncated string output.
 /// </summary>
 /// <param name="s">The destination stream.</param>
 protected void WriteOnePass(ArrayDataIO s)
 {
     WriteTable(s);
 }
        /// <summary>
        ///   Writes this binary table with data first going
        ///   to a temp file (and heap file if necessary),
        ///   then with header going to destination stream,
        ///   then copying data from temp file to destination stream,
        ///   then if necessary copying heap file to destination stream.
        /// </summary>
        /// <param name="s">The destination stream.</param>
        /// steps:
        /// 1) write the table to a tempfile
        ///    byterenderers write data to the heap if necessary
        ///    byterenderers return heap positions and lengths if necessary
        ///    these are returned as a byte sequence like any other data
        ///    and are written to the table like any other data
        /// 2) fix the header
        ///    write the header to the main stream
        /// 3) write the table tempfile to the main stream
        /// 4) write the heap tempfile to the main stream
        /// what a pain
        protected void WriteHeapOutputWithTempTableAndHeapFiles(ArrayDataIO s)
        {
            String tempFilename = CreateTempFilename() + "temp.tmp";
              String heapFilename = CreateTempFilename() + "heap.tmp";
              Stream tempS = new ActualBufferedStream(new FileStream(tempFilename, FileMode.Create));
              HeapStream heapS = null;
              int[] maxColWidths = null;
              bool _doHeap = _hasStrings && _writeMode != StringWriteMode.TRUNCATE;

              if(_doHeap)
              {
            maxColWidths = new int[_byteRenderers.Length];
            heapS = new HeapStream(new FileStream(heapFilename, FileMode.Create));
            for(int col = 0; col < _byteRenderers.Length; ++col)
            {
              _byteRenderers[col].Heap = heapS;
              maxColWidths[col] = -1;
            }
              }

              #region 1) write the table
              int nRows = 0;
              for(Array[] els = _rs.GetNextRow(ref _row); els != null;)
              {
            ++nRows;
            for(int col = 0; col < _byteRenderers.Length; ++col)
            {
              _byteRenderers[col].Write(els[col], tempS);
              if(_doHeap && els[col] is String[])
              {
                maxColWidths[col] = maxColWidths[col] < ((String[])els[col])[0].Length ?
                  ((String[])els[col])[0].Length : maxColWidths[col];
              }
            }

            els = _rs.GetNextRow(ref _row);
              }
              tempS.Flush();
              #endregion

              #region 2) fix the header and write it to the main stream
              myHeader.RemoveCard("NAXIS2");
              myHeader.SetNaxis(2, nRows);
              // shoehorn correct heap information into header
              // PCOUNT, THEAP, and TFORMn
              // fix NAXIS1
              if(_doHeap)
              {
            heapS.Flush();
            int theap = (nRows * _rowSizeInBytes);
            int pad = FitsUtil.Padding((long)theap + heapS.Position);
            int pcount = (int)heapS.Position + pad;
            // here we correct for swapping out actual strings with heap indices/lengths
            myHeader.RemoveCard("NAXIS1");
            myHeader.InsertCard(new HeaderCard("NAXIS1", _rowSizeInBytes, null), "NAXIS2");
            myHeader.RemoveCard("PCOUNT");
            myHeader.InsertCard(new HeaderCard("PCOUNT", pcount, "Length of heap area in bytes"),
              "GCOUNT");
            myHeader.RemoveCard("THEAP");
            myHeader.AddValue("THEAP", theap, "Position of heap wrt start of binary table");
              }

              // fix the TFORMn entries for string columns
              IEnumerator ie = null;
              bool found = false;
              //for(int i = 0; i < maxColWidths.Length; ++i, found = false)
              for(int i = 0; i < _rs.ModelRow.Length; ++i, found = false)
              {
            if(_rs.ModelRow[i] is String[])
            {
              ie = myHeader.GetEnumerator();
              ie.MoveNext();
              for(int j = 0; !found && ie.Current != null; ++j, ie.MoveNext())
              {
                if(("TFORM" + (i + 1)).Equals(((DictionaryEntry)ie.Current).Key))
                {
                  if(_doHeap)
                  {
                    myHeader.RemoveCard(j);
                    myHeader.
                      InsertCard(new HeaderCard("TFORM" + (i + 1),
                      "1PA(" + maxColWidths[i] + ")",
                      null), j);
                    found = true;
                  }
                  else
                  {
                    myHeader.RemoveCard(j);
                    myHeader.
                      InsertCard(new HeaderCard("TFORM" + (i + 1),
                      _stringTruncationLength + "A",
                      null), j);
                    found = true;
                  }
                }
              }
            }
              }
              myHeader.Write(s);
              #endregion

              #region 3) write the table tempfile to the main stream
              tempS.Seek(0, SeekOrigin.Begin);
              for(int nRead = tempS.Read(_buf, 0, _buf.Length); nRead > 0;)
              {
            s.Write(_buf, 0, nRead);
            nRead = tempS.Read(_buf, 0, _buf.Length);
              }
              tempS.Close();
              File.Delete(tempFilename);

              // if there's a heap, pad the heap instead of the table
              if(!_doHeap)
              {
            int pad = FitsUtil.Padding((long)nRows * (long)_rowSizeInBytes);
            s.Write(new byte[pad], 0, pad);
              }
              #endregion

              #region 4) write the heap tempfile to the main stream
              if(_doHeap)
              {
            // calculate the pad
            int pad = FitsUtil.Padding((long)nRows * (long)_rowSizeInBytes + heapS.Position);

            // write to the main stream
            heapS.Seek(0, SeekOrigin.Begin);
            for(int nRead = heapS.Read(_buf, 0, _buf.Length); nRead > 0;)
            {
              s.Write(_buf, 0, nRead);
              nRead = heapS.Read(_buf, 0, _buf.Length);
            }
            heapS.Close();
            File.Delete(heapFilename);

            // pad the file
            s.Write(new byte[pad], 0, pad);
              }
              #endregion
        }
        /// <summary>
        ///   Writes this binary table with heap temp file if necessary,
        ///   then fixing nRows and PCOUNT in header,
        ///   then if necessary copying heap file to destination stream.
        /// </summary>
        /// <param name="s">The destination stream.</param>
        /// steps:
        /// 1) write the header to the main stream
        ///    write the table to the main stream
        ///    byterenderers write data to the heap if necessary
        ///    byterenderers return heap positions and lengths if necessary
        ///    these are returned as a byte sequence like any other data
        ///    and are written to the table like any other data
        /// 2) fix the header
        /// 3) write the heap tempfile to the main stream
        /// what a pain
        protected void WriteHeapOutputWithTempHeapFile(ArrayDataIO s)
        {
            String heapFilename = CreateTempFilename() + "heap.tmp";
              HeapStream heapS = null;
              int[] maxColWidths = null;

              if(_hasStrings)
              {
            maxColWidths = new int[_byteRenderers.Length];
            heapS = new HeapStream(new FileStream(heapFilename, FileMode.Create));
            for(int col = 0; col < _byteRenderers.Length; ++col)
            {
              _byteRenderers[col].Heap = heapS;
              maxColWidths[col] = -1;
            }
              }

              #region 1) write the header and the table
              // prep header to make sure it will line up properly with the table later on.
              // since we made the header, we know that anything we add later
              // (except THEAP, accounted for here) will already have been there,
              // so we're not inflating the header
              myHeader.RemoveCard("THEAP");
              if(_hasStrings && _writeMode == StringWriteMode.HEAP)
              {
            myHeader.AddValue("THEAP", 0, null);
              }
              long headerMark = s.Position;
              myHeader.Write(s);

              int nRows = 0;
              for(Array[] els = _rs.GetNextRow(ref _row); els != null;)
              {
            ++nRows;
            for(int col = 0; col < _byteRenderers.Length; ++col)
            {
              _byteRenderers[col].Write(els[col], s);
              if(els[col] is String[])
              {
                maxColWidths[col] = maxColWidths[col] < ((String[])els[col])[0].Length ?
                  ((String[])els[col])[0].Length : maxColWidths[col];
              }
            }

            els = _rs.GetNextRow(ref _row);
              }

              // pad the table.  if there's a heap, pad the heap instead
              if(!_hasStrings)
              {
            int pad = FitsUtil.Padding((long)nRows * (long)_rowSizeInBytes);
            s.Write(new byte[pad], 0, pad);
              }
              s.Flush();
              #endregion

              #region 2) fix the header and write it to the main stream
              myHeader.RemoveCard("NAXIS2");
              myHeader.SetNaxis(2, nRows);
              // shoehorn correct heap information into header
              // PCOUNT, THEAP, and TFORMn
              // fix NAXIS1
              if(_hasStrings)
              {
            long theap = (long)nRows * (long)_rowSizeInBytes;
            int pad = FitsUtil.Padding(theap + heapS.Position);
            int pcount = (int)heapS.Position + pad;
            // here we correct for swapping out actual strings with heap indices/lengths
            myHeader.RemoveCard("NAXIS1");
            myHeader.InsertCard(new HeaderCard("NAXIS1", _rowSizeInBytes, null), "NAXIS2");
            myHeader.RemoveCard("PCOUNT");
            myHeader.InsertCard(new HeaderCard("PCOUNT", pcount, "Length of heap area in bytes"),
              "GCOUNT");
            myHeader.RemoveCard("THEAP");
            // can't fit a long in here!
            if(pcount > 0 && _writeMode == StringWriteMode.HEAP)
            {
              myHeader.AddValue("THEAP", (int)theap, "Position of heap wrt start of binary table");
            }

            // fix the TFORMn entries for string columns
            IEnumerator ie = null;
            bool found = false;
            for(int i = 0; i < maxColWidths.Length; ++i, found = false)
            {
              if(maxColWidths[i] > -1)
              {
                ie = myHeader.GetEnumerator();
                ie.MoveNext();
                for(int j = 0; !found && ie.Current != null; ++j, ie.MoveNext())
                {
                  if(("TFORM" + (i + 1)).Equals(((DictionaryEntry)ie.Current).Key))
                  {
                    myHeader.RemoveCard(j);
                    myHeader.
                      InsertCard(new HeaderCard("TFORM" + (i + 1),
                      "1PA(" + maxColWidths[i] + ")",
                      null), j);
                    found = true;
                  }
                }
              }
            }
              }
              // rewrite the header
              long heapMark = s.Position;
              s.Seek(headerMark, SeekOrigin.Begin);
              myHeader.Write(s);
              #endregion

              #region 3) write the heap tempfile to the main stream
              if(_hasStrings)
              {
            // calculate the pad
            int pad = FitsUtil.Padding((long)nRows * (long)_rowSizeInBytes + heapS.Position);

            s.Seek(heapMark, SeekOrigin.Begin);

            // write heap to the main stream
            heapS.Seek(0, SeekOrigin.Begin);
            for(int nRead = heapS.Read(_buf, 0, _buf.Length); nRead > 0;)
            {
              s.Write(_buf, 0, nRead);
              nRead = heapS.Read(_buf, 0, _buf.Length);
            }
            heapS.Close();
            File.Delete(heapFilename);

            // pad the file
            s.Write(new byte[pad], 0, pad);
              }
              #endregion
        }
 public override void Write(ArrayDataIO s)
 {
     System.Threading.Monitor.Enter(this);
       //((Writer)_writerMap[new Config(_rs.NRows != RowSource.NA, _hasStrings, s.CanSeek, _writeMode)]).Write(s);
       Config c = new Config(_rs.NRows != RowSource.NA, _hasStrings, s.CanSeek, _writeMode);
       ((Writer)_writerMap[c]).Write(s);
       s.Flush();
       System.Threading.Monitor.Exit(this);
 }
 public override void Write(ArrayDataIO s)
 {
     _table.WritePadOutput(s);
 }
 public override void Write(ArrayDataIO s)
 {
     _table.WriteOnePass(s);
 }
Exemple #16
0
 /// <summary> Skip the ASCII table and throw an exception.</summary>
 /// <param name="stream">the stream from which the data is read.</param>
 public override void ReadData(ArrayDataIO stream)
 {
     myData.Read(stream);
 }
        protected int WriteTable(ArrayDataIO s)
        {
            myHeader.Write(s);

              // write the table
              int nRows = 0;
              for(Array[] els = _rs.GetNextRow(ref _row); els != null;)
              {
            ++nRows;
            for(int col = 0; col < _byteRenderers.Length; ++col)
            {
              _byteRenderers[col].Write(els[col], s);
            }

            els = _rs.GetNextRow(ref _row);
              }

              // pad
              s.Write(new byte[FitsUtil.Padding((long)nRows * (long)_rowSizeInBytes)]);

              return nRows;
        }
Exemple #18
0
 /// <summary>Write the data -- including any buffering needed</summary>
 /// <param name="o"> The output stream on which to write the data.</param>
 public abstract void Write(ArrayDataIO o);
        /// <summary>
        ///   Writes this binary table in one pass,
        ///   then seeks back to fix NAXIS2.  Requires
        ///   s to be seekable and
        ///   either no strings or truncated string output.
        /// </summary>
        /// <param name="s">The destination stream.</param>
        protected void WriteThenFix(ArrayDataIO s)
        {
            long headerMark = s.Position;
              int nRows = WriteTable(s);
              long endMark = s.Position;

              myHeader.RemoveCard("NAXIS2");
              myHeader.SetNaxis(2, nRows);
              myHeader.InsertComment("No comment.", "THEAP");
              myHeader.RemoveCard("THEAP");
              s.Seek(headerMark, SeekOrigin.Begin);
              myHeader.Write(s);
              s.Seek(endMark, SeekOrigin.Begin);
        }
Exemple #20
0
        /// <summary>Read the data -- or defer reading on random access</summary>
        public override void Read(ArrayDataIO i)
        {
            SetFileOffset(i);
            currInput = i;

            if (i is RandomAccess)
            {
                try
                {
                    //BinaryReader temp_BinaryReader;
                    Int64 temp_Int64;
                    //temp_BinaryReader = i;
                    temp_Int64 = i.Position;//temp_BinaryReader.BaseStream.Position;
                    temp_Int64 = i.Seek(TrueSize, SeekOrigin.Current) - temp_Int64; //temp_BinaryReader.BaseStream.Seek(TrueSize, IO.SeekOrigin.Current) - temp_Int64;
                    int generatedAux = (int)temp_Int64;
                    //IO.BinaryReader temp_BinaryReader2;
                    Int64 temp_Int65;
                    //temp_BinaryReader2 = i;
                    temp_Int65 = i.Position;//temp_BinaryReader2.BaseStream.Position;
                    temp_Int65 = i.Seek(FitsUtil.Padding(TrueSize), SeekOrigin.Current) - temp_Int65;//temp_BinaryReader2.BaseStream.Seek(FitsUtil.padding(TrueSize), IO.SeekOrigin.Current) - temp_Int65;
                    int generatedAux2 = (int)temp_Int65;
                }
                catch(IOException e)
                {
                    throw new FitsException("Unable to skip binary table HDU:" + e);
                }
            }
            else
            {
                if (table == null)
                {
                    table = CreateTable();
                }

                ReadTrueData(i);
            }
        }
 public override void Write(ArrayDataIO s)
 {
     _table.WriteThenFix(s);
 }
 /// <summary>Write the RandomGroupsData.</summary>
 public override void Write(ArrayDataIO str)
 {
     try
     {
         str.WriteArray(dataArray);
         byte[] padding = new byte[FitsUtil.Padding(TrueSize)];
         str.Write(padding);
         str.Flush();
     }
     catch(IOException e)
     {
         throw new FitsException("IO error writing random groups data " + e);
     }
 }
        /// <summary>Need to tell header about the Heap before writing.</summary>
        public override void Write(ArrayDataIO ado)
        {
            int oldSize = myHeader.GetIntValue("PCOUNT");
            if (oldSize != table.HeapSize)
            {
                myHeader.AddValue("PCOUNT", table.HeapSize, "Includes Heap");
            }

            if (myHeader.GetIntValue("PCOUNT") == 0)
            {
                myHeader.DeleteKey("THEAP");
            }
            else
            {
                myHeader.GetIntValue("TFIELDS");
                int offset = myHeader.GetIntValue("NAXIS1") * myHeader.GetIntValue("NAXIS2") + table.HeapOffset;
                myHeader.AddValue("THEAP", offset, "");
            }

            base.Write(ado);
        }
Exemple #24
0
        /// <summary>Write a table.</summary>
        /// <param name="os">the output stream to write to.</param>
        public virtual int Write(ArrayDataIO os)
        {
            if (rowSize == 0)
            {
                return(0);
            }

            for (int row = 0; row < nrow; row += 1)
            {
                int ibyte    = 0;
                int ishort   = 0;
                int iint     = 0;
                int ilong    = 0;
                int ichar    = 0;
                int ifloat   = 0;
                int idouble  = 0;
                int iboolean = 0;

                // Loop over the columns within the row.
                for (int col = 0; col < arrays.Length; col += 1)
                {
                    int arrOffset = sizes[col] * row;
                    int size      = sizes[col];

                    Type t = bases[col];
                    if (typeof(int).Equals(t))
                    {
                        int[] ia = intPointers[iint];
                        iint += 1;
                        os.Write(ia, arrOffset, size);
                    }
                    else if (typeof(short).Equals(t))
                    {
                        short[] s = shortPointers[ishort];
                        ishort += 1;
                        os.Write(s, arrOffset, size);
                    }
                    else if (typeof(byte).Equals(t))
                    {
                        byte[] b = bytePointers[ibyte];
                        ibyte += 1;
                        os.Write(b, arrOffset, size);
                    }
                    else if (typeof(float).Equals(t))
                    {
                        float[] f = floatPointers[ifloat];
                        ifloat += 1;
                        os.Write(f, arrOffset, size);
                    }
                    else if (typeof(double).Equals(t))
                    {
                        double[] d = doublePointers[idouble];
                        idouble += 1;
                        os.Write(d, arrOffset, size);
                    }
                    else if (typeof(char).Equals(t))
                    {
                        char[] c = charPointers[ichar];
                        ichar += 1;
                        os.Write(c, arrOffset, size);
                    }
                    else if (typeof(long).Equals(t))
                    {
                        long[] l = longPointers[ilong];
                        ilong += 1;
                        os.Write(l, arrOffset, size);
                    }
                    else if (typeof(bool).Equals(t))
                    {
                        bool[] bool_Renamed = booleanPointers[iboolean];
                        iboolean += 1;
                        os.Write(bool_Renamed, arrOffset, size);
                    }
                }
            }

            // All done if we get here...
            return(rowSize * nrow);
        }
Exemple #25
0
 /// <summary>
 /// 
 /// </summary>
 public virtual void Close()
 {
     dataStr.Close();
     dataStr = null;
 }
Exemple #26
0
        /// <summary>
        /// method to write data
        /// </summary>
        /// <param name="o"></param>
        public override void Write(ArrayDataIO o)
        {
            // Don't need to write null data (noted by Jens Knudstrup)
            if (byteSize == 0)
            {
                return ;
            }

            // changes suggested in .97 version:
            if (dataArray == null)
            {
                if (tiler != null)
                {
                    // Need to read in the whole image first.
                    try
                    {
                        dataArray = tiler.CompleteImage;
                    }
                    catch(IOException)
                    {
                        throw new FitsException("Error attempting to fill image");
                    }
                }
                else if (dataArray == null && dataDescription != null)
                {
                    // Need to create an array to match a specified header.
                    dataArray = ArrayFuncs.NewInstance(dataDescription.type, dataDescription.dims);
                }
                else
                {
                    // This image isn't ready to be written!
                    throw new FitsException("Null image data");
                }
            }

            try
            {
                o.WriteArray(dataArray);
            }
            catch(IOException e)
            {
                throw new FitsException("IO Error on image write: " + e);
            }

            byte[] padding = new byte[FitsUtil.Padding(TrueSize)];
            try
            {
                o.Write(padding);
                o.Flush();
            }
            catch(IOException e)
            {
                throw new FitsException("Error writing padding: " + e);
            }
        }
Exemple #27
0
        /// <summary>Read a FITS file from an InputStream object.</summary>
        /// <param name="is">The InputStream stream whence the FITS information is found.</param>
        public virtual void Read(Stream is_Renamed)
        {
            bool newIS = false;

            if (is_Renamed is ArrayDataIO)
            {
                dataStr = (ArrayDataIO) is_Renamed;
            }
            else
            {
                dataStr = new BufferedDataStream(is_Renamed);
            }

            Read();

            if (newIS)
            {
                dataStr.Close();
                dataStr = null;
            }
        }
Exemple #28
0
        /// <summary>Write the current header (including any needed padding) to the
        /// output stream.</summary>
        /// <param name="dos">The output stream to which the data is to be written.</param>
        /// <exception cref="FitsException">FitsException if the header could not be written.</exception>
        public void Write(ArrayDataIO dos)
        {
            fileOffset = FitsUtil.FindOffset(dos);

            // change suggested in .99.1 version: used HeaderOrder to sort keyword before write op.
            // Ensure that all cards are in the proper order.
            cards.Sort(new HeaderOrder());

            CheckBeginning();
            CheckEnd();

            if(cards.Count <= 0)
            {
                return ;
            }

            //Cursor cursor = cards.GetCursor(0);
            Cursor cursor = cards.GetCursor();

            try
            {
                while(cursor.MoveNext())
                {
                    HeaderCard card = (HeaderCard)((DictionaryEntry)cursor.Current).Value;
                    byte[] b = SupportClass.ToByteArray(card.ToString());
                    dos.Write(b);
                }

                byte[] padding = new byte[FitsUtil.Padding(NumberOfCards * 80)];
                for (int i = 0; i < padding.Length; i += 1)
                {
                    padding[i] = (byte)' ';// SupportClass.Identity(' ');
                }
                dos.Write(padding);
            }
            catch(IOException e)
            {
                throw new FitsException("IO Error writing header: " + e);
            }
            try
            {
                dos.Flush();
            }
            catch(IOException)
            {
            }
        }
Exemple #29
0
        /// <summary>Initialize using buffered random access</summary>
        protected internal virtual void RandomInit(FileInfo f,FileAccess access)
        {
            // FileAccess access =
             // SupportClass.FileCanWrite(f) ? FileAccess.ReadWrite : FileAccess.Read;

            if(!f.Exists)
            {
                throw new FitsException("File '" + f + "' does not exist.");
            }
            try
            {
                // change suggested in .99.4 version: FileInfo passed instead of Filename (string)
                if(access.Equals(FileAccess.Read))
                    dataStr = new BufferedFile(f, access,FileShare.Read);
                else
                    dataStr = new BufferedFile(f, access, FileShare.ReadWrite);
                ((BufferedFile)dataStr).Seek(0);
            }
            catch(IOException)
            {
                throw new FitsException("Unable to open file " + f.FullName);
            }
        }
Exemple #30
0
 /// <summary>Create a header and populate it from the input stream</summary>
 /// <param name="is_Renamed"> The input stream where header information is expected.</param>
 public Header(ArrayDataIO is_Renamed)
 {
     InitBlock();
     Read(is_Renamed);
 }
Exemple #31
0
        /// <summary>Do the stream initialization.</summary>
        /// <param name="str">The input stream.</param>
        /// <param name="compressed">Is this data compressed?  If so,
        /// then the GZIPInputStream class will be
        /// used to inflate it.</param>
        protected internal virtual void StreamInit(Stream str, bool compressed, bool seekable)
        {
            if (str == null)
            {
                throw new FitsException("Null input stream");
            }

            if (compressed)
            {
                //gzip functionality added
                try
                {
                    str = new GZipStream(str, CompressionMode.Decompress);

                }
                catch (System.IO.IOException e)
                {
                    throw new FitsException("Cannot inflate input stream" + e);
                }
            }

            if(str is ArrayDataIO)
            {
                dataStr = (ArrayDataIO)str;
            }
            else
            {
                // Use efficient blocking for input.
                dataStr = new BufferedDataStream(str);
            }
        }