Ejemplo n.º 1
0
 public void SetValues(ITime time, object values)
 {
     if (!(values is double[]))
     {
         throw new ArgumentException("Expecting array of doubles");
     }
     buffer.AddValues(time, (double[])values);
 }
Ejemplo n.º 2
0
        public override void Initialize(IArgument[] arguments)
        {
            Status = LinkableComponentStatus.Initializing;
              double start = Time.ToModifiedJulianDay(new DateTime(2004, 12, 31, 0, 0, 0));

              for (int i = 0; i < 30; i++)
              {
            buffer.AddValues(new Time(start + i, 1), new double[] { i });
              }
              Status = LinkableComponentStatus.Initialized;
        }
 private void CheckBuffer()
 {
     if (_buffer == null)
     {
         _buffer = new SmartBuffer();
         ITimeSpaceValueSet outputItemValues = _adaptee.Values;
         IList <ITime>      outputItemTimes  = _adaptee.TimeSet.Times;
         for (int t = 0; t < outputItemTimes.Count; t++)
         {
             ITime time = outputItemTimes[t];
             _buffer.AddValues(time, outputItemValues.GetElementValuesForTime(0));
         }
     }
 }
Ejemplo n.º 4
0
 private void CheckBuffer()
 {
     if (buffer == null)
     {
         buffer = new SmartBuffer();
         IList         outputItemValues = DecoratedOutputItem.Values;
         IList <ITime> outputItemTimes  = DecoratedOutputItem.TimeSet.Times;
         int           i = 0;
         foreach (ITime time in outputItemTimes)
         {
             buffer.AddValues(time, new double[] { (double)outputItemValues[i++] });
         }
     }
 }
