/// <summary>
 /// Copy constructor
 /// </summary>
 /// <param name="source">The Data Operation to copy</param>
 public DataOperation(IDataOperation source)
 {
     ID = source.ID;
     for (int i = 0; i < source.ArgumentCount; i++)
     {
         AddArgument(source.GetArgument(i));
     }
 }
Esempio n. 2
0
 /// <summary>
 /// Copy constructor
 /// </summary>
 /// <param name="source">The Data Operation to copy</param>
 public DataOperation(IDataOperation source)
 {
     ID = source.ID;
     for (int i=0;i<source.ArgumentCount;i++)
         AddArgument(source.GetArgument(i));
 }
Esempio n. 3
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
        }
        /// <summary>
        /// Constructs a new <see cref="PropertyManager">PropertyManager</see> from <c>object</c>
        /// of known type.
        /// </summary>
        /// <param name="obj">Object of known type.</param>
        /// <param name="allReadOnly">If true, all properties are readonly.</param>
        /// <returns>Returns new <see cref="PropertyManager">PropertyManager</see>
        /// or <c>null</c> if object's type isn't known.</returns>
        /// <remarks>A this time this method knowns following types:
        /// <list>
        /// <item><see cref="IQuantity">IQuantity</see></item>
        /// <item><see cref="IElementSet">IElementSet</see></item>
        /// <item><see cref="IDataOperation">IDataOperation</see></item>
        /// <item><see cref="ILinkableComponent">ILinkableComponent</see></item>
        /// </list>
        /// Method saves <c>obj</c> parameter to <see cref="Tag">Tag</see> property, but you can
        /// use it for any purpose.
        /// </remarks>
        public static PropertyManager ConstructPropertyManager(object obj, bool allReadOnly)
        {
            PropertyManager prop = null;

            if (obj is IQuantity)
            {
                IQuantity quantity = (IQuantity)obj;
                prop = new PropertyManager();

                // General
                prop.SetProperty("Description", quantity.Description, true, "Description of this Quantity.", "General");
                prop.SetProperty("ID", quantity.ID, true, "ID of this Quantity.", "General");
                prop.SetProperty("ValueType", quantity.ValueType.ToString(), true, "Type of this Quantity's value.", "General");

                // Dimensions
                prop.SetProperty("AmountOfSubstance", quantity.Dimension.GetPower(DimensionBase.AmountOfSubstance).ToString(), true, "The amount of substance in mole.", "Dimensions");
                prop.SetProperty("Currency", quantity.Dimension.GetPower(DimensionBase.Currency).ToString(), true, "Currency in Euro.", "Dimensions");
                prop.SetProperty("ElectricCurrent", quantity.Dimension.GetPower(DimensionBase.ElectricCurrent).ToString(), true, "Electric current in ampere.", "Dimensions");
                prop.SetProperty("Length", quantity.Dimension.GetPower(DimensionBase.Length).ToString(), true, "Length in meter.", "Dimensions");
                prop.SetProperty("LuminousIntensity", quantity.Dimension.GetPower(DimensionBase.LuminousIntensity).ToString(), true, "Luminous intensity in candela.", "Dimensions");
                prop.SetProperty("Mass", quantity.Dimension.GetPower(DimensionBase.Mass).ToString(), true, "Mass in kilogram.", "Dimensions");
                prop.SetProperty("Temperature", quantity.Dimension.GetPower(DimensionBase.Temperature).ToString(), true, "Temperature in kelvin.", "Dimensions");
                prop.SetProperty("Time", quantity.Dimension.GetPower(DimensionBase.Time).ToString(), true, "Time in second.", "Dimensions");

                // Unit
                prop.SetProperty("ConversionFactorToSI", quantity.Unit.ConversionFactorToSI.ToString(), true, "Multiplicative coefficient used to convert this quantity to SI (SiUnit = Unit*ConversionFactorToSI + OffSetToSI).", "Unit");
                prop.SetProperty("OffSetToSI", quantity.Unit.OffSetToSI.ToString(), true, "Additive coefficient used to convert this quantity to SI (SiUnit = Unit*ConversionFactorToSI + OffSetToSI).", "Unit");
                prop.SetProperty("UnitDescription", quantity.Unit.Description, true, "Description of this unit.", "Unit");
                prop.SetProperty("UnitID", quantity.Unit.ID, true, "ID of this unit.", "Unit");
            }
            else if (obj is IElementSet)
            {
                IElementSet elementSet = (IElementSet)obj;
                prop = new PropertyManager();

                // General
                prop.SetProperty("ID", elementSet.ID, true, "ID of this ElementSet", "General");
                prop.SetProperty("Version", elementSet.Version.ToString(), true, "Version of this ElementSet.", "General");
                prop.SetProperty("SpatialReferenceID", elementSet.SpatialReference.ID, true, "ID of this ElementSet's SpatialReference", "General");
                prop.SetProperty("Description", elementSet.Description, true, "Description of this ElementSet.", "General");
                prop.SetProperty("ElementCount", elementSet.ElementCount.ToString(), true, "Count of elements of this ElementSet.", "General");
                prop.SetProperty("ElementType", elementSet.ElementType.ToString(), true, "Type of elements in this ElementSet.", "General");
            }
            else if (obj is IDataOperation)
            {
                IDataOperation dataOperation = (IDataOperation)obj;
                prop = new PropertyManager();

                string DataOperationID = "DataOperationID";

                // small trick to avoid that some argument's name is same as DataOperationID.
                // it's not quite pure, but it works:-)
                bool conflict;
                do
                {
                    conflict = false;
                    for (int i = 0; i < dataOperation.ArgumentCount; i++)
                    {
                        if (dataOperation.GetArgument(i).Key == DataOperationID)
                        {
                            DataOperationID += " ";
                            conflict         = true;
                            break;
                        }
                    }
                }while(conflict);

                // General
                prop.SetProperty(DataOperationID, dataOperation.ID, true, "ID of this DataOperation", "General");

                // Arguments
                for (int i = 0; i < dataOperation.ArgumentCount; i++)
                {
                    IArgument arg = dataOperation.GetArgument(i);
                    prop.SetProperty(arg.Key, arg.Value, arg.ReadOnly || allReadOnly, arg.Description, "Arguments");
                }
            }
            else if (obj is ILinkableComponent)
            {
                ILinkableComponent linkableComponent = (ILinkableComponent)obj;
                prop = new PropertyManager();

                DateTime
                    timeHorizonStart  = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.TimeHorizon.Start.ModifiedJulianDay),
                    timeHorizonEnd    = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.TimeHorizon.End.ModifiedJulianDay),
                    earliestInputTime = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.EarliestInputTime.ModifiedJulianDay);

                // General
                prop.SetProperty("ComponentID", linkableComponent.ComponentID, true, "ID the component.", "General");
                prop.SetProperty("ComponentDescription", linkableComponent.ComponentDescription, true, "Description of this component.", "General");
                prop.SetProperty("InputExchangeItemCount", linkableComponent.InputExchangeItemCount.ToString(), true, "Number of input exchange items.", "General");
                prop.SetProperty("OutputExchangeItemCount", linkableComponent.OutputExchangeItemCount.ToString(), true, "Number of output exchange items.", "General");
                prop.SetProperty("ModelID", linkableComponent.ModelID, true, "ID of the model (model=component+data).", "General");
                prop.SetProperty("ModelDescription", linkableComponent.ModelDescription, true, "Description of the model.", "General");
                prop.SetProperty("TimeHorizonStart", timeHorizonStart.ToString(), true, "Start of component's timehorizon.", "General");
                prop.SetProperty("TimeHorizonEnd", timeHorizonEnd.ToString(), true, "End of component's timehorizon.", "General");
                prop.SetProperty("ValidationMessage", linkableComponent.Validate(), true, "Validation string generated by component. No error ocured if it's empty.", "General");
                prop.SetProperty("EarliestInputTime", earliestInputTime.ToString(), true, "Earliest time for which component needs next input.", "General");

                string implementsIManageState = obj is IManageState ? "yes" : "no";
                prop.SetProperty("ImplementsIManageState", implementsIManageState, true, "Describes whether model implements IManageState interface.", "General");
            }

            if (prop != null)
            {
                prop.Tag = obj;
            }

            return(prop);
        }