public static object ReadDataFromCSV(string filePath, int titleRows = 0, string valuesSeparator = ";", string linesSeparator = "\n")
        {
            string        dataString     = ServiceTools.ReadTextFromFile(filePath);
            List <string> dataSubstrings = new List <string>(dataString.Split(linesSeparator.ToCharArray()));

            if (titleRows > 0)
            {
                dataSubstrings = dataSubstrings.Skip(titleRows).ToList();
            }

            dataSubstrings.RemoveAll(str => str == "");
            string[] values0 = dataSubstrings[0].Split(valuesSeparator.ToCharArray());
            if (values0.Count() == 1)
            {
                DenseVector retVec = DenseVector.Create(dataSubstrings.Count(),
                                                        idx => Convert.ToDouble(dataSubstrings[idx].Replace(".", ",")));
                return(retVec);
            }
            else
            {
                DenseMatrix retMatrix = DenseMatrix.Create(dataSubstrings.Count(), values0.Count(),
                                                           (r, c) =>
                                                           Convert.ToDouble(dataSubstrings[r].Split(valuesSeparator.ToCharArray())[c].Replace(".", ",")));
                //foreach (string substring in dataSubstrings)
                //{
                //    List<string> currRowStrings = new List<string>(substring.Split(valuesSeparator.ToCharArray()));
                //    retMatrix.InsertRow(retMatrix.RowCount,
                //        DenseVector.OfEnumerable(
                //            currRowStrings.ConvertAll<double>(str => Convert.ToDouble(str.Replace(".", ",")))));
                //}
                return(retMatrix);
            }
        }
        public static DenseMatrix ReadDenseMatrixFromFile(string fileName)
        {
            double[,] res = null;

            if (!ServiceTools.CheckIfDirectoryExists(fileName))
            {
                return(null);
            }
            NetCDFDataSet ds = null;

            try
            {
                ds = new NetCDFDataSet("msds:nc?file=" + fileName + "&enableRollback=false",
                                       ResourceOpenMode.ReadOnly);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            //Variable<double> thDataVar = ds.AddVariable<double>("dataMatrix", dmData.ToArray(), "y", "x");
            //Variable<double> thDataVar = ds.Variables
            foreach (Variable theVar in ds)
            {
                res = (double[, ])theVar.GetData();
            }

            return(DenseMatrix.OfArray(res));
        }
예제 #3
0
        public FileDatetimeInfo(string _filename, ServiceTools.DatetimeExtractionMethod method = ServiceTools.DatetimeExtractionMethod.Filename,
                                string _datetimeFilenameMask = "?????xxxxxxxxxxxxxxxxxxx*")
        {
            filename = _filename;
            datetimeExtractionMethod = method;
            datetimeFilenameMask     = _datetimeFilenameMask;

            switch (method)
            {
            case ServiceTools.DatetimeExtractionMethod.Filename:
            {
                try
                {
                    string strDateOfFile =
                        String.Concat(
                            Path.GetFileName(filename)
                            .Zip(datetimeFilenameMask, (c, s) => (s == 'x') ? (c.ToString()) : (""))
                            .ToArray());
                    datetime = CommonTools.DateTimeOfString(strDateOfFile);
                    DateTime.SpecifyKind(datetime, DateTimeKind.Utc);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                break;
            }

            case ServiceTools.DatetimeExtractionMethod.FileCreation:
            {
                datetime = new FileInfo(filename).CreationTimeUtc;
                DateTime.SpecifyKind(datetime, DateTimeKind.Utc);
                break;
            }

            case ServiceTools.DatetimeExtractionMethod.Content:
            {
                Dictionary <string, object> currDict = ServiceTools.ReadDictionaryFromXML(filename);
                currDict.Add("XMLfileName", Path.GetFileName(filename));
                ConcurrentData retVal = null;
                try
                {
                    retVal   = new ConcurrentData(currDict);
                    datetime = retVal.datetimeUTC;
                    DateTime.SpecifyKind(datetime, DateTimeKind.Utc);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                break;
            }

            default:
            {
                break;
            }
            }
        }
        private void pb1_DoubleClick(object sender, EventArgs e)
        {
            PictureBox pbSender     = sender as PictureBox;
            int        pbNumber     = Convert.ToInt32(pbSender.Name.ToString().Substring(2));
            Bitmap     targetBitmap = bmList[pbNumber - 1];

            ServiceTools.ShowPicture(targetBitmap);
        }
        private int getPointPositionY_ByValue(double value, object objContainer)
        {
            //int mouseClickY = pt.Y;
            double H     = Convert.ToDouble(ServiceTools.getPropValue(objContainer, "Height"));
            double dReal = (maxValue - minValue);
            double y     = H - (H / dReal) * (value - minValue);

            return(Convert.ToInt32(y));
        }
        public void SwapLog(string filename)
        {
            if (!ServiceTools.CheckIfDirectoryExists(filename))
            {
                return;
            }

            ServiceTools.logToTextFile(filename, textBox1.Text, false);

            ThreadSafeOperations.SetTextTB(textBox1, "", false);
        }
        private Rectangle RectangleOnImageFromRealValuesRectangle(RectangleF rectF2convert, object objContainer)
        {
            Rectangle rectOut = new Rectangle();

            rectOut.X      = Convert.ToInt32(rectF2convert.X);
            rectOut.Y      = getPointPositionY_ByValue(rectF2convert.Location.Y, objContainer);
            rectOut.Width  = Convert.ToInt32(rectF2convert.Width);
            rectOut.Height = Convert.ToInt32((Convert.ToDouble(ServiceTools.getPropValue(objContainer, "Height")) * (double)(rectF2convert.Height) / (maxValue - minValue)));

            return(rectOut);
        }
 public void Dispose()
 {
     //imgR.Dispose();
     //imgG.Dispose();
     //imgB.Dispose();
     dmR   = null;
     dmG   = null;
     dmB   = null;
     dmRes = null;
     ServiceTools.FlushMemory();
     //throw new NotImplementedException();
 }
        private ImageOperationalValue ImageOperationalValueDDY(ImageOperationalValue a)
        {
            ImageOperationalValue res = new ImageOperationalValue();

            if (a.operandType() == OperandTypes.DenseMatrix)
            {
                DenseMatrix dmOrig   = (DenseMatrix)a.DmImageComponent.Clone();
                DenseMatrix dmyPlus1 = (DenseMatrix)a.DmImageComponent.Clone();
                dmyPlus1.MapIndexedInplace(new Func <int, int, double, double>((row, column, val) =>
                {
                    if (row < dmyPlus1.RowCount - 1)
                    {
                        return(dmOrig[row + 1, column]);
                    }
                    else
                    {
                        return(val);
                    }
                }));

                DenseMatrix dmyMinus1 = (DenseMatrix)a.DmImageComponent.Clone();
                dmyMinus1.MapIndexedInplace(new Func <int, int, double, double>((row, column, val) =>
                {
                    if (row > 0)
                    {
                        return(dmOrig[row - 1, column]);
                    }
                    else
                    {
                        return(val);
                    }
                }));



                DenseMatrix dmGradY = dmyPlus1 - dmyMinus1;
                //dmGradY.MapInplace(new Func<double, double>(x => x/2.0d));
                dmGradY  = (DenseMatrix)dmGradY.Multiply(0.5d);
                dmyPlus1 = null;
                ServiceTools.FlushMemory();

                res.DmImageComponent = dmGradY;
                dmGradY = null;
                ServiceTools.FlushMemory();
            }
            else
            {
                res.dNumber = 0.0d;
            }

            return(res);
        }
예제 #10
0
        /// <summary>
        /// Makes the thresholded image representing the data, using setting like
        /// double thresholdingValue
        /// bool thresholdingUsageTop
        /// bool thresholdingUsageBtm
        ///
        /// DEPRECATED - legacy only
        /// </summary>
        public void makeThresholdedDataImage()
        {
            if (currentColorScheme == null)
            {
                return;
            }

            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix tmpDM = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)(dmSourceData.Clone());
            ImageProcessing.maskedImageChannelDenseMatrixThresholdedInplace(tmpDM, maskImageBinary, (double)thresholdingValue, 0.0d, thresholdingUsageTop, thresholdingUsageBtm);

            thresholdedImage = ImageProcessing.grayscaleImageFromDenseMatrix(tmpDM);

            ServiceTools.FlushMemory(null, null);
        }
        public string CSVHeader()
        {
            List <string> lStrPropertiesNames = ServiceTools.GetPropertiesNamesOfClass(this);
            List <string> lStrHeaders         = new List <string>();
            string        retStr = "";

            foreach (string propertyName in lStrPropertiesNames)
            {
                lStrHeaders.Add(propertyName);
            }

            retStr = String.Join(",", lStrHeaders.ToArray <string>());
            return(retStr);
        }
        public static DenseMatrix ReadDenseMatrixFromFile(string fileName, string varName = "DataMatrix")
        {
            double[,] res = null;
            DenseMatrix dmRes = null;

            if (!ServiceTools.CheckIfDirectoryExists(fileName))
            {
                return(null);
            }

            NetCDFDataSet ds = null;

            try
            {
                ds = new NetCDFDataSet("msds:nc?file=" + fileName + "&enableRollback=false", ResourceOpenMode.ReadOnly);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //Variable<double> thDataVar = ds.AddVariable<double>("dataMatrix", dmData.ToArray(), "y", "x");
            //Variable<double> thDataVar = ds.Variables
            foreach (Variable theVar in ds)
            {
                if (theVar.Name != varName)
                {
                    continue;
                }
                else
                {
                    if (theVar.TypeOfData == typeof(double))
                    {
                        res   = (double[, ])theVar.GetData();
                        dmRes = DenseMatrix.OfArray(res);
                    }
                    else if (theVar.TypeOfData == typeof(Single))
                    {
                        Single[,] res1 = (Single[, ])theVar.GetData();
                        dmRes          = DenseMatrix.Create(theVar.Dimensions[0].Length, theVar.Dimensions[1].Length, ((i, j) =>
                        {
                            return(Convert.ToDouble(res1[i, j]));
                        }));
                    }

                    break;
                }
            }

            return(dmRes);
        }
예제 #13
0
        public Field3Drepresentation(DenseMatrix dmDataToRepresent, Dictionary <string, object> properties, string description = "")
        {
            InitializeComponent();

            strDataDescription = description;
            ThreadSafeOperations.SetText(lblDescription, strDataDescription, false);

            defaultProperties  = properties;
            strOutputDirectory = (string)defaultProperties["DefaultDataFilesLocation"];
            if (!ServiceTools.CheckIfDirectoryExists(strOutputDirectory))
            {
                strOutputDirectory = "";
            }

            dmData = dmDataToRepresent.Copy();


            ILScene scene = new ILScene();

            currSurfPlotCube          = new ILPlotCube();
            currSurfPlotCube.TwoDMode = false;
            ILSurface surf;

            ILInArray <double> ilaDataMeshToShow = dmData.ToArray();

            if ((dmDataXcoord != null) && (dmDataYcoord != null))
            {
                ILInArray <double> ilaXvalues = dmDataXcoord.Row(0).ToArray();
                ILInArray <double> ilaYvalues = dmDataYcoord.Column(0).ToArray();
                surf = new ILSurface(ilaDataMeshToShow, ilaXvalues, ilaYvalues);
            }
            else
            {
                surf = new ILSurface(ilaDataMeshToShow);
            }

            surf.UseLighting = true;
            surf.Colormap    = Colormaps.ILNumerics;
            surf.Children.Add(new ILColorbar());

            currSurfPlotCube.Children.Add(surf);
            currSurfPlotCube.Rotation = Matrix4.Rotation(new Vector3(1, 0, 0), 1.2f) *
                                        Matrix4.Rotation(new Vector3(0, 0, 1), Math.PI);
            currSurfPlotCube.Projection = Projection.Perspective;

            scene.Add(currSurfPlotCube);

            ilPanel1.Scene = scene;
        }
        public static DenseMatrix sRGBluminanceFrom_sRGB(DenseMatrix dmR, DenseMatrix dmG, DenseMatrix dmB)
        {
            //Y_lin = 0.2126 R_lin + 0.7152 G_lin + 0.0722 B_lin

            // MathNet.Numerics.Control.UseNativeMKL();

            DenseMatrix dmLuminance;
            DenseMatrix dmLin = (DenseMatrix)dmR.Clone();

            //dmLin.MapInplace((val) => val/255.0d);
            dmLin = (DenseMatrix)dmLin.Divide(255.0d);
            // dmLin.MapInplace(sRGBtoLinear);
            dmLin = sRGBtoLinear(dmLin);
            //dmLin.MapInplace((val) => 0.2126d*val);
            dmLin       = (DenseMatrix)dmLin.Multiply(0.2126d);
            dmLuminance = (DenseMatrix)dmLin.Clone();

            ServiceTools.FlushMemory();

            dmLin = (DenseMatrix)dmG.Clone();
            // dmLin.MapInplace((val) => val / 255.0d);
            dmLin = (DenseMatrix)dmLin.Divide(255.0d);
            //dmLin.MapInplace(sRGBtoLinear);
            dmLin = sRGBtoLinear(dmLin);
            //dmLin.MapInplace((val) => 0.7152d * val);
            dmLin       = (DenseMatrix)dmLin.Multiply(0.7152d);
            dmLuminance = dmLuminance + dmLin;

            ServiceTools.FlushMemory();

            dmLin = (DenseMatrix)dmB.Clone();
            // dmLin.MapInplace((val) => val / 255.0d);
            dmLin = (DenseMatrix)dmLin.Divide(255.0d);
            //dmLin.MapInplace(sRGBtoLinear);
            dmLin = sRGBtoLinear(dmLin);
            //dmLin.MapInplace((val) => 0.0722d * val);
            dmLin       = (DenseMatrix)dmLin.Multiply(0.0722d);
            dmLuminance = dmLuminance + dmLin;

            ServiceTools.FlushMemory();

            //dmLuminance.MapInplace(LinearTo_sRGB);
            dmLuminance = LinearTo_sRGB(dmLuminance);
            //dmLuminance.MapInplace((val) => val * 255.0d);
            dmLuminance = (DenseMatrix)dmLuminance.Multiply(255.0d);

            return(dmLuminance);
        }
예제 #15
0
        private void pbRes_MouseMove(object sender, MouseEventArgs e)
        {
            imageConditionAndData currentImgData = null;

            if (sender == pbRes)
            {
                currentImgData = imgData;
            }
            PointD origDataPointPosition = new PointD();
            double clickedValue          = currentImgData.GetValueByClickEvent((PictureBox)sender, e, out origDataPointPosition);
            PointD thePointD             = currentImgData.getDataPositionByClickEvent((PictureBox)sender, e);
            Point  thePoint    = new Point(Convert.ToInt32(thePointD.X), Convert.ToInt32(thePointD.Y));
            string tooltipText = "position: " + thePoint + Environment.NewLine + ServiceTools.DoubleValueRepresentingString(clickedValue);

            ShowToolTip(e, tooltipText, sender);
        }
        public static List <List <string> > ReadDataFromCSV(string filePath, int titleRows = 0, bool nonNumberData = true, string valuesSeparator = ";", string linesSeparator = "\n")
        {
            string        dataString     = ServiceTools.ReadTextFromFile(filePath);
            List <string> dataSubstrings = new List <string>(dataString.Split(linesSeparator.ToCharArray()));

            if (titleRows > 0)
            {
                dataSubstrings = dataSubstrings.Skip(titleRows).ToList();
            }

            dataSubstrings.RemoveAll(str => str == "");

            List <List <string> > output =
                dataSubstrings.ConvertAll <List <string> >(
                    str => new List <string>(str.Split(valuesSeparator.ToCharArray())));

            return(output);
        }
예제 #17
0
        public bool SaveHistDataToXMLFole(string filename)
        {
            List <PointD> dataToSave = new List <PointD>();

            for (int i = 0; i < binsCount - 1; i++)
            {
                dataToSave.Add(new PointD(dvbinsCenters[i], dvProbDens[i]));
            }
            try
            {
                ServiceTools.WriteObjectToXML(dataToSave, filename);
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
        public LufftR2Sdata(string strCSVfileEntry)
        {
            List <string> lastWSdataStrings = ServiceTools.StringsDataFromCSVstring(strCSVfileEntry, ";");

            if (lastWSdataStrings.Count == 0)
            {
                throw new Exception("unable to parse CSV string using semicolon delimiter: " + Environment.NewLine +
                                    strCSVfileEntry);
            }

            dateTimeUTC = DateTime.ParseExact(lastWSdataStrings[0], "yyyy-MM-dd HH:mm:ss", null);
            DateTime.SpecifyKind(dateTimeUTC, DateTimeKind.Utc);

            PrecipitationAbs_mm            = CommonTools.ParseDouble(lastWSdataStrings[1]);
            PrecipitationTypeCode          = Convert.ToInt32(lastWSdataStrings[2]);
            AmbientTemperatureCels         = CommonTools.ParseDouble(lastWSdataStrings[3]);
            PrecipitationIntensity_milPerH = CommonTools.ParseDouble(lastWSdataStrings[4]);
        }
        private ImageOperationalValue ImageOperationalValueAbs(ImageOperationalValue a)
        {
            ImageOperationalValue res = new ImageOperationalValue();

            if (a.operandType() == OperandTypes.DenseMatrix)
            {
                DenseMatrix dmResLocal = (DenseMatrix)a.DmImageComponent.Clone();
                dmResLocal.MapInplace((val) => Math.Abs(val));
                res.DmImageComponent = dmResLocal;
                ServiceTools.FlushMemory();
            }
            else
            {
                res.dNumber = Math.Abs(a.dNumber);
            }

            return(res);
        }
        private ImageOperationalValue ImageOperationalValueSigm(ImageOperationalValue a)
        {
            ImageOperationalValue res = new ImageOperationalValue();

            if (a.operandType() == OperandTypes.DenseMatrix)
            {
                DenseMatrix           dmResLocal = (DenseMatrix)a.DmImageComponent.Clone();
                DescriptiveStatistics stat       = new DescriptiveStatistics(dmResLocal.Values);
                res.dNumber = stat.StandardDeviation;
                ServiceTools.FlushMemory();
            }
            else
            {
                res.dNumber = 0.0d;
            }

            return(res);
        }
        private ImageOperationalValue ImageOperationalValueSqrt(ImageOperationalValue a)
        {
            ImageOperationalValue res = new ImageOperationalValue();

            if (a.operandType() == OperandTypes.DenseMatrix)
            {
                DenseMatrix dmResLocal = (DenseMatrix)a.DmImageComponent.Clone();
                //dmResLocal.MapInplace(new Func<double, double>((val) => Math.Pow(val, 0.5d)));
                dmResLocal           = (DenseMatrix)dmResLocal.PointwisePower(0.5d);
                res.DmImageComponent = dmResLocal;
                ServiceTools.FlushMemory();
            }
            else
            {
                res.dNumber = Math.Sqrt(a.dNumber);
            }

            return(res);
        }
예제 #22
0
        private void ShowToolTip(MouseEventArgs e, String textToShow, object theElement)
        {
            if (textToolTip == null)
            {
                textToolTip = new ToolTip();
            }
            else
            {
                if (previousTooltipMouseLocation == e.Location)
                {
                    return;
                }
                textToolTip.Dispose();
                textToolTip = new ToolTip();
            }
            Point loc = (Point)ServiceTools.getPropValue(theElement, "Location");

            textToolTip.Show(textToShow, this, e.X + loc.X, e.Y + loc.Y);
            previousTooltipMouseLocation = e.Location;
        }
        public LufftWSdata(string strCSVfileEntry)
        {
            List <string> lastWSdataStrings = ServiceTools.StringsDataFromCSVstring(strCSVfileEntry, ";");

            if (lastWSdataStrings.Count == 0)
            {
                throw new Exception("unable to parse CSV string using semicolon delimiter: " + Environment.NewLine +
                                    strCSVfileEntry);
            }

            dateTimeUTC = DateTime.ParseExact(lastWSdataStrings[0], "yyyy-MM-dd HH:mm:ss", null);
            DateTime.SpecifyKind(dateTimeUTC, DateTimeKind.Utc);

            TemperatureCels = CommonTools.ParseDouble(lastWSdataStrings[1]);

            AirPressureAbs = CommonTools.ParseDouble(lastWSdataStrings[2]);

            relHumidity = CommonTools.ParseDouble(lastWSdataStrings[3]);

            absHumidity = CommonTools.ParseDouble(lastWSdataStrings[4]);
        }
예제 #24
0
        public bool SaveHistDataToASCII(string filename)
        {
            List <PointD> dataToSave = new List <PointD>();
            string        strToSave  = "bin-center;density" + Environment.NewLine;

            for (int i = 0; i < binsCount - 1; i++)
            {
                dataToSave.Add(new PointD(dvbinsCenters[i], dvProbDens[i]));
                strToSave += dvbinsCenters[i].ToString("e") + ";" + dvProbDens[i].ToString("e") + Environment.NewLine;
            }

            try
            {
                ServiceTools.logToTextFile(filename, strToSave);
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
        public string ToCSV()
        {
            List <string> lStrPropertiesNames = ServiceTools.GetPropertiesNamesOfClass(this);
            List <string> lStrValues          = new List <string>();
            string        retStr = "";

            foreach (string propertyName in lStrPropertiesNames)
            {
                object propValue = GetType().GetProperty(propertyName).GetValue(this, null);
                if ((propValue.GetType() == typeof(double)) || (propValue.GetType() == typeof(float)))
                {
                    lStrValues.Add(propValue.ToString().Replace(",", "."));
                }
                else
                {
                    lStrValues.Add(propValue.ToString());
                }
            }

            retStr = String.Join(",", lStrValues.ToArray <string>());
            return(retStr);
        }
        public static void AddDataMatrixToFile(DenseMatrix dmData, string fileName, TextBox tbLog,
                                               bool absolutePath = false, string varName = "dataMatrix")
        {
            string baseDir          = "G:\\_gulevlab\\SkyIndexAnalyzerSolo_appData\\_dataDirectory\\";
            string connectionString = "msds:nc?file=";

            if (absolutePath)
            {
                if (!ServiceTools.CheckIfDirectoryExists(fileName))
                {
                    return;
                }
                connectionString += fileName;
            }
            else
            {
                if (!ServiceTools.CheckIfDirectoryExists(baseDir + fileName))
                {
                    return;
                }
                connectionString += baseDir + fileName;
            }

            NetCDFDataSet ds = null;

            try
            {
                ds = new NetCDFDataSet(connectionString, ResourceOpenMode.OpenOrCreate);
            }
            catch (Exception ex)
            {
                if (tbLog != null)
                {
                    ThreadSafeOperations.SetTextTB(tbLog, "Не получилось :( " + Environment.NewLine + ex.Message, true);
                }
                else
                {
                    throw ex;
                }
            }


            Variable <double> thDataVar;

            if (!ds.Variables.Contains(varName))
            {
                thDataVar = ds.AddVariable <double>(varName, dmData.ToArray(), "y", "x");
            }
            else
            {
                thDataVar = (Variable <double>)ds.Variables[varName];
                thDataVar.Append(dmData.ToArray());
            }


            try
            {
                ds.TryCommit();
            }
            catch (Exception ex)
            {
                if (tbLog != null)
                {
                    ThreadSafeOperations.SetTextTB(tbLog, "Не получилось :( " + Environment.NewLine + ex.Message, true);
                }
                else
                {
                    throw ex;
                }
            }

            ds.Dispose();
        }
        public static void AddVariousDataToFile(Dictionary <string, object> dataToWrite, string fileName)
        {
            if (!ServiceTools.CheckIfDirectoryExists(fileName))
            {
                return;
            }

            string connectionString = "msds:nc?file=";

            connectionString += fileName;
            NetCDFDataSet ds = null;

            try
            {
                ds = new NetCDFDataSet(connectionString, ResourceOpenMode.OpenOrCreate);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            foreach (KeyValuePair <string, object> keyValuePair in dataToWrite)
            {
                if (keyValuePair.Value.GetType() == typeof(DenseMatrix))
                {
                    if (ds.Variables.Contains(keyValuePair.Key))
                    {
                        Variable <double> theDataVar = (Variable <double>)ds.Variables[keyValuePair.Key];
                        theDataVar.Append(((DenseMatrix)keyValuePair.Value).ToArray());
                    }
                    else
                    {
                        Variable <double> theDataVar = ds.AddVariable <double>(keyValuePair.Key,
                                                                               ((DenseMatrix)(keyValuePair.Value)).ToArray(), "y", "x");
                    }
                }

                if (keyValuePair.Value.GetType() == typeof(DenseVector))
                {
                    if (ds.Variables.Contains(keyValuePair.Key))
                    {
                        Variable <double> theDataVar = (Variable <double>)ds.Variables[keyValuePair.Key];
                        theDataVar.Append(((DenseVector)keyValuePair.Value).ToArray());
                    }
                    else
                    {
                        Variable <double> theDataVar = ds.AddVariable <double>(keyValuePair.Key,
                                                                               ((DenseVector)(keyValuePair.Value)).ToArray(), keyValuePair.Key);
                    }
                }

                if (keyValuePair.Value.GetType() == typeof(long[]))
                {
                    if (ds.Variables.Contains(keyValuePair.Key))
                    {
                        Variable <long> theDataVar = (Variable <long>)ds.Variables[keyValuePair.Key];
                        theDataVar.Append((long[])(keyValuePair.Value));
                    }
                    else
                    {
                        Variable <long> theDataVar = ds.AddVariable <long>(keyValuePair.Key, (long[])(keyValuePair.Value),
                                                                           keyValuePair.Key);
                    }
                }

                if (keyValuePair.Value.GetType() == typeof(int[]))
                {
                    if (ds.Variables.Contains(keyValuePair.Key))
                    {
                        Variable <int> theDataVar = (Variable <int>)ds.Variables[keyValuePair.Key];
                        theDataVar.Append((int[])(keyValuePair.Value));
                    }
                    else
                    {
                        Variable <int> theDataVar = ds.AddVariable <int>(keyValuePair.Key, (int[])(keyValuePair.Value),
                                                                         keyValuePair.Key);
                    }
                }

                if (keyValuePair.Value.GetType() == typeof(string[]))
                {
                    if (ds.Variables.Contains(keyValuePair.Key))
                    {
                        Variable <string> theDataVar = (Variable <string>)ds.Variables[keyValuePair.Key];
                        theDataVar.Append((string[])(keyValuePair.Value));
                    }
                    else
                    {
                        Variable <string> theDataVar = ds.AddVariable <string>(keyValuePair.Key, (string[])(keyValuePair.Value),
                                                                               keyValuePair.Key);
                    }
                }
            }

            try
            {
                ds.TryCommit();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            ds.Dispose();
        }
        public static void SaveVariousDataToFile(Dictionary <string, object> dataToWrite, string fileName)
        {
            if (!ServiceTools.CheckIfDirectoryExists(fileName))
            {
                return;
            }

            string connectionString = "msds:nc?file=";

            connectionString += fileName;
            // connectionString += "&deflate=best";
            NetCDFDataSet ds = null;

            try
            {
                ds = new NetCDFDataSet(connectionString, ResourceOpenMode.Create);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            foreach (KeyValuePair <string, object> keyValuePair in dataToWrite)
            {
                if (keyValuePair.Value.GetType() == typeof(DenseMatrix))
                {
                    try
                    {
                        Variable <double> theDataVar = ds.AddVariable <double>(keyValuePair.Key, ((DenseMatrix)(keyValuePair.Value)).ToArray(), "y", "x");
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                if (keyValuePair.Value.GetType() == typeof(DenseVector))
                {
                    try
                    {
                        Variable <double> theDataVar = ds.AddVariable <double>(keyValuePair.Key, ((DenseVector)(keyValuePair.Value)).ToArray(), keyValuePair.Key);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                if (keyValuePair.Value.GetType() == typeof(long[]))
                {
                    try
                    {
                        Variable <long> theDataVar = ds.AddVariable <long>(keyValuePair.Key, (long[])(keyValuePair.Value), keyValuePair.Key);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }


                if (keyValuePair.Value.GetType() == typeof(long[, ]))
                {
                    try
                    {
                        Variable <long> theDataVar = ds.AddVariable <long>(keyValuePair.Key, (long[, ])(keyValuePair.Value), "y", "x");
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }


                if (keyValuePair.Value.GetType() == typeof(int[]))
                {
                    try
                    {
                        Variable <int> theDataVar = ds.AddVariable <int>(keyValuePair.Key, (int[])(keyValuePair.Value), keyValuePair.Key);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }


                if (keyValuePair.Value.GetType() == typeof(int[, ]))
                {
                    try
                    {
                        Variable <int> theDataVar = ds.AddVariable <int>(keyValuePair.Key, (int[, ])(keyValuePair.Value), "y", "x");
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }


                if (keyValuePair.Value.GetType() == typeof(short[]))
                {
                    try
                    {
                        Variable <short> theDataVar = ds.AddVariable <short>(keyValuePair.Key, (short[])(keyValuePair.Value), keyValuePair.Key);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }


                if (keyValuePair.Value.GetType() == typeof(short[, ]))
                {
                    try
                    {
                        Variable <short> theDataVar = ds.AddVariable <short>(keyValuePair.Key, (short[, ])(keyValuePair.Value), "y", "x");
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }



                if (keyValuePair.Value.GetType() == typeof(byte[]))
                {
                    try
                    {
                        Variable <byte> theDataVar = ds.AddVariable <byte>(keyValuePair.Key, (byte[])(keyValuePair.Value), keyValuePair.Key);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }


                if (keyValuePair.Value.GetType() == typeof(byte[, ]))
                {
                    try
                    {
                        Variable <byte> theDataVar = ds.AddVariable <byte>(keyValuePair.Key, (byte[, ])(keyValuePair.Value), "y", "x");
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }



                if (keyValuePair.Value.GetType() == typeof(byte[, , ]))
                {
                    try
                    {
                        Variable <byte> theDataVar = ds.AddVariable <byte>(keyValuePair.Key, (byte[, , ])(keyValuePair.Value), "y", "x", "z");
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }



                if (keyValuePair.Value.GetType() == typeof(string[]))
                {
                    Variable <string> theDataVar = ds.AddVariable <string>(keyValuePair.Key, (string[])(keyValuePair.Value), keyValuePair.Key);
                }
            }



            try
            {
                ds.TryCommit();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            ds.Dispose();
        }
        public static Dictionary <string, object> ReadDataFromFile(string fileName, List <string> varNames = null)
        {
            if (!ServiceTools.CheckIfDirectoryExists(fileName))
            {
                return(null);
            }

            Dictionary <string, object> retDict = new Dictionary <string, object>();

            double[,] res = null;
            NetCDFDataSet ds = null;

            try
            {
                ds = new NetCDFDataSet("msds:nc?file=" + fileName + "&enableRollback=false", ResourceOpenMode.ReadOnly);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            foreach (Variable theVar in ds)
            {
                bool loadThisVar = false;
                if (varNames == null)
                {
                    loadThisVar = true;
                }
                else if (varNames.Contains(theVar.Name))
                {
                    loadThisVar = true;
                }
                if (!loadThisVar)
                {
                    continue;
                }

                if (theVar.TypeOfData == typeof(double))
                {
                    if (theVar.Dimensions.Count == 1)
                    {
                        double[] res1 = (double[])theVar.GetData();
                        retDict.Add(theVar.Name, DenseVector.OfEnumerable(res1));
                    }
                    else if (theVar.Dimensions.Count == 2)
                    {
                        double[,] res1 = (double[, ])theVar.GetData();
                        retDict.Add(theVar.Name, DenseMatrix.OfArray(res1));
                    }
                }



                if (theVar.TypeOfData == typeof(Single))
                {
                    if (theVar.Dimensions.Count == 1)
                    {
                        Single[]    res1   = (Single[])theVar.GetData();
                        DenseVector dvRes1 = DenseVector.Create(theVar.Dimensions[0].Length,
                                                                i => Convert.ToDouble(res1[i]));
                        retDict.Add(theVar.Name, dvRes1);
                    }
                    else if (theVar.Dimensions.Count == 2)
                    {
                        Single[,] res1 = (Single[, ])theVar.GetData();
                        DenseMatrix dmRes = DenseMatrix.Create(theVar.Dimensions[0].Length, theVar.Dimensions[1].Length,
                                                               ((i, j) =>
                        {
                            return(Convert.ToDouble(res1[i, j]));
                        }));
                        retDict.Add(theVar.Name, dmRes);
                    }
                }



                if (theVar.TypeOfData == typeof(long))
                {
                    if (theVar.Dimensions.Count == 1)
                    {
                        long[] res1 = (long[])theVar.GetData();
                        retDict.Add(theVar.Name, res1);
                    }
                    else if (theVar.Dimensions.Count == 2)
                    {
                        long[,] res1 = (long[, ])theVar.GetData();
                        retDict.Add(theVar.Name, res1);
                    }
                }


                if (theVar.TypeOfData == typeof(int))
                {
                    if (theVar.Dimensions.Count == 1)
                    {
                        int[] res1 = (int[])theVar.GetData();
                        retDict.Add(theVar.Name, res1);
                    }
                    else if (theVar.Dimensions.Count == 2)
                    {
                        int[,] res1 = (int[, ])theVar.GetData();
                        retDict.Add(theVar.Name, res1);
                    }
                }


                if (theVar.TypeOfData == typeof(string))
                {
                    string[] res1 = (string[])theVar.GetData();
                    retDict.Add(theVar.Name, res1);
                }
            }

            return(retDict);
        }
        public void SaveAsPDF(string filename = "", bool absolutePath = true)
        {
            if (filename == "")
            {
                return;
            }

            int pointsCount = 101;

            string matlabScript = "clear;" + Environment.NewLine;

            matlabScript += "fig = figure;" + Environment.NewLine;
            matlabScript += "set(fig,'units','normalized','outerposition',[0 0 1 1]);" + Environment.NewLine;
            matlabScript += "hold on;" + Environment.NewLine;

            double xSpaceDiff = (xSpaceMax - xSpaceMin) / (double)(pointsCount - 1);


            if (theRepresentingFunctions.Count > 0)
            {
                DenseVector xSpaceML = DenseVector.Create(pointsCount, new Func <int, double>(i =>
                {
                    return(xSpaceMin + ((double)i / (double)pointsCount) * (xSpaceMax - xSpaceMin));
                }));

                foreach (Tuple <int, double> tuple in xSpaceML.EnumerateIndexed())
                {
                    matlabScript += "xSpace(" + (tuple.Item1 + 1).ToString() + ") = " + tuple.Item2.ToString("e").Replace(",", ".") + ";" + Environment.NewLine;
                }

                int funcCounter = 0;
                for (int funcIndex = 0; funcIndex < theRepresentingFunctions.Count; funcIndex++)
                {
                    Func <DenseVector, double, double> function = theRepresentingFunctions[funcIndex];
                    DenseVector parametersVector = parameters[funcIndex];

                    DenseVector dvCurrFuncValues = DenseVector.Create(pointsCount,
                                                                      new Func <int, double>(i => function(parametersVector, xSpaceML[i])));
                    foreach (Tuple <int, double> tuple in dvCurrFuncValues.EnumerateIndexed())
                    {
                        matlabScript += "func" + funcIndex.ToString() + "(" + (tuple.Item1 + 1).ToString() + ") = " + tuple.Item2.ToString("e").Replace(",", ".") + ";" + Environment.NewLine;
                    }
                }


                for (int i = 0; i < theRepresentingFunctions.Count; i++)
                {
                    Bgr    CurrColor = lineColors[i];
                    string colR      = (CurrColor.Red / 255.0d).ToString("e").Replace(",", ".");
                    string colG      = (CurrColor.Green / 255.0d).ToString("e").Replace(",", ".");
                    string colB      = (CurrColor.Blue / 255.0d).ToString("e").Replace(",", ".");
                    matlabScript += "plot(xSpace, func" + i + ", 'Color', [" + colR + " " + colG + " " + colB + "], 'LineWidth', 2.0);" + Environment.NewLine;
                }
            }


            if ((dvScatterXSpace != null) && (dvScatterFuncValues != null))
            {
                foreach (Tuple <int, double> tuple in dvScatterXSpace.EnumerateIndexed())
                {
                    matlabScript += "scatterXSpace(" + (tuple.Item1 + 1).ToString() + ") = " + tuple.Item2.ToString("e").Replace(",", ".") + ";" + Environment.NewLine;
                }


                foreach (Tuple <int, double> tuple in dvScatterFuncValues.EnumerateIndexed())
                {
                    matlabScript += "scatterFuncVals(" + (tuple.Item1 + 1).ToString() + ") = " + tuple.Item2.ToString("e").Replace(",", ".") + ";" + Environment.NewLine;
                }

                matlabScript += "scatter(scatterXSpace, scatterFuncVals, 'bo', 'LineWidth', 2);" + Environment.NewLine;
            }

            matlabScript += "title('" + currentDescription + "', 'FontWeight','bold', 'FontUnits', 'normalized', 'FontSize', 0.03);" + Environment.NewLine;
            matlabScript += "ylabel(gca, '" + yAxisNote + "', 'FontWeight','bold', 'FontUnits', 'normalized', 'FontSize', 0.03);" + Environment.NewLine;
            matlabScript += "xlabel(gca, '" + xAxisNote + "', 'FontWeight','bold', 'FontUnits', 'normalized', 'FontSize', 0.03);" + Environment.NewLine;
            matlabScript += "export_fig '" + filename + "';" + Environment.NewLine;
            matlabScript += "close(fig);" + Environment.NewLine;

            ServiceTools.logToTextFile(filename.Replace(".", "") + ".m", matlabScript);

            //MLApp.MLApp ml = new MLApp.MLApp();
            //ml.Visible = 0;
            //ml.Execute("run('" + curDir + "tmpMLscript.m" + "');");
            //File.Delete(curDir + "tmpMLscript.m");
            //ml.Execute("exit;");
        }