Ejemplo n.º 1
0
        public void EarliestInputTime()
        {
            gwModelLC.Prepare();
            DateTime earliestInputTime = CalendarConverter.ModifiedJulian2Gregorian(gwModelLC.EarliestInputTime.ModifiedJulianDay);

            Assert.AreEqual(new DateTime(1990, 1, 2, 0, 0, 0), earliestInputTime);
        }
Ejemplo n.º 2
0
        public void Test_GK()
        {
            double jd;

            const double needJD = 2448174.5; // 1990-10-10 [g], 1990-09-27 [j], 5751-07-21 [h]

            //for (int i = 0; i < 1000000; i++) {
            jd = CalendarConverter.gregorian_to_jd2(-4713, 11, 24);
            Assert.AreEqual(0.0, jd);

            jd = CalendarConverter.gregorian_to_jd(1990, 10, 10);
            Assert.AreEqual(needJD, jd);

            jd = CalendarConverter.julian_to_jd(1990, 09, 27);
            Assert.AreEqual(needJD, jd);

            jd = CalendarConverter.hebrew_to_jd(5751, 07, 21);
            Assert.AreEqual(needJD, jd);
            //}

            jd = CalendarConverter.gregorian_to_jd2(1990, 10, 10);
            var dtx = CalendarConverter.jd_to_gregorian2((int)jd);

            Assert.AreEqual(1990, dtx.Year, "g2jd 1");
            Assert.AreEqual(10, dtx.Month, "g2jd 2");
            Assert.AreEqual(10, dtx.Day, "g2jd 3");
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Converts event to <c>string</c> representation.
        /// </summary>
        /// <param name="Event">Event to be converted to <c>string</c></param>
        /// <returns>Returns resulting <c>string</c>.</returns>
        public static string EventToString(IEvent Event)
        {
            StringBuilder builder = new StringBuilder(200);

            builder.Append("[Type=");
            builder.Append(Event.Type.ToString());

            if (Event.Description != null)
            {
                builder.Append("][Message=");
                builder.Append(Event.Description);
            }

            if (Event.Sender != null)
            {
                builder.Append("][ModelID=");
                builder.Append(((ILinkableComponent)Event.Sender).ModelID);
            }

            if (Event.SimulationTime != null)
            {
                builder.Append("][SimTime=");
                builder.Append(CalendarConverter.ModifiedJulian2Gregorian(Event.SimulationTime.ModifiedJulianDay).ToString());
            }

            builder.Append(']');

            return(builder.ToString());
        }
Ejemplo n.º 4
0
        private void AddCItem(double jd, int year, int month, int day,
                              string[] months, string[] weekdays, string ext, string cdrName)
        {
            string s = ext + d2s(day, months[month - 1], year, weekdays[CalendarConverter.jwday(jd)]);

            AddItem(cdrName, s);
        }
Ejemplo n.º 5
0
    public void ToCalendarEvent()
    {
        var start = DateTime.Parse("2000-01-13 12:00:00");
        var end   = DateTime.Parse("2000-01-13 13:00:00");

        var item = new Item
        {
            Id        = "id",
            Title     = "title",
            StaffName = "firstName lastName",
            Location  = new[] { "location" },
            Start     = start,
            End       = end,
            AllDay    = false
        };

        var converter = new CalendarConverter();

        var calendarEvent = converter.ConvertToCalendarEvent(item);

        Assert.Equal("id", calendarEvent.Uid);
        Assert.Equal("title (firstName)", calendarEvent.Summary);
        Assert.Equal("location", calendarEvent.Location);
        Assert.Equal(start, calendarEvent.DtStart.Value);
        Assert.Equal("Europe/Copenhagen", calendarEvent.DtStart.TimeZoneName);
        Assert.Equal(end, calendarEvent.DtEnd.Value);
        Assert.Equal("Europe/Copenhagen", calendarEvent.DtEnd.TimeZoneName);
    }
Ejemplo n.º 6
0
        public IValueSet GetValues(ITime time, string linkID)
        {
            // covert time to a DateTime data type
            TimeStamp timestamp = (TimeStamp)time;
            DateTime  dt        = CalendarConverter.ModifiedJulian2Gregorian(
                (double)timestamp.ModifiedJulianDay);

            // write datetime to log file
            StreamWriter sr = new StreamWriter("hydrolink_log.txt", true);

            sr.WriteLine("get values request for time: " + dt.ToLongDateString()
                         + " " + dt.ToLongTimeString());
            sr.Flush();

            //get scalar set
            IValueSet values = _buffervalues[linkID].GetValues(time);

            // write value set to log file
            ScalarSet ss = (ScalarSet)values;

            sr.Write("values set: ");
            sr.Flush();
            for (int i = 0; i < ss.Count; ++i)
            {
                sr.Write(" " + ss.GetScalar(i).ToString() + " ");
                sr.Flush();
            }
            sr.Write("\n");
            sr.Close();
            return(values);
        }
Ejemplo n.º 7
0
        public override bool PerformTimeStep()
        {
            //---- get input data
            //-- temp
            double[] temp = ((ScalarSet)this.GetValues(input_quantity[0], input_elementset[0])).data;
            //-- max temp
            double[] maxtemp = ((ScalarSet)this.GetValues(input_quantity[1], input_elementset[1])).data;
            //-- min temp
            double[] mintemp = ((ScalarSet)this.GetValues(input_quantity[2], input_elementset[2])).data;

            //---- calculate pet for each element
            //-- get the number of elements (assuming that they're all the same)
            int elemcount = this.GetInputExchangeItem(0).ElementSet.ElementCount;

            double[] pet = new double[elemcount];
            for (int i = 0; i <= elemcount - 1; i++)
            {
                pet[i] = CalculatePET(temp[i], mintemp[i], maxtemp[i], i);
            }

            //---- save output values
            DateTime dt = CalendarConverter.ModifiedJulian2Gregorian(((TimeStamp)this.GetCurrentTime()).ModifiedJulianDay);

            _output.Add(dt, pet);

            //---- set output values
            this.SetValues(output_quantity, output_elementset, new ScalarSet(pet));

            //---- advance to the next timestep
            this.AdvanceTime();

            return(true);
        }
Ejemplo n.º 8
0
        public void ExchangeItemsDefinedByConfig()
        {
            _engine = new LoadCalculator.LoadCalculatorLinkableEngine();

            ArrayList componentArguments = new ArrayList();

            componentArguments.Add(new Argument("ConfigFile", "./config.xml", true, "none"));
            _engine.Initialize((IArgument[])componentArguments.ToArray(typeof(IArgument)));
            int in_count  = _engine.InputExchangeItemCount;
            int out_count = _engine.OutputExchangeItemCount;

            for (int i = 0; i <= in_count - 1; i++)
            {
                InputExchangeItem ie = (InputExchangeItem)_engine.GetInputExchangeItem(i);
                Debug.Write("Testing Input Element Count..."); Assert.IsFalse(ie.ElementSet.ElementCount > 0); Debug.WriteLine("done.");
                Debug.Write("Testing Input Conv2SI..."); Assert.IsTrue(ie.Quantity.Unit.ConversionFactorToSI >= 0); Debug.WriteLine("done.");
                Debug.Write("Testing Input Offset2SI..."); Assert.IsTrue(ie.Quantity.Unit.OffSetToSI >= 0); Debug.WriteLine("done.");
            }

            for (int i = 0; i <= out_count - 1; i++)
            {
                OutputExchangeItem oe = (OutputExchangeItem)_engine.GetOutputExchangeItem(i);
                Debug.Write("Testing Output Element Count..."); Assert.IsTrue(oe.ElementSet.ElementCount > 0); Debug.WriteLine("done.");
                Debug.Write("Testing Output Conv2SI..."); Assert.IsTrue(oe.Quantity.Unit.ConversionFactorToSI >= 0); Debug.WriteLine("done.");
                Debug.Write("Testing Output Offset2SI..."); Assert.IsTrue(oe.Quantity.Unit.OffSetToSI >= 0); Debug.WriteLine("done.");
            }

            Assert.IsTrue(_engine.TimeHorizon.Start.ModifiedJulianDay == CalendarConverter.
                          Gregorian2ModifiedJulian(new DateTime(2009, 10, 27, 08, 30, 00)));

            _engine.Finish();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Calculates the potential evapotranspiration using the Hargreaves-Samani method
        /// </summary>
        /// <param name="T">Averaged daily temperature</param>
        /// <param name="Tmin">Minimum daily temperature</param>
        /// <param name="Tmax">Maximum daily temperature</param>
        /// <param name="e">element index</param>
        /// <returns>PET in mm/day</returns>
        public double CalculatePET(double T, double Tmin, double Tmax, int eid)
        {
            //calc Ra from http://www.civil.uwaterloo.ca/watflood/Manual/02_03_2.htm

            //---- calculate the relative distance between the earth and sun
            //-- get julien day
            TimeStamp ts = (TimeStamp)this.GetCurrentTime();
            DateTime  dt = CalendarConverter.ModifiedJulian2Gregorian(ts.ModifiedJulianDay);
            int       j  = dt.DayOfYear;
            double    dr = 1 + 0.033 * Math.Cos((2 * Math.PI * j) / 365);

            //---- calculate the solar declination
            double d = 0.4093 * Math.Sin((2 * Math.PI * j) / 365 - 1.405);

            //---- calculate the sunset hour angle
            //-- get latitude in degrees
            ElementSet es = (ElementSet)this.GetInputExchangeItem(0).ElementSet;
            Element    e  = es.GetElement(eid);
            double     p  = e.GetVertex(0).y *Math.PI / 180;
            //-- calc ws
            double ws = Math.Acos(-1 * Math.Tan(p) * Math.Tan(d));

            //---- calculate the total incoming extra terrestrial solar radiation (tested against http://www.engr.scu.edu/~emaurer/tools/calc_solar_cgi.pl)
            double Ra = 15.392 * dr * (ws * Math.Sin(p) * Math.Sin(d) + Math.Cos(p) * Math.Cos(d) * Math.Sin(ws));

            //---- calculate PET (From Hargreaves and Samani 1985)
            //-- calculate latent heat of vaporization (from Water Resources Engineering, David A. Chin)
            double L   = 2.501 - 0.002361 * T;
            double PET = (0.0023 * Ra * Math.Sqrt(Tmax - Tmin) * (T + 17.8)) / L;

            return(PET);
        }
Ejemplo n.º 10
0
        int nt = 1;// number of earliest outputs need to be saved

        public override void Finish()
        {
            if (!System.IO.Directory.Exists(outputPath))
            {
                System.IO.Directory.CreateDirectory(outputPath);
            }

            //System.IO.Directory.CreateDirectory("wateroutput");
            StreamWriter swa = new StreamWriter(outputPath + "/waterAdvection.csv");

            swa.WriteLine("This is some info about the model....");
            DateTime start = CalendarConverter.ModifiedJulian2Gregorian(((TimeStamp)this.GetTimeHorizon().Start).ModifiedJulianDay);
            DateTime end   = CalendarConverter.ModifiedJulian2Gregorian(((TimeStamp)this.GetTimeHorizon().End).ModifiedJulianDay);

            swa.WriteLine("StartDate: , " + String.Format("{0:d/M/yyyy HH:mm:ss}", start));
            swa.WriteLine("EndDate: , " + String.Format("{0:d/M/yyyy HH:mm:ss}", end));
            swa.WriteLine();
            swa.WriteLine("Time [H:mm:ss], Concentration");
            foreach (KeyValuePair <DateTime, double[, ]> kvp in outputValues)
            {
                string time = String.Format("{0:HH:mm:ss}", kvp.Key);
                swa.Write(time + ",");
                //StreamWriter sw = new StreamWriter("wateroutput/" + time + ".csv");
                for (int i = 0; i < kvp.Value.GetLength(0); i++)
                {
                    for (int j = 0; j < kvp.Value.GetLength(1); j++)
                    {
                        swa.Write(kvp.Value[i, j].ToString() + ",");
                    }
                    swa.Write("\n");
                }
            }
            swa.Close();
        }
        /// <summary>
        /// Reads the Configuration file, and creates OpenMI exchange items
        /// </summary>
        /// <param name="configFile">path pointing to the components comfiguration (XML) file</param>
        public void SetVariablesFromConfigFile(string configFile)
        {
            //Read config file
            XmlDocument doc = new XmlDocument();

            doc.Load(configFile);
            XmlElement  root = doc.DocumentElement;
            XmlNodeList outputExchangeItems = root.SelectNodes("//OutputExchangeItem");

            foreach (XmlNode outputExchangeItem in outputExchangeItems)
            {
                OutputExchangeItem o = (OutputExchangeItem)CreateExchangeItemsFromXMLNode(outputExchangeItem, "OutputExchangeItem");
                _outputExchangeItems.Add(o);
                string Key = o.ElementSet.ID + ":" + o.Quantity.ID;
                System.Collections.Hashtable hashtable = new Hashtable();
                hashtable.Add("OutputExchangeItem", Key);

                //pass this info to the IRunEngine, via Intitialize
                _engineApiAccess.Initialize(hashtable);
            }

            XmlNodeList inputExchangeItems = root.SelectNodes("//InputExchangeItem");

            foreach (XmlNode inputExchangeItem in inputExchangeItems)
            {
                InputExchangeItem i = (InputExchangeItem)CreateExchangeItemsFromXMLNode(inputExchangeItem, "InputExchangeItem");
                _inputExchangeItems.Add(i);
            }

            XmlNode timeHorizon = root.SelectSingleNode("//TimeHorizon");

            this.start = CalendarConverter.Gregorian2ModifiedJulian(Convert.ToDateTime(timeHorizon["StartDateTime"].InnerText));
        }
Ejemplo n.º 12
0
        public void TimeHorizon()
        {
            DateTime startDate = new DateTime(1990, 1, 2, 0, 0, 0);
            DateTime endDate   = new DateTime(1990, 2, 1, 0, 0, 0);

            Assert.AreEqual(startDate, CalendarConverter.ModifiedJulian2Gregorian(gwModelLC.TimeHorizon.Start.ModifiedJulianDay));
            Assert.AreEqual(endDate, CalendarConverter.ModifiedJulian2Gregorian(gwModelLC.TimeHorizon.End.ModifiedJulianDay));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// This method is called in <see cref="Run">Run</see> method.
        /// </summary>
        private void RunThreadFunction()
        {
            Trigger trigger = GetTrigger();

            Debug.Assert(trigger != null);

            Thread.Sleep(0);

            try
            {
                // run it !!!
                trigger.Run(new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(TriggerInvokeTime)));

                // close models down
                if (_runListener != null)
                {
                    Event theEvent = new Event(EventType.Informative);
                    theEvent.Description = "Closing models down...";
                    _runListener.OnEvent(theEvent);
                }

                foreach (UIModel uimodel in _models)
                {
                    if (_runListener != null)
                    {
                        string ModelID  = uimodel.ModelID;
                        Event  theEvent = new Event(EventType.Informative);
                        theEvent.Description = "Calling Finish() on model " + ModelID;
                        _runListener.OnEvent(theEvent);
                    }
                    uimodel.LinkableComponent.Finish();
                }

                // thread finishes - send well known event
                if (_runListener != null)
                {
                    _simulationFinishedEvent.Description = "Simulation finished successfuly at " + DateTime.Now.ToString() + "...";
                    _runListener.OnEvent(SimulationFinishedEvent);
                }
            }
            catch (Exception e)
            {
                if (_runListener != null)
                {
                    Event theEvent = new Event(EventType.Informative);
                    theEvent.Description = "Exception occured during simulation: " + e.ToString();
                    _runListener.OnEvent(theEvent);

                    _simulationFailedEvent.Description = "Simulation FAILED at " + DateTime.Now.ToString() + "...";
                    _runListener.OnEvent(SimulationFailedEvent);
                }
            }
            finally
            {
                _running     = false;
                _runListener = null; // release listener
            }
        }
Ejemplo n.º 14
0
        [TestMethod] public void TrickyDates()
        {
            double   julianDate = 46096.999999998196;
            DateTime gregorian  = CalendarConverter.ModifiedJulian2Gregorian(julianDate);

            Assert.AreEqual(1985, gregorian.Year, "Year expected");
            Assert.AreEqual(2, gregorian.Month, "Month expected");
            Assert.AreEqual(1, gregorian.Day, "Day expected");
        }
Ejemplo n.º 15
0
        public void ConverterCreatesWorkingCalendar()
        {
            var converter = new CalendarConverter();

            var output = converter.Convert(TestSchedules.CreateScheduleDetails(), null);

            Assert.True(output.IsActiveOn(new DateTime(2019, 8, 1)));
            Assert.False(output.IsActiveOn(new DateTime(2019, 8, 3)));
        }
Ejemplo n.º 16
0
        public void ConverterReusesExistingCalendar()
        {
            var converter = new CalendarConverter();

            var output1 = converter.Convert(TestSchedules.CreateScheduleDetails(), null);
            var output2 = converter.Convert(TestSchedules.CreateScheduleDetails(), null);

            Assert.Same(output1, output2);
        }
Ejemplo n.º 17
0
        public override void Initialize(IArgument[] properties)
        {
            double start = CalendarConverter.Gregorian2ModifiedJulian(new DateTime(2004, 12, 31, 0, 0, 0));

            for (int i = 0; i < 30; i++)
            {
                buffer.AddValues(new HydroNumerics.OpenMI.Sdk.Backbone.TimeSpan(new TimeStamp(start + i), new TimeStamp(start + i + 1)), new ScalarSet(new double[] { (double)i }));
            }
        }
Ejemplo n.º 18
0
        private void Evaluate(DateTime inGregDate)
        {
            double modJulDate = CalendarConverter.Gregorian2ModifiedJulian(inGregDate);
            long   mjdInt     = (long)modJulDate;

            DateTime outGregDate = CalendarConverter.ModifiedJulian2Gregorian(modJulDate);

            Assert.AreEqual(inGregDate.ToString(), outGregDate.ToString(), modJulDate.ToString());
        }
Ejemplo n.º 19
0
        public void RunSimulationWithInputAndOutput()
        {
            ITimeSpan modelSpan = mohidWaterEngineWrapper.GetTimeHorizon();
            double    now       = modelSpan.Start.ModifiedJulianDay;

            Stopwatch win     = new Stopwatch();
            Stopwatch wout    = new Stopwatch();
            Stopwatch wengine = new Stopwatch();

            while (now < modelSpan.End.ModifiedJulianDay)
            {
                DateTime currentTime = CalendarConverter.ModifiedJulian2Gregorian(now);
                DateTime intitalTime =
                    CalendarConverter.ModifiedJulian2Gregorian(
                        mohidWaterEngineWrapper.GetTimeHorizon().Start.ModifiedJulianDay);

                Console.WriteLine(currentTime.ToString());

                wengine.Start();
                mohidWaterEngineWrapper.PerformTimeStep();
                wengine.Stop();

                wout.Start();
                //Gets outputs Items
                for (int i = 0; i < mohidWaterEngineWrapper.GetOutputExchangeItemCount(); i++)
                {
                    OutputExchangeItem ouputItem = mohidWaterEngineWrapper.GetOutputExchangeItem(i);

                    IValueSet values = mohidWaterEngineWrapper.GetValues(ouputItem.Quantity.ID, ouputItem.ElementSet.ID);
                }
                wout.Stop();

                //Sets Input Items
                win.Start();
                for (int i = 0; i < mohidWaterEngineWrapper.GetInputExchangeItemCount(); i++)
                {
                    InputExchangeItem inputItem = mohidWaterEngineWrapper.GetInputExchangeItem(i);

                    double[] aux = new double[inputItem.ElementSet.ElementCount];
                    for (int j = 0; j < inputItem.ElementSet.ElementCount; j++)
                    {
                        aux[j] = 0;
                    }
                    IValueSet values = new ScalarSet(aux);

                    //mohidLandEngineWrapper.SetValues(inputItem.Quantity.ID, inputItem.ElementSet.ID, values);
                }
                win.Stop();

                now = mohidWaterEngineWrapper.GetEarliestNeededTime().ModifiedJulianDay;
            }

            Console.WriteLine("Input Exchange:  " + win.ElapsedMilliseconds.ToString());
            Console.WriteLine("Output Exchange: " + wout.ElapsedMilliseconds.ToString());
            Console.WriteLine("Engine:          " + wengine.ElapsedMilliseconds.ToString());
        }
Ejemplo n.º 20
0
        public void AccessTimes()
        {
            DateTime start = new DateTime(2002, 1, 1, 0, 0, 0);
            DateTime end   = new DateTime(2002, 1, 1, 12, 0, 0);

            ITimeSpan timeHorizon = mohidWaterEngineWrapper.GetTimeHorizon();

            Assert.AreEqual(CalendarConverter.ModifiedJulian2Gregorian(timeHorizon.Start.ModifiedJulianDay), start);
            Assert.AreEqual(CalendarConverter.ModifiedJulian2Gregorian(timeHorizon.End.ModifiedJulianDay), end);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// This method performs specified actions upon the closure of the model
        /// </summary>
        public override void Finish()
        {
            //intialize streamwriter to write output data.
            if (_outDir != null)
            {
                try
                { sw = new System.IO.StreamWriter(_outDir + "/MuskingumRouting_output.csv"); }
                catch (SystemException e)
                {
                    throw new Exception("The Muskingum Component was unable to create the desired output file. " +
                                        "This is possibly due to an invalid \'OutDir\' field supplied in " +
                                        "the *.omi file", e);
                }
            }
            else
            {
                try { sw = new System.IO.StreamWriter("../MuskingumRouting_output.csv"); }
                catch (SystemException e)
                {
                    throw new Exception(" The Muskingum component failed in writing it output file to path " +
                                        System.IO.Directory.GetCurrentDirectory() + ". This may be due to " +
                                        "lack of user permissions.", e);
                }
            }



            // current time
            TimeStamp time     = (TimeStamp)this.GetCurrentTime();
            DateTime  current  = CalendarConverter.ModifiedJulian2Gregorian(time.ModifiedJulianDay);
            Double    step_sec = this.GetTimeStep();

            //get the last time
            current = current.AddSeconds(-1 * step_sec);

            sw.Write("Date,");
            for (int i = 1; i <= _output[current].Length; i++)
            {
                sw.Write("Element " + i.ToString() + ",");
            }
            sw.Write("\n");


            foreach (KeyValuePair <DateTime, double[]> kvp in _output)
            {
                sw.Write(kvp.Key.ToShortDateString() + " " + kvp.Key.ToLongTimeString() + ",");
                for (int j = 0; j < kvp.Value.Length; j++)
                {
                    sw.Write(kvp.Value[j].ToString() + ",");
                }
                sw.Write("\n");
            }
            sw.Close();
        }
        private int _timeIncrement = 300; //in seconds (should be specifiec by the user)

        public LoadCalculatorLinkableEngine()
        {
            _links = new Dictionary <string, ILink>();
            _inputExchangeItems            = new List <IInputExchangeItem>();
            _inputExchangeItemsTransformed = new List <IInputExchangeItem>();
            _outputExchangeItems           = new List <IOutputExchangeItem>();
            start = -999;
            end   = CalendarConverter.Gregorian2ModifiedJulian(new DateTime(2011, 01, 01, 00, 00, 00));
            _earliestInputTime = end;
            _currentTime       = -999;
            _timeIncrement     = 20;
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates a new instance of <see cref="Trigger">Trigger</see> class.
        /// </summary>
        public Trigger()
        {
            _link = null;
            _inputExchangeItem = new TriggerExchangeItem();

            HydroNumerics.OpenMI.Sdk.Backbone.TimeStamp
                start = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(new DateTime(1800, 1, 1))),
                end   = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(new DateTime(2200, 1, 1)));
            _timeHorizon = new HydroNumerics.OpenMI.Sdk.Backbone.TimeSpan(start, end);

            _earliestInputTime = end;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// This method is being used to write the calculated values to file, for use outside of the OpenMI environment.
        /// </summary>
        public override void Finish()
        {
            //intialize streamwriter to write output data.
            if (_outDir != null)
            {
                try
                { sw = new System.IO.StreamWriter(_outDir + "/SCSUnitHydrograph_output.csv"); }
                catch (SystemException e)
                {
                    throw new Exception("The UH Component was unable to create the desired output file. " +
                                        "This is possibly due to an invalid \'OutDir\' field supplied in " +
                                        "the *.omi file", e);
                }
            }
            else
            {
                try { sw = new System.IO.StreamWriter("../SCSUnitHydrograph_output.csv"); }
                catch (SystemException e)
                {
                    throw new Exception(" The UH component failed in writing it output file to path " +
                                        System.IO.Directory.GetCurrentDirectory() + ". This may be due to " +
                                        "lack of user permissions.", e);
                }
            }


            //Write output data

            sw.Write("Date, Time, ");

            OpenMI.Standard.ITimeSpan ts = this.GetTimeHorizon();
            TimeStamp t  = (TimeStamp)ts.Start;
            DateTime  dt = CalendarConverter.ModifiedJulian2Gregorian((double)t.ModifiedJulianDay);

            for (int i = 0; i <= output[dt].Count - 1; i++)
            {
                sw.Write("element " + (i + 1).ToString() + ",");
            }
            sw.Write("\n");

            foreach (System.Collections.Generic.KeyValuePair <DateTime, ArrayList> kvp in output)
            {
                sw.Write(String.Format("{0:MM/dd/yyyy}", kvp.Key) + ", " +
                         String.Format("{0:hh:mm tt}", kvp.Key) + ",");
                for (int i = 0; i <= kvp.Value.Count - 1; i++)
                {
                    sw.Write(kvp.Value[i].ToString() + ",");
                }
                sw.Write("\n");
            }

            sw.Close();
        }
Ejemplo n.º 25
0
        public override bool PerformTimeStep()
        {
            //Defie current time step and the row of water component
            TimeStamp SedTime = (TimeStamp)this.GetCurrentTime();
            ScalarSet aa      = (ScalarSet)this.GetValues("Concentration", "water");

            //set adv_prev to the imported values
            for (int i = 0; i <= cw.GetLength(1) - 1; i++)
            {
                adv_prev[0, i] = aa.data[i];
            }
            // specifies if the values should be saved.
            bool      SaveValues = true;
            TimeStamp t          = (TimeStamp)this.GetCurrentTime();
            DateTime  time       = CalendarConverter.ModifiedJulian2Gregorian(t.ModifiedJulianDay);

            // calculate concentration in sediment using diffusion mechanism from water
            cs = Calculate_concentration();

            //setup the value of diff_prev= upper row of cs since cs contain 9 rows
            for (int i = 0; i <= cs.GetLength(1) - 1; i++)
            {
                diff_prev[i] = cs[cs.GetUpperBound(0), i];
            }


            //save results for output during Finish()
            double[,] z = new double[rows_S, cols_S];
            if (SaveValues)
            {
                for (int i = 0; i <= cs.GetLength(0) - 1; i++)
                {
                    for (int j = 0; j <= cs.GetLength(1) - 1; j++)
                    {
                        z[i, j] = cs[i, j];
                    }
                }

                //save results for output during Finish()
                outputValues.Add(time, z);
                outv.Add(z);
            }
            //setting boundary conditions so that they are available to water component.
            double[] outvals = new double[cs.GetLength(1)];
            for (int i = 0; i <= cs.GetLength(1) - 1; i++)
            {
                outvals[i] = cs[8, i];
            }
            this.SetValues("Concentration", "sed", new ScalarSet(outvals));
            this.AdvanceTime();

            return(true);
        }
Ejemplo n.º 26
0
        public ITimeSpan GetTimeHorizon()
        {
            DateTime modelStart = MohidWaterEngine.GetStartInstant();
            DateTime modelEnd   = MohidWaterEngine.GetStopInstant();

            double start = CalendarConverter.Gregorian2ModifiedJulian(modelStart);
            double end   = CalendarConverter.Gregorian2ModifiedJulian(modelEnd);

            ITimeStamp tStart = new Oatc.OpenMI.Sdk.Backbone.TimeStamp(start);
            ITimeStamp tEnd   = new TimeStamp(end);

            return(new Oatc.OpenMI.Sdk.Backbone.TimeSpan(tStart, tEnd));
        }
Ejemplo n.º 27
0
        private void AddCItem(double jd, int year, int month, int day,
                              string[] months, string[] weekdays, string ext, string calendar)
        {
            // jwday (sunday == 0)
            int jwday = CalendarConverter.jwday(jd);
            // all arrays in range [monday..sunday]
            int    weekDay = (jwday > 0) ? jwday - 1 : 6;
            string strDate = ext + string.Format("{0} {1} {2}, {3}", day, months[month - 1], year, weekdays[weekDay]);

            ListViewItem item = lvDates.Items.Add(calendar);

            item.SubItems.Add(strDate);
        }
Ejemplo n.º 28
0
        public void GetValues()
        {
            Console.Write("Begin Get Values Test...");
            //create the his component
            DbReader his = new DbReader();

            IArgument[] arguments = new IArgument[2];
            arguments[0] = new Argument("DbPath", @"..\data\cuahsi-his\demo.db", true, "Database");
            arguments[1] = new Argument("Relaxation", "1", true, "Time interpolation factor, btwn 0(linear inter.) and 1(nearest neigbor)");
            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(0).ElementSet;
            link.SourceQuantity   = his.GetOutputExchangeItem(0).Quantity;
            link.TargetComponent  = his;

            //run configuration
            his.AddLink(link);

            //prepare
            his.Prepare();

            DateTime dt = Convert.ToDateTime("2009-08-20");

            while (dt <= Convert.ToDateTime("2009-09-20"))
            {
                ITimeStamp time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(dt));
                Application.DoEvents();
                ScalarSet scalarset = (ScalarSet)his.GetValues(time_stmp, "link-1");
                Console.WriteLine("GetValues: " + dt.ToString("s"));
                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.º 29
0
        public void GetTimeHorizon()
        {
            Console.WriteLine("Begin Get Time Horizon 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);

            //get earliest and latest times
            Console.WriteLine("start: " + CalendarConverter.ModifiedJulian2Gregorian(his.TimeHorizon.Start.ModifiedJulianDay).ToString());
            Console.WriteLine("end: " + CalendarConverter.ModifiedJulian2Gregorian(his.TimeHorizon.End.ModifiedJulianDay).ToString());
        }
        public LoadCalculatorEngine(int timeIncrement, string modelID)
        {
            _inputExchangeItems  = new Dictionary <string, List <string> >();
            _outputExchangeItems = new Dictionary <string, List <string> >();
            _values = new Dictionary <string, ScalarSet>();
            _links  = new Dictionary <string, Link>();

            start = CalendarConverter.Gregorian2ModifiedJulian(new DateTime(1900, 01, 01, 00, 00, 00));
            end   = CalendarConverter.Gregorian2ModifiedJulian(new DateTime(2011, 01, 01, 00, 00, 00));
            _earliestInputTime  = end;
            _currentTime        = -999;
            this._timeIncrement = timeIncrement;
            this._modelID       = modelID;
        }