Example #1
0
        /// <summary>
        /// Is called when a user requests to import a ."sgy file.
        /// It is actually up to this method to read the file itself.
        /// </summary>
        /// <param name="filename">The complete path to the new file.</param>
        /// <param name="index">The index of the file type as it had been specified by the AddFileTypes method.</param>
        /// <param name="doc">The document to be written.</param>
        /// <param name="options">Options that specify how to write file.</param>
        /// <returns>A value that defines success or a specific failure.</returns>
        protected override bool ReadFile(string filename, int index, RhinoDoc doc, Rhino.FileIO.FileReadOptions options)
        {
            bool read_success = false;

            var       reader = new SegyReader();
            ISegyFile file   = reader.Read(filename);

            RhinoApp.WriteLine("SEGY: Header Text: {0}", file.Header.Text);
            RhinoApp.WriteLine("SEGY: Nº of Traces: {0}", file.Traces.Count);
            for (int i = 0; i < file.Traces.Count; i++)
            {
                var trace = file.Traces[0];
                RhinoApp.WriteLine("SEGY: Trace #" + trace.Header.TraceNumber + " Count #: " + i + " Sample Count: {0}", trace.Header.SampleCount);
                RhinoApp.WriteLine("SEGY: Trace #" + trace.Header.TraceNumber + " Count #: " + i + " Crossline Nº: {0}", trace.Header.CrosslineNumber);
                RhinoApp.WriteLine("SEGY: Trace #" + trace.Header.TraceNumber + " Count #: " + i + " Inline Nº: {0}", trace.Header.InlineNumber);

                for (int j = 0; j < trace.Values.Count; j++)
                {
                    RhinoApp.WriteLine("SEGY: Trace #" + trace.Header.TraceNumber + " Count #: " + i + " Value Nº " + j + ": {0}", trace.Values[j]);
                }
            }

            read_success = true;

            return(read_success);
        }
Example #2
0
        private static void VerifyExampleValuesAndTraceCount(ISegyFile result)
        {
            VerifyExampleValues(result);
            var fileLength = new FileInfo(_example).Length;

            Assert.AreEqual((fileLength - 3200 - 400) / (240 + 1001 * 4), result.Traces.Count);
        }