Ejemplo n.º 5
0
        private void AddToBuffer(ILink link)
        {
            // ----------------------------------------------------------------------------------------------------
            // The method adds values associated with the link.source to a SmartBuffer.
            // ----------------------------------------------------------------------------------------------------

            //dictionary of values indexed by their date\time
            SortedDictionary <DateTime, ArrayList> dict = new SortedDictionary <DateTime, ArrayList>();

            //create a buffer instance to temporarily store data
            SmartBuffer _smartBuffer = new SmartBuffer();

            //set the relaxation factor, if specifed in *.omi file.
            if (_relaxationFactor > 0)
            {
                _smartBuffer.RelaxationFactor = _relaxationFactor;
            }

            //get link.source quantity and elementset
            IQuantity   sourceQuantity   = link.SourceQuantity;
            IElementSet sourceElementSet = link.SourceElementSet;

            string sql = "SELECT DISTINCT ds.SeriesID " +
                         "FROM DataValues dv " +
                         "INNER JOIN DataSeries ds ON dv.SeriesID = ds.SeriesID " +
                         "INNER JOIN DataThemes dt ON dv.SeriesID = dt.SeriesID " +
                         "INNER JOIN Sites s ON ds.SiteID = s.SiteID " +
                         "INNER JOIN DataThemeDescriptions dtd On dt.ThemeID = dtd.ThemeID " +
                         "WHERE dtd.ThemeName = '" + sourceElementSet.ID.ToString() + "' " +
                         "ORDER BY s.SiteName ASC";

            DataTable tbl = _db.LoadTable("values", sql);

            //get the number of series' in this theme
            Dictionary <string, int> sites = new Dictionary <string, int>();

            //get the number of sites in this series
            int k = 0;

            foreach (DataRow row in tbl.Rows)
            {
                if (!sites.ContainsKey(Convert.ToString(row["SeriesID"])))
                {
                    sites.Add(Convert.ToString(row["SeriesID"]), k);
                    k++;
                }
            }


            //query the db for values associated with source quantity and elementset
            //TODO: LOOKUP BY THEMENAME, NOT THEMEID
            sql = "SELECT ds.SeriesID, dv.LocalDateTime, dv.DataValue " +
                  "FROM DataValues dv " +
                  "INNER JOIN DataSeries ds ON dv.SeriesID = ds.SeriesID " +
                  "INNER JOIN DataThemes dt ON dv.SeriesID = dt.SeriesID " +
                  "INNER JOIN DataThemeDescriptions dtd On dt.ThemeID = dtd.ThemeID " +
                  "WHERE dtd.ThemeName = '" + sourceElementSet.ID.ToString() + "' " +
                  "ORDER BY dv.LocalDateTime ASC";
            //"ORDER BY dv.DataValue ASC";

            tbl = _db.LoadTable("values", sql);

            //get the number of series' in this theme
            List <DateTime> t = new List <DateTime>();
            Dictionary <DateTime, double[]> Times = new Dictionary <DateTime, double[]>();

            //get the number of sites in this series
            //int k = 0;
            //foreach (DataRow row in tbl.Rows)
            //{
            //    if (!sites.ContainsKey(Convert.ToString(row["SeriesID"])))
            //    {
            //        sites.Add(Convert.ToString(row["SeriesID"]), k);
            //        k++;
            //    }

            //    if(!t.Contains(Convert.ToDateTime(row["LocalDateTime"])))
            //        t.Add(Convert.ToDateTime(row["LocalDateTime"]));
            //}
            //initialize a dictionary to hold the times and values
            foreach (DataRow row in tbl.Rows)
            {
                if (!Times.ContainsKey(Convert.ToDateTime(row["LocalDateTime"])))
                {
                    Times.Add(Convert.ToDateTime(row["LocalDateTime"]), new double[sites.Count]);
                }
            }
            //Times.OrderBy<pair,
            Times.OrderBy(pair => pair.Value);
            foreach (DataRow row in tbl.Rows)
            {
                double   v  = Convert.ToDouble(row["DataValue"]);
                string   id = Convert.ToString(row["SeriesID"]);
                DateTime dt = Convert.ToDateTime(row["LocalDateTime"]);
                Times[dt][sites[id]] = v;
            }


            for (int i = 0; i <= t.Count - 1; i++)
            {
                double[] vals = new double[sites.Count];
                DateTime dt   = t[i];
                foreach (DataRow row in tbl.Rows)
                {
                    double v  = Convert.ToDouble(row["DataValue"]);
                    string id = Convert.ToString(row["SeriesID"]);

                    //add v to vals in the location defined by its site id
                    vals[sites[id]] = v;
                }

                ArrayList a = new ArrayList();
                a.Add(vals);
                dict.Add(t[i], a);
            }
            ////check to see if time/value combination has been already added
            //if (dict.ContainsKey(dt))
            //{
            //    //if yes, add value to existing dictionary
            //    ArrayList a = dict[dt];
            //    a.Add(v);
            //}
            //else
            //{
            //    //if not, add value to new dictionary
            //    ArrayList a = new ArrayList();
            //    a.Add(v);
            //    dict.Add(dt, a);
            //}

            //double[] valueset = null;
            //ITimeStamp time_stmp = null;
            ////add dictionary to the smart buffer
            //foreach (KeyValuePair<DateTime, ArrayList> kvp in dict)
            //{
            //    time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
            //    valueset = (double[])kvp.Value.ToArray(typeof(double));
            //    _smartBuffer.AddValues(time_stmp, new ScalarSet(valueset));
            //}


            // //sort the dictionary
            //var sortDict = from keys in Times.Keys
            //           orderby Times[keys] ascending
            //           select keys;

            ////Times = (Dictionary<DateTime, double[]>)sortDict;

            //foreach (KeyValuePair<DateTime, double[]> kvp in Times.OrderBy(key => key.Value))
            //{

            //    time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
            //    valueset = kvp.Value;
            //    _smartBuffer.AddValues(time_stmp, new ScalarSet(valueset));
            //}

            //add dictionary to the smart buffer
            double[]   valueset  = null;
            ITimeStamp time_stmp = null;

            foreach (KeyValuePair <DateTime, double[]> kvp in Times)
            {
                time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
                valueset  = kvp.Value;
                _smartBuffer.AddValues(time_stmp, new ScalarSet(valueset));
            }

            //if ExactMatch is requested, then save the times for using in the GetValues method
            try
            {
                if (_exactMatch)
                {
                    List <double> times = new List <double>();
                    foreach (KeyValuePair <DateTime, double[]> kvp in Times)
                    {
                        time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
                        times.Add(time_stmp.ModifiedJulianDay);
                    }
                    _times.Add(link.ID, times);
                }
            }
            catch (Exception) { }

            ////if ExactMatch is requested, then save the times for using in the GetValues method
            //try
            //{
            //    if (_exactMatch)
            //    {
            //        List<double> times = new List<double>();
            //        foreach (KeyValuePair<DateTime, ArrayList> kvp in dict)
            //        {

            //            time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
            //            times.Add(time_stmp.ModifiedJulianDay);
            //        }
            //        _times.Add(link.ID, times);
            //    }
            //}
            //catch (Exception) { }

            //store the number of elements for this link
            _elementCount.Add(link.ID, valueset.Length);

            //store the lastest known time for this link
            _endTimes.Add(link.ID, (TimeStamp)time_stmp);
            //store the smart buffer based on linkID
            _buffer.Add(link.ID, _smartBuffer);

            //initialize the last index variable
            _lastIndex.Add(link.ID, 0);

            //adjust start time based on target component
            if (link.TargetComponent.TimeHorizon.Start.ModifiedJulianDay > this.EarliestInputTime.ModifiedJulianDay)
            {
                this._earliestInputTime = link.TargetComponent.TimeHorizon.Start.ModifiedJulianDay;
            }


            #region Initialize Element Mapper

            try
            {
                //get the first (stored) data operation
                IDataOperation dataOp = link.GetDataOperation(0);
                //get dataOperation description
                string dataOpDesc = dataOp.GetArgument(1).Value;
                //add a element mapper instance to the mapper dictionary
                mapper.Add(link.ID, new ElementMapper());
                //initialize the element mapper and create a mapping matrix
                mapper[link.ID].Initialise(dataOpDesc, link.SourceElementSet, link.TargetElementSet);
            }
            catch (Exception e) { }

            #endregion
        }