Example #3
0
        private void button1_Click(object sender, EventArgs e)           //клик на кнопку открыть файл
        {
            if (!is_Drag_Drop)                                           //если запуск произошел не из-за драг-дропа
            {
                if (openFileDialog1.ShowDialog() == DialogResult.Cancel) //то показываем диалог на открытие файла
                {
                    return;                                              // если отмена то выходим
                }
                filename = openFileDialog1.FileName;                     //имя файла
            }
            else
            {
                filename = filename_Drag_Drop;//имя файла
            }

            try
            {
                var reader = new SegyReader();//чтение
                line = reader.Read(filename);
            }
            catch (Exception ex)//если не получилось
            {
                is_File_Ok = false;
                MessageBox.Show(null, "Не удалось открыть файл: \n" + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            is_File_Ok             = true;
            label_name.Text        = "Файл: " + Path.GetFileName(filename);
            label_traces_dots.Text = "Трасс / точек: " + line.Traces.Count.ToString() + " / " + line.Traces[0].Values.Count.ToString();
            Text = filename + " — файл открыт";
            FindStepSizeForTrace();
            is_Drag_Drop = false;
        }
Example #4
0
 private static IEnumerable<int> GetInlineNumbers(ISegyFile segyFile)
 {
     return segyFile.Traces.Select(t =>
     {
         if (t.Header == null)
             return 0;
         return t.Header.InlineNumber;
     }
     ).Distinct();
 }
Example #5
0
        public static double[] Do(ISegyFile line, double[] usilenie)
        {
            ITrace trace      = line.Traces[0];
            double max_outter = double.MinValue;
            double min_outter = double.MaxValue;
            double max_inner  = double.MinValue;
            double min_inner  = double.MaxValue;
            double new_value;
            int    j;

            for (int i = 0; i < line.Traces.Count; i++)
            {
                trace     = line.Traces[i];
                max_inner = double.MinValue;
                min_inner = double.MaxValue;
                j         = 1;
                foreach (var sampleValue in trace.Values)
                {
                    if (usilenie[0] == 0)
                    {
                        if (sampleValue < min_inner)
                        {
                            min_inner = sampleValue;
                        }
                        if (sampleValue > max_inner)
                        {
                            max_inner = sampleValue;
                        }
                    }
                    else
                    {
                        new_value = sampleValue * usilenie[1] * Math.Pow(j, usilenie[2]);
                        if (new_value < min_inner)
                        {
                            min_inner = new_value;
                        }
                        if (new_value > max_inner)
                        {
                            max_inner = new_value;
                        }
                    }
                    j++;
                }
                if (min_inner < min_outter)
                {
                    min_outter = min_inner;
                }
                if (max_inner > max_outter)
                {
                    max_outter = max_inner;
                }
            }
            double[] ans = { min_outter, max_outter };
            return(ans);
        }
Example #6
0
        public void ShouldReadFileHeadersAndAllTraces()
        {
            // Arrange
            var path = _example;

            // Act
            ISegyFile segy = Subject.Read(path);

            // Assert
            VerifyExampleValuesAndTraceCount(segy);
        }
Example #7
0
 private void WriteBitmapPerInline(ISegyFile segyFile, string path, IEnumerable <int> inlineNumbers, ValueRange range)
 {
     foreach (var inline in inlineNumbers)
     {
         var traces     = segyFile.Traces.Where(t => t.Header.InlineNumber == inline);
         var filename   = Path.GetFileNameWithoutExtension(path);
         var extenstion = Path.GetExtension(path);
         var newPath    = filename + " (" + inline + ")" + extenstion;
         WriteBitmapForTraces(traces, newPath, range);
     }
 }
Example #8
0
 public static void GetColor(double[] usilenie, ColorMap cmap, ISegyFile line, int curr_trace, int j)
 {
     if (usilenie[0] == 0)
     {
         color = cmap[line.Traces[curr_trace].Values[j]];
     }
     else
     {
         color = cmap[line.Traces[curr_trace].Values[j] * usilenie[1] * Math.Pow(j, usilenie[2])];
     }
 }
Example #9
0
        public void ShouldReadAllTracesIfRequestedTraceCountIsGreater()
        {
            // Arrange
            using (Stream stream = File.OpenRead(_example))
            {
                // Act
                ISegyFile segy = Subject.Read(stream, 9999);

                // Assert
                VerifyExampleValuesAndTraceCount(segy);
            }
        }
Example #10
0
 private static IEnumerable <int> GetInlineNumbers(ISegyFile segyFile)
 {
     return(segyFile.Traces.Select(t =>
     {
         if (t.Header == null)
         {
             return 0;
         }
         return t.Header.InlineNumber;
     }
                                   ).Distinct());
 }
Example #11
0
        public void ShouldReadStreamHeadersAndAllTraces()
        {
            // Arrange
            var       path = _example;
            ISegyFile segy = null;

            // Act
            using (Stream stream = File.OpenRead(path))
                segy = Subject.Read(stream);

            // Assert
            VerifyExampleValuesAndTraceCount(segy);
        }
Example #12
0
        private static void VerifyExampleValues(ISegyFile result)
        {
            StringAssert.StartsWith(result.Header.Text, "C 1");
            StringAssert.Contains(result.Header.Text, "C16 GEOPHONES");
            Assert.AreEqual(FormatCode.IbmFloatingPoint4, result.Header.SampleFormat);
            Assert.AreEqual(1001, result.Traces.First().Header.SampleCount);
            var traceValues = result.Traces.First().Values.ToList();

            Assert.AreEqual(1001, traceValues.Count);
            CollectionAssert.Contains(traceValues, 0f);
            CollectionAssert.Contains(traceValues, 0.9834598f);
            CollectionAssert.DoesNotContain(traceValues, float.PositiveInfinity);
        }
Example #13
0
        public void ShouldReadNoMoreThanRequestedNumberOfTraces()
        {
            // Arrange
            int traceCount = 5;

            using (Stream stream = File.OpenRead(_example))
            {
                // Act
                ISegyFile segy = Subject.Read(stream, traceCount);

                // Assert
                VerifyExampleValues(segy);
                Assert.AreEqual(traceCount, segy.Traces.Count);
            }
        }
Example #14
0
        public static Bitmap Do(ISegyFile line, double radius, double v, double t, double[] maxmin, string pallete, int quantity_of_colors, double[] usilenie)
        {
            double x, y, changing_radius;
            double angle               = 0;                                                   //угол = 0
            int    quantity_of_dots    = Convert.ToInt32(Math.Floor((2 * radius) / (v * t))); //количество пикселей в одном радиусе
            double step_size_for_angle = 360.0 / (line.Traces.Count - 1);                     //шаг для трассы в градусах

            ColorMap cmap;                                                                    //инициализация палитры

            if (pallete == "default pallete")
            {
                cmap = new ColorMap("my_own_colormap", maxmin[0], maxmin[1], quantity_of_colors, MainForm.rgbs, MainForm.positions);
            }
            else
            {
                cmap = new ColorMap(pallete, maxmin[0], maxmin[1], quantity_of_colors);
            }

            byte[]    color;                     //массив байтов для цвета
            int       i = line.Traces.Count - 1; //текущая трасса
            const int space_for_axes = 40;       //место для осей
            //создание битмапа для изображения
            Bitmap graph = new Bitmap(2 * Convert.ToInt32(quantity_of_dots) + space_for_axes + 20, 2 * Convert.ToInt32(quantity_of_dots) + space_for_axes + 20);

            while (angle < 360)                            //пока угол меньше 360
            {
                changing_radius = quantity_of_dots;        //текущий радиус - количество точек
                for (int j = 0; j < quantity_of_dots; j++) //цикл от 0 до количества точек
                {
                    if (usilenie[0] == 0)                  //определение цвета в зависимосто от усиления
                    {
                        color = cmap[line.Traces[i].Values[j]];
                    }
                    else
                    {
                        color = cmap[line.Traces[i].Values[j] * usilenie[1] * Math.Pow(j + 1, usilenie[2])];
                    }
                    x = quantity_of_dots + (changing_radius * Math.Cos(angle * Math.PI / 180.0));                                   //определение координаты х
                    y = quantity_of_dots + (changing_radius * Math.Sin(angle * Math.PI / 180.0));                                   //определение координаты у
                    graph.SetPixel((int)x + space_for_axes, (int)y + space_for_axes, Color.FromArgb(color[0], color[1], color[2])); //отрисовка пикселся на битмапе
                    changing_radius = changing_radius - 1;                                                                          //текущий радиус на 1 меньше
                }
                i--;                                                                                                                //следующая трасса
                angle += step_size_for_angle;                                                                                       //следующий угол
            }

            return(graph);//вернуть изображение
        }
Example #15
0
 /// <summary>
 /// Writes one or more bitmap for the given SEGY file. 
 /// If the SEGY has multiple inline numbers, it is assumed to be 3D, and one bitmap is written for each inline.
 /// </summary>
 /// <param name="path">
 /// The destination path for the image. 
 /// If multiple images are written, each inline number is added parenthetically to the file name.
 /// </param>
 public virtual void Write(ISegyFile segyFile, string path)
 {
     if (segyFile.Traces == null)
     {
         using (var bitmap = new Bitmap(1, 1))
             bitmap.Save(path);
         return;
     }
     var inlineNumbers = GetInlineNumbers(segyFile);
     if (inlineNumbers.Count() == 1)
         Write(segyFile.Traces, path);
     else
     {
         dynamic range = FindRange(segyFile.Traces);
         WriteBitmapPerInline(segyFile, path, inlineNumbers, range);
     }
 }
Example #16
0
        private Bitmap GetBitmapForMiddle(ISegyFile segy, Func <ITrace, int> numberSelector)
        {
            var imageWriter = new ImageWriter {
                SetNullValuesToTransparent = false
            };
            var numbers      = segy.Traces.Select(numberSelector).Distinct();
            var index        = numbers.Count() / 2;
            int middleNumber = numbers.ElementAt(index);

            Console.WriteLine("line num: " + middleNumber);
            Console.WriteLine("line index: " + index);
            var inlineTraces = segy.Traces.Where(t => numberSelector(t) == middleNumber).ToList();
            var bitmapPath   = Path.GetTempFileName() + ".png";
            var bitmap       = imageWriter.GetBitmap(inlineTraces);

            bitmap.Save(bitmapPath, ImageFormat.Png);
            TestContext.AddResultFile(bitmapPath);
            return(bitmap);
        }
Example #17
0
        /// <summary>
        /// Writes one or more bitmap for the given SEGY file.
        /// If the SEGY has multiple inline numbers, it is assumed to be 3D, and one bitmap is written for each inline.
        /// </summary>
        /// <param name="path">
        /// The destination path for the image.
        /// If multiple images are written, each inline number is added parenthetically to the file name.
        /// </param>
        public virtual void Write(ISegyFile segyFile, string path)
        {
            if (segyFile.Traces == null)
            {
                using (var bitmap = new Bitmap(1, 1))
                    bitmap.Save(path);
                return;
            }
            var inlineNumbers = GetInlineNumbers(segyFile);

            if (inlineNumbers.Count() == 1)
            {
                Write(segyFile.Traces, path);
            }
            else
            {
                dynamic range = FindRange(segyFile.Traces);
                WriteBitmapPerInline(segyFile, path, inlineNumbers, range);
            }
        }
Example #18
0
        public static Bitmap Do(ISegyFile line, double[] maxmin, string pallete, int quantity_of_colors, double[] usilenie, PictureBox[] pictureBoxes, double v, double t)
        {
            ITrace trace = line.Traces[0];                                                                                           //создаем переменную типа трасса

            Bitmap   graph = new Bitmap(line.Traces.Count, trace.Values.Count);                                                      //создаем битмап для изображения
            ColorMap cmap;                                                                                                           //создаем палитру

            if (pallete == "default pallete")                                                                                        //если выбрана палитра по умолчанию
            {
                cmap = new ColorMap("my_own_colormap", maxmin[0], maxmin[1], quantity_of_colors, MainForm.rgbs, MainForm.positions); //инициализируем ее по умолчанию
            }
            else
            {
                cmap = new ColorMap(pallete, maxmin[0], maxmin[1], quantity_of_colors); //если нет, то инициализируем ее в соответствии с входными параметрами
            }
            byte[] color;                                                               //массив байтов - цвет точки
            int    j = 1;                                                               //счетчик

            for (int i = 0; i < line.Traces.Count; i++)                                 //цикл по трассам от 0 до количества трасс
            {
                trace = line.Traces[i];                                                 //текущая трасса
                j     = 0;                                                              //обнуление счетчика отвечающего за номер точки
                foreach (var sampleValue in trace.Values)                               //перебор всех точек в текущей трассе
                {
                    if (usilenie[0] == 0)                                               //если усиление не требуется
                    {
                        color = cmap[sampleValue];                                      //цвет определяется без усиления
                    }
                    else
                    {
                        color = cmap[sampleValue * usilenie[1] * Math.Pow(j, usilenie[2])]; //иначе с учетом усиления
                    }
                    graph.SetPixel(i, j, Color.FromArgb(color[0], color[1], color[2]));     //рисуем пиксель на битмапе
                    j++;                                                                    //увеличиваем номер точки
                }
            }
            drawAxesForGraph.Do(pictureBoxes, line.Traces.Count, line.Traces[0].Values.Count * t, v, t, 10, false); //рисуем оси
            return(graph);                                                                                          //возвращаем изображение
        }
Example #19
0
 /// <summary>
 /// Returns a single bitmap image composed from all the trace in the SEGY file.
 /// The caller is responsible for disposing of the bitmap. This is highy recommended
 /// so that GDI resources will be cleaned up.
 /// </summary>
 /// <returns>A disposable bitmap</returns>
 public virtual Bitmap GetBitmap(ISegyFile segyFile)
 {
     return GetBitmap(segyFile.Traces);
 }
Example #20
0
 private void WriteBitmapPerInline(ISegyFile segyFile, string path, IEnumerable<int> inlineNumbers, dynamic range)
 {
     foreach (var inline in inlineNumbers)
     {
         var traces = segyFile.Traces.Where(t => t.Header.InlineNumber == inline);
         var filename = Path.GetFileNameWithoutExtension(path);
         var extenstion = Path.GetExtension(path);
         var newPath = filename + " (" + inline + ")" + extenstion;
         WriteBitmapForTraces(traces, newPath, range);
     }
 }
Example #21
0
 /// <summary>
 /// Returns a single bitmap image composed from all the trace in the SEGY file.
 /// The caller is responsible for disposing of the bitmap. This is highy recommended
 /// so that GDI resources will be cleaned up.
 /// </summary>
 /// <returns>A disposable bitmap</returns>
 public virtual Bitmap GetBitmap(ISegyFile segyFile)
 {
     return(GetBitmap(segyFile.Traces));
 }
Example #22
0
        //Bitmap graph;

        public static Bitmap Do(ISegyFile line, double side_a, double side_b, double v, double t, double[] maxmin, string pallete, int quantity_of_colors, double[] usilenie)
        {
            Bitmap    graph;
            double    quantity_of_dots_a = 0, quantity_of_dots_b = 0, x_for_a_quantity_of_traces = 0, koeff_i = 0;
            int       quantity_of_traces_a = 0, quantity_of_traces_b = 0, curr_trace = 0, quantity_of_dots = 0, step_size_for_trace = 0, n = 0;
            const int space_for_axes = 40;
            ColorMap  cmap;//инициализация палитры

            if (pallete == "default pallete")
            {
                cmap = new ColorMap("my_own_colormap", maxmin[0], maxmin[1], quantity_of_colors, MainForm.rgbs, MainForm.positions);
            }
            else
            {
                cmap = new ColorMap(pallete, maxmin[0], maxmin[1], quantity_of_colors);
            }
            if (side_a == side_b)                                                                                                 //если колонна квадратная
            {
                quantity_of_dots_a   = Math.Round(2 * side_a / (v * t));                                                          //количество точек
                quantity_of_dots_b   = quantity_of_dots_a;                                                                        //по сторонам количество точек одинаковое
                step_size_for_trace  = Convert.ToInt32(Math.Floor(line.Traces.Count / (4 * quantity_of_dots_a)));                 //шаг для трассы
                quantity_of_traces_a = line.Traces.Count;                                                                         //количество трасс
                graph = new Bitmap((int)quantity_of_dots_a + space_for_axes + 20, (int)quantity_of_dots_a + space_for_axes + 20); //создание битмапа


                for (int k = 0; k < 4; k++)                                //цикл по треугольникам
                {
                    curr_trace = quantity_of_traces_a / 4 * k;             //текущая трасса в зависимости от треугольника
                    for (int i = 0; i < quantity_of_dots_a; i++)           //цикл по основанию треугольника (ось х)
                    {
                        curr_trace = curr_trace + step_size_for_trace;     //изменяем трассу на шаг
                        for (int j = 0; j < i; j++)                        //цикл по высоте треугольника (ось у)
                        {
                            if (j > quantity_of_dots_a - i)                //если перешли половину
                            {
                                continue;                                  //то пропускаем итеррацию
                            }
                            GetColor(usilenie, cmap, line, curr_trace, j); //получаем цвет
                            switch (k)
                            {
                            case 0:                                                                                                   //рисуем левый треугольник
                                graph.SetPixel(space_for_axes + j, space_for_axes + i, Color.FromArgb(color[0], color[1], color[2])); //left
                                break;

                            case 1:                                                                                                                                         //рисуем нижний треугольник
                                graph.SetPixel(space_for_axes + i, space_for_axes + Convert.ToInt32(quantity_of_dots_a - j), Color.FromArgb(color[0], color[1], color[2])); //down
                                break;

                            case 2:                                                                                                                                                                               //рисуем правый треугольник
                                graph.SetPixel(space_for_axes + Convert.ToInt32(quantity_of_dots_a - j), space_for_axes + Convert.ToInt32(quantity_of_dots_a - i), Color.FromArgb(color[0], color[1], color[2])); //right
                                break;

                            case 3:                                                                                                                                         //рисуем верхний треугольник
                                graph.SetPixel(space_for_axes + Convert.ToInt32(quantity_of_dots_a - i), space_for_axes + j, Color.FromArgb(color[0], color[1], color[2])); //up
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                quantity_of_dots_a         = Math.Round(2 * side_a / (v * t));                                                                   //количество точек по длине
                quantity_of_dots_b         = Math.Round(2 * side_b / (v * t));                                                                   //количество точек по ширине
                x_for_a_quantity_of_traces = line.Traces.Count / (2 + 2 * (side_b / side_a));                                                    //неизвестная для распеределения трасс  по сторонам
                quantity_of_traces_a       = Convert.ToInt32(2 * x_for_a_quantity_of_traces);                                                    //количество трасс по длине
                quantity_of_traces_b       = Convert.ToInt32(2 * x_for_a_quantity_of_traces * (side_b / side_a));                                //количество трасс по ширине
                step_size_for_trace        = Convert.ToInt32(Math.Floor(line.Traces.Count / (2 * quantity_of_dots_a + 2 * quantity_of_dots_b))); //шаг для трассы
                graph = new Bitmap((int)quantity_of_dots_a + space_for_axes + 20, (int)quantity_of_dots_b + space_for_axes + 20);                //создание битмапа для изображения
                for (int k = 0; k < 4; k++)                                                                                                      //цикл по треугольникам
                {
                    switch (k)                                                                                                                   //инициализация начальных данных
                    {
                    case 0:                                                                                                                      //левый треугольник
                        quantity_of_dots = (int)quantity_of_dots_b;                                                                              //длина основания равна ширине изображения
                        koeff_i          = side_a / side_b;                                                                                      //кофэфициент равен длина / ширина = тангенс угла между диагональю и шириной
                        break;

                    case 1:                                         //нижний треугольник
                        quantity_of_dots = (int)quantity_of_dots_a; //длина основания равна длине изображения
                        koeff_i          = side_b / side_a;         //коэффициент равен ширина / длина = тангенс угла между диагональю и длиной
                        break;

                    case 2:                                         //правый треугольник
                        quantity_of_dots = (int)quantity_of_dots_b; //длина основания равна ширине изображения
                        koeff_i          = side_a / side_b;         //кофэфициент равен длина / ширина = тангенс угла между диагональю и шириной
                        break;

                    case 3:
                        quantity_of_dots = (int)quantity_of_dots_a; //длина основания равна длине изображения
                        koeff_i          = side_b / side_a;         //коэффициент равен ширина / длина = тангенс угла между диагональю и длиной
                        break;
                    }

                    for (int i = 0; i < quantity_of_dots; i++)            //цикл по основанию треугольника
                    {
                        curr_trace = curr_trace + step_size_for_trace;    //увеличение текущей трассы на шаг
                        if (i < quantity_of_dots / 2)                     //если двигаясь по основанию перешли половину
                        {
                            n = Convert.ToInt32(Math.Floor(koeff_i * i)); //то координата диагонали увеличивается с увеличением n
                        }
                        else
                        {
                            n = Convert.ToInt32(Math.Floor(koeff_i * (quantity_of_dots - i)));                                        //иначе уменьшается
                        }
                        for (int j = 0; j <= n; j++)                                                                                  //цикл по высоте от основания до начала диагонали в прямоугольнике (стороны треугольника)
                        {
                            GetColor(usilenie, cmap, line, curr_trace, j);                                                            //получить цвет
                            switch (k)                                                                                                //определение номера треугольника
                            {
                            case 0:                                                                                                   //левый треугольник
                                graph.SetPixel(space_for_axes + j, space_for_axes + i, Color.FromArgb(color[0], color[1], color[2])); //ставим пиксель
                                break;

                            case 1:                                                                                                                                         //нижний треугольник
                                graph.SetPixel(space_for_axes + i, space_for_axes + Convert.ToInt32(quantity_of_dots_b - j), Color.FromArgb(color[0], color[1], color[2])); ////ставим пиксель
                                break;

                            case 2:                                                                                                                                                                               //правый треугольник
                                graph.SetPixel(space_for_axes + Convert.ToInt32(quantity_of_dots_a - j), space_for_axes + Convert.ToInt32(quantity_of_dots_b - i), Color.FromArgb(color[0], color[1], color[2])); ////ставим пиксель
                                break;

                            case 3:                                                                                                                                         //верхний треугольник
                                graph.SetPixel(space_for_axes + Convert.ToInt32(quantity_of_dots_a - i), space_for_axes + j, Color.FromArgb(color[0], color[1], color[2])); ////ставим пиксель
                                break;
                            }
                        }
                    }
                }
            }
            return(graph);//возвращаем изображение
        }