Ejemplo n.º 6
0
        public void LinearTimeInterpolation()
        {
            Console.Write("Begin Linear Interpolation Test...");

            //create the his component
            DbReader his = new DbReader();

            IArgument[] arguments = new IArgument[1];
            arguments[0] = new Argument("DbPath", @"..\data\cuahsi-his\demo.db", true, "Database");
            his.Initialize(arguments);

            //create a trigger component
            Trigger trigger = new Trigger();

            trigger.Initialize(null);

            //link the two components
            Link link = new Link();

            link.ID = "link-1";
            link.TargetElementSet = trigger.GetInputExchangeItem(0).ElementSet;
            link.TargetQuantity   = trigger.GetInputExchangeItem(0).Quantity;
            link.TargetComponent  = trigger;


            link.SourceElementSet = his.GetOutputExchangeItem(1).ElementSet;
            link.SourceQuantity   = his.GetOutputExchangeItem(1).Quantity;
            link.TargetComponent  = his;


            //Spatial interpolation
            IDataOperation dataOp = (his).GetOutputExchangeItem(0).GetDataOperation(7);

            link.AddDataOperation(dataOp);


            //run configuration
            his.AddLink(link);

            trigger.Validate();
            his.Validate();

            //prepare
            his.Prepare();

            DateTime dt = Convert.ToDateTime("2009-08-20T21:40:00");

            SmartBuffer _smartBuffer = new SmartBuffer();

            //Add all values to buffer in 10min intervals
            Console.Write("Storing values in the smart buffer (10min resolution)... ");
            while (dt <= Convert.ToDateTime("2009-08-21T02:00:00"))
            {
                ITimeStamp time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(dt));
                ScalarSet  scalarset = (ScalarSet)his.GetValues(time_stmp, "link-1");

                if (scalarset.Count == 0)
                {
                    int       f         = his.GetOutputExchangeItem(1).ElementSet.ElementCount;
                    ArrayList zeroArray = new ArrayList();
                    for (int i = 0; i <= f - 1; i++)
                    {
                        zeroArray.Add(0.0);
                    }

                    double[] zeros = (double[])zeroArray.ToArray(typeof(double));

                    scalarset = new ScalarSet(zeros);
                }

                _smartBuffer.AddValues(time_stmp, scalarset);

                dt = dt.AddMinutes(10);
            }
            Console.WriteLine("done.\n\n");

            //request values from the smart buffer at 5min intervals
            dt = Convert.ToDateTime("2009-08-20T21:40:00");
            while (dt <= Convert.ToDateTime("2009-08-21T02:00:00"))
            {
                ITimeStamp time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(dt));

                //Get values at requested time
                ScalarSet scalarset = (ScalarSet)_smartBuffer.GetValues(time_stmp);

                Console.WriteLine("GetValues: " + dt.ToString("s"));


                //loop through interpolated values
                int i = 0;
                foreach (double d in scalarset.data)
                {
                    Console.WriteLine(link.SourceElementSet.GetElementID(i).ToString() + " " + d.ToString());
                    ++i;
                }
                dt = dt.AddMinutes(5);
            }

            Console.Write("done. \n");
        }
Ejemplo n.º 7
0
        private SmartBuffer CreateBuffer(string elementSet)
        {
            Dictionary <DateTime, ArrayList> dict = new Dictionary <DateTime, ArrayList>();
            SmartBuffer smartbuffer = new SmartBuffer();

            //Move to the .dll directory
            try
            {
                Directory.SetCurrentDirectory(_fullPath);
            }
            catch (System.IO.IOException) { }


            elementSet = _dbPath + "\\" + elementSet;
            string[] files = Directory.GetFiles(elementSet);



            //read all files within element set
            foreach (string file in files)
            {
                //load the first file in the directory as an XML document
                XmlDocument xmldoc = new XmlDocument();

                // load the first xml file in the directory
                StreamReader sr = new StreamReader(file);

                //deserialize
                XmlSerializer          xml_reader = new XmlSerializer(typeof(TimeSeriesResponseType));
                TimeSeriesResponseType tsr        = (TimeSeriesResponseType)xml_reader.Deserialize(sr);


                ValueSingleVariable[] values = tsr.timeSeries.values.value;

                foreach (ValueSingleVariable value in values)
                {
                    DateTime dt = value.dateTime;
                    double   v  = Convert.ToDouble(value.Value);

                    //check to see if time/value combination has been already added
                    if (dict.ContainsKey(dt))
                    {
                        ArrayList a = dict[dt];
                        a.Add(v);
                    }
                    //Add key to dictionary
                    else
                    {
                        ArrayList a = new ArrayList();
                        a.Add(v);
                        dict.Add(dt, a);
                    }
                }
            }

            //put values in oder, starting with the earliest time (from http://dotnetperls.com/sort-dictionary-values)
            var items = from k in dict.Keys
                        orderby dict[k] ascending
                        select k;

            //load values into the smart buffer
            foreach (KeyValuePair <DateTime, ArrayList> kvp in dict)
            {
                ITimeStamp time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
                double[]   valueset  = (double[])kvp.Value.ToArray(typeof(double));
                smartbuffer.AddValues(time_stmp, new ScalarSet(valueset));
            }
            return(smartbuffer);
        }