Пример #1
0
        public static void ShiftEvents(this IEnumerable <TrackChunk> trackChunks, ITimeSpan distance, TimeDivision timeDivision)
        {
            ThrowIfArgument.IsNull(nameof(trackChunks), trackChunks);
            ThrowIfArgument.IsNull(nameof(distance), distance);
            ThrowIfArgument.IsNull(nameof(timeDivision), timeDivision);

            foreach (var trackChunk in trackChunks)
            {
                trackChunk.ShiftEvents(distance, timeDivision);
            }
        }
Пример #2
0
        /// <summary>
        /// Adds a time span to the current one.
        /// </summary>
        /// <remarks>
        /// If <paramref name="timeSpan"/> and the current time span have the same type,
        /// the result time span will be of this type too; otherwise - of the <see cref="MathTimeSpan"/>.
        /// </remarks>
        /// <param name="timeSpan">Time span to add to the current one.</param>
        /// <param name="mode">Mode of the operation that defines meaning of time spans the
        /// operation will be performed on.</param>
        /// <returns>Time span that is a sum of the <paramref name="timeSpan"/> and the
        /// current time span.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="timeSpan"/> is invalid.</exception>
        /// <exception cref="InvalidEnumArgumentException"><paramref name="mode"/> specified an invalid value.</exception>
        public ITimeSpan Add(ITimeSpan timeSpan, TimeSpanMode mode)
        {
            ThrowIfArgument.IsNull(nameof(timeSpan), timeSpan);
            ThrowIfArgument.IsInvalidEnumValue(nameof(mode), mode);

            var metricTimeSpan = timeSpan as MetricTimeSpan;

            return(metricTimeSpan != null
                ? this + metricTimeSpan
                : TimeSpanUtilities.Add(this, timeSpan, mode));
        }
Пример #3
0
        /// <summary>
        /// Splits chords contained in the specified <see cref="MidiFile"/> at the specified distance
        /// from a chord's start or end.
        /// </summary>
        /// <param name="midiFile"><see cref="MidiFile"/> to split chords in.</param>
        /// <param name="distance">Distance to split chords at.</param>
        /// <param name="from">Point of a chord <paramref name="distance"/> should be measured from.</param>
        /// <param name="notesTolerance">Notes tolerance that defines maximum distance of notes from the
        /// start of the first note of a chord. Notes within this tolerance will be considered as a chord.</param>
        /// <exception cref="ArgumentNullException">
        /// <para>One of the following errors occured:</para>
        /// <list type="bullet">
        /// <item>
        /// <description><paramref name="midiFile"/> is <c>null</c>.</description>
        /// </item>
        /// <item>
        /// <description><paramref name="distance"/> is <c>null</c>.</description>
        /// </item>
        /// </list>
        /// </exception>
        /// <exception cref="InvalidEnumArgumentException"><paramref name="from"/> specified an invalid value.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="notesTolerance"/> is negative.</exception>
        public static void SplitChordsAtDistance(this MidiFile midiFile, ITimeSpan distance, LengthedObjectTarget from, long notesTolerance = 0)
        {
            ThrowIfArgument.IsNull(nameof(midiFile), midiFile);
            ThrowIfArgument.IsNull(nameof(distance), distance);
            ThrowIfArgument.IsInvalidEnumValue(nameof(from), from);
            ThrowIfNotesTolerance.IsNegative(nameof(notesTolerance), notesTolerance);

            var tempoMap = midiFile.GetTempoMap();

            midiFile.GetTrackChunks().SplitChordsAtDistance(distance, from, tempoMap, notesTolerance);
        }
Пример #4
0
        /// <summary>
        /// Adds a time span to the current one.
        /// </summary>
        /// <remarks>
        /// If <paramref name="timeSpan"/> and the current time span have the same type,
        /// the result time span will be of this type too; otherwise - of the <see cref="MathTimeSpan"/>.
        /// </remarks>
        /// <param name="timeSpan">Time span to add to the current one.</param>
        /// <param name="mode">Mode of the operation that defines meaning of time spans the
        /// operation will be performed on.</param>
        /// <returns>Time span that is a sum of the <paramref name="timeSpan"/> and the
        /// current time span.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="timeSpan"/> is invalid.</exception>
        /// <exception cref="InvalidEnumArgumentException"><paramref name="mode"/> specified an invalid value.</exception>
        public ITimeSpan Add(ITimeSpan timeSpan, TimeSpanMode mode)
        {
            ThrowIfArgument.IsNull(nameof(timeSpan), timeSpan);
            ThrowIfArgument.IsInvalidEnumValue(nameof(mode), mode);

            var barBeatFractionTimeSpan = timeSpan as BarBeatFractionTimeSpan;

            return(barBeatFractionTimeSpan != null
                ? this + barBeatFractionTimeSpan
                : TimeSpanUtilities.Add(this, timeSpan, mode));
        }
Пример #5
0
        internal static ITimeSpan Add(ITimeSpan timeSpan1, ITimeSpan timeSpan2, TimeSpanMode mode)
        {
            ThrowIfArgument.IsInvalidEnumValue(nameof(mode), mode);

            if (mode == TimeSpanMode.TimeTime)
            {
                throw new ArgumentException("Times cannot be added.", nameof(mode));
            }

            return(new MathTimeSpan(timeSpan1, timeSpan2, MathOperation.Add, mode));
        }
        /// <summary>
        /// Sets time and length of the specified note.
        /// </summary>
        /// <param name="note">Note to set time and length to.</param>
        /// <param name="time">Time to set to <paramref name="note"/>.</param>
        /// <param name="length">Length to set to <paramref name="note"/>.</param>
        /// <param name="tempoMap">Tempo map that will be used for time and length conversion.</param>
        /// <returns>An input <paramref name="note"/> with new time and length.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="note"/> is null. -or-
        /// <paramref name="time"/> is null. -or- <paramref name="length"/> is null. -or-
        /// <paramref name="tempoMap"/> is null.</exception>
        public static Note SetTimeAndLength(this Note note, ITimeSpan time, ITimeSpan length, TempoMap tempoMap)
        {
            ThrowIfArgument.IsNull(nameof(note), note);
            ThrowIfArgument.IsNull(nameof(time), time);
            ThrowIfArgument.IsNull(nameof(length), length);
            ThrowIfArgument.IsNull(nameof(tempoMap), tempoMap);

            note.Time   = TimeConverter.ConvertFrom(time, tempoMap);
            note.Length = LengthConverter.ConvertFrom(length, note.Time, tempoMap);
            return(note);
        }
        /// <summary>
        /// Sets time and length of the specified chord.
        /// </summary>
        /// <param name="chord">Chord to set time and length to.</param>
        /// <param name="time">Time to set to <paramref name="chord"/>.</param>
        /// <param name="length">Length to set to <paramref name="chord"/>.</param>
        /// <param name="tempoMap">Tempo map that will be used for time and length conversion.</param>
        /// <returns>An input <paramref name="chord"/> with new time and length.</returns>
        /// <exception cref="ArgumentNullException">
        /// <para>One of the following errors occured:</para>
        /// <list type="bullet">
        /// <item>
        /// <description><paramref name="chord"/> is <c>null</c>.</description>
        /// </item>
        /// <item>
        /// <description><paramref name="time"/> is <c>null</c>.</description>
        /// </item>
        /// <item>
        /// <description><paramref name="length"/> is <c>null</c>.</description>
        /// </item>
        /// <item>
        /// <description><paramref name="tempoMap"/> is <c>null</c>.</description>
        /// </item>
        /// </list>
        /// </exception>
        public static Chord SetTimeAndLength(this Chord chord, ITimeSpan time, ITimeSpan length, TempoMap tempoMap)
        {
            ThrowIfArgument.IsNull(nameof(chord), chord);
            ThrowIfArgument.IsNull(nameof(time), time);
            ThrowIfArgument.IsNull(nameof(length), length);
            ThrowIfArgument.IsNull(nameof(tempoMap), tempoMap);

            chord.Time   = TimeConverter.ConvertFrom(time, tempoMap);
            chord.Length = LengthConverter.ConvertFrom(length, chord.Time, tempoMap);
            return(chord);
        }
Пример #8
0
        /// <summary>
        /// Shifts playback position back by the specified step.
        /// </summary>
        /// <param name="step">Amount of time to shift playback position by.</param>
        /// <exception cref="ArgumentNullException"><paramref name="step"/> is null.</exception>
        /// <exception cref="ObjectDisposedException">The current <see cref="Playback"/> is disposed.</exception>
        /// <exception cref="MidiDeviceException">An error occurred on device.</exception>
        public void MoveBack(ITimeSpan step)
        {
            ThrowIfArgument.IsNull(nameof(step), step);
            EnsureIsNotDisposed();

            var currentTime = (MetricTimeSpan)_clock.CurrentTime;

            MoveToTime(TimeConverter.ConvertTo <MetricTimeSpan>(step, TempoMap) > currentTime
                ? new MetricTimeSpan()
                : currentTime.Subtract(step, TimeSpanMode.TimeLength));
        }
Пример #9
0
        /// <summary>
        /// Subtracts a time span from the current one.
        /// </summary>
        /// <remarks>
        /// If <paramref name="timeSpan"/> and the current time span have the same type,
        /// the result time span will be of this type too; otherwise - of the <see cref="MathTimeSpan"/>.
        /// </remarks>
        /// <param name="timeSpan">Time span to subtract from the current one.</param>
        /// <param name="mode">Mode of the operation that defines meaning of time spans the
        /// operation will be performed on.</param>
        /// <returns>Time span that is a difference between the <paramref name="timeSpan"/> and the
        /// current time span.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="timeSpan"/> is invalid.</exception>
        /// <exception cref="InvalidEnumArgumentException"><paramref name="mode"/> specified an invalid value.</exception>
        public ITimeSpan Subtract(ITimeSpan timeSpan, TimeSpanMode mode)
        {
            ThrowIfArgument.IsNull(nameof(timeSpan), timeSpan);
            ThrowIfArgument.IsInvalidEnumValue(nameof(mode), mode);

            var barBeatTicksTimeSpan = timeSpan as BarBeatTicksTimeSpan;

            return(barBeatTicksTimeSpan != null
                ? this - barBeatTicksTimeSpan
                : TimeSpanUtilities.Subtract(this, timeSpan, mode));
        }
Пример #10
0
        public static void Subtract_LengthLength(ITimeSpan timeSpan1, ITimeSpan timeSpan2, TempoMap tempoMap, long time)
        {
            var mathTimeSpan = CheckMathTimeSpan(timeSpan1, timeSpan2, MathOperation.Subtract, TimeSpanMode.LengthLength);

            AreEqual(timeSpan1,
                     LengthConverter.ConvertTo(mathTimeSpan.Add(timeSpan2, TimeSpanMode.LengthLength),
                                               timeSpan1.GetType(),
                                               time,
                                               tempoMap),
                     $"({timeSpan1} - {timeSpan2}) + {timeSpan2} != {timeSpan1}.");
        }
Пример #11
0
 internal QuantizedTime(long newTime,
                        long gridTime,
                        ITimeSpan shift,
                        long distanceToGridTime,
                        ITimeSpan convertedDistanceToGridTime)
 {
     NewTime                     = newTime;
     GridTime                    = gridTime;
     Shift                       = shift;
     DistanceToGridTime          = distanceToGridTime;
     ConvertedDistanceToGridTime = convertedDistanceToGridTime;
 }
Пример #12
0
        /// <summary>
        /// Score for overlapping of two subtitles between 0 and 1.
        ///
        /// Corner cases:
        ///     subtitles do not overlap -> 0
        ///     subtitles fully overlap -> 1
        /// </summary>
        /// <returns>The score.</returns>
        /// <param name="a">The alpha component.</param>
        /// <param name="b">The blue component.</param>
        public static double OverlappingScore(ITimeSpan a, ITimeSpan b)
        {
            double overlappingSpan = UtilsCommon.OverlappingTimeSpan(a, b);
            double line1timeSpan   = a.EndTime - a.StartTime;
            double line2timeSpan   = b.EndTime - b.StartTime;

            // ignore matchings if there is next to no overlapping
            double line1score = (double)overlappingSpan / (double)line1timeSpan;
            double line2score = (double)overlappingSpan / (double)line2timeSpan;

            return((line1score + line2score) * 0.5f);
        }
Пример #13
0
        private void SetStartTime(ITimeSpan time)
        {
            var convertedTime = (TimeSpan)TimeConverter.ConvertTo <MetricTimeSpan>(time, TempoMap);

            _clock.SetCurrentTime(convertedTime);

            _eventsEnumerator.Reset();
            do
            {
                _eventsEnumerator.MoveNext();
            }while (_eventsEnumerator.Current != null && _eventsEnumerator.Current.Time < convertedTime);
        }
Пример #14
0
        public long ConvertFrom(ITimeSpan timeSpan, long time, TempoMap tempoMap)
        {
            var ticksPerQuarterNoteTimeDivision = tempoMap.TimeDivision as TicksPerQuarterNoteTimeDivision;

            if (ticksPerQuarterNoteTimeDivision == null)
            {
                throw new ArgumentException("Time division is not supported for time span conversion.", nameof(tempoMap));
            }

            var musicalTimeSpan = (MusicalTimeSpan)timeSpan;

            return(4 * musicalTimeSpan.Numerator * ticksPerQuarterNoteTimeDivision.TicksPerQuarterNote / musicalTimeSpan.Denominator);
        }
        public PrefetchMonitor(ArrayList outputLinks, TraceFile traceFile, ITimeSpan timeHorizon)
        {
            this.traceFile = traceFile;
            this.timeHorizon = timeHorizon;
            items = new Dictionary<string, LinkQuantityInfo>();

            foreach (DataOutputLink link in outputLinks)
            {
                var linkId = getLinkId(link.link);
                var linkInfo = new LinkQuantityInfo(linkId);
                items[linkId] = linkInfo;
            }
        }
Пример #16
0
        private static TimedMidiEvent[] ParseNote(Record record, MidiFileCsvConversionSettings settings)
        {
            if (record.TrackNumber == null)
            {
                CsvError.ThrowBadFormat(record.LineNumber, "Invalid track number.");
            }

            if (record.Time == null)
            {
                CsvError.ThrowBadFormat(record.LineNumber, "Invalid time.");
            }

            var parameters = record.Parameters;

            if (parameters.Length < 5)
            {
                CsvError.ThrowBadFormat(record.LineNumber, "Invalid number of parameters provided.");
            }

            var i = -1;

            try
            {
                var channel    = (FourBitNumber)TypeParser.FourBitNumber(parameters[++i], settings);
                var noteNumber = (SevenBitNumber)TypeParser.NoteNumber(parameters[++i], settings);

                ITimeSpan length = null;
                TimeSpanUtilities.TryParse(parameters[++i], settings.NoteLengthType, out length);

                var velocity    = (SevenBitNumber)TypeParser.SevenBitNumber(parameters[++i], settings);
                var offVelocity = (SevenBitNumber)TypeParser.SevenBitNumber(parameters[++i], settings);

                return(new[]
                {
                    new TimedMidiEvent(record.Time, new NoteOnEvent(noteNumber, velocity)
                    {
                        Channel = channel
                    }),
                    new TimedMidiEvent(record.Time.Add(length, TimeSpanMode.TimeLength), new NoteOffEvent(noteNumber, offVelocity)
                    {
                        Channel = channel
                    }),
                });
            }
            catch
            {
                CsvError.ThrowBadFormat(record.LineNumber, $"Parameter ({i}) is invalid.");
            }

            return(null);
        }
        public PrefetchManager(TraceFile traceFile, Statistics statistics, HazelcastClient hazelcastClient, string scenarioId, ArrayList outputLinks, ITimeSpan timeHorizon, bool isEnabled, WebServiceManager webServiceManager)
        {
            this.traceFile = traceFile;
            this.statistics = statistics;
            this.hazelcastClient = hazelcastClient;
            this.scenarioId = scenarioId;
            this.isEnabled = isEnabled;
            this.webServiceManager = webServiceManager;

            mapValueSet = hazelcastClient.getMap<string, ValueSetEntry>("valueSet");
            queueValueSetRequest = hazelcastClient.getQueue<ValueSetRequestEntry>("valueSetRequest");

            prefetchMonitor = new PrefetchMonitor(outputLinks, traceFile, timeHorizon);
        }
        private static bool TryParse(string input, Parser parser, out ITimeSpan timeSpan)
        {
            timeSpan = null;

            var parsingResult = parser(input);

            if (parsingResult.Item1.Status == ParsingStatus.Parsed)
            {
                timeSpan = parsingResult.Item2;
                return(true);
            }

            return(false);
        }
Пример #19
0
        public void MoveToTime(ITimeSpan time)
        {
            ThrowIfArgument.IsNull(nameof(time), time);

            var needStart = IsRunning;

            Stop();
            SetStartTime(time);

            if (needStart)
            {
                Start();
            }
        }
Пример #20
0
 public NoteWithCustomTimeAndLength(byte noteNumber,
                                    byte channel,
                                    byte velocity,
                                    byte offVelocity,
                                    ITimeSpan time,
                                    ITimeSpan length)
 {
     NoteNumber  = (SevenBitNumber)noteNumber;
     Channel     = (FourBitNumber)channel;
     Velocity    = (SevenBitNumber)velocity;
     OffVelocity = (SevenBitNumber)offVelocity;
     Time        = time;
     Length      = length;
 }
        /// <summary>
        /// Converts the string representation of a time span to its <see cref="ITimeSpan"/> equivalent.
        /// A return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="input">A string containing a time span to convert.</param>
        /// <param name="timeSpan">When this method returns, contains the <see cref="ITimeSpan"/>
        /// equivalent of the time span contained in <paramref name="input"/>, if the conversion succeeded, or
        /// null if the conversion failed. The conversion fails if the <paramref name="input"/> is null or
        /// <see cref="String.Empty"/>, or is not of the correct format. This parameter is passed uninitialized;
        /// any value originally supplied in result will be overwritten.</param>
        /// <returns>true if <paramref name="input"/> was converted successfully; otherwise, false.</returns>
        public static bool TryParse(string input, out ITimeSpan timeSpan)
        {
            timeSpan = null;

            foreach (var parser in Parsers.Values)
            {
                if (TryParse(input, parser, out timeSpan))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #22
0
        public long ConvertFrom(ITimeSpan timeSpan, long time, TempoMap tempoMap)
        {
            var ticksPerQuarterNoteTimeDivision = tempoMap.TimeDivision as TicksPerQuarterNoteTimeDivision;

            if (ticksPerQuarterNoteTimeDivision == null)
            {
                throw new ArgumentException("Time division is not supported for time span conversion.", nameof(tempoMap));
            }

            var startTimeSpan = TicksToMetricTimeSpan(time, ticksPerQuarterNoteTimeDivision.TicksPerQuarterNote, tempoMap);
            var endTimeSpan   = startTimeSpan + (MetricTimeSpan)timeSpan;

            return(MetricTimeSpanToTicks(endTimeSpan, ticksPerQuarterNoteTimeDivision.TicksPerQuarterNote, tempoMap) - time);
        }
Пример #23
0
        /// <summary>
        /// Resizes group of notes to the specified length treating all notes as single object.
        /// </summary>
        /// <param name="notes">Notes to resize.</param>
        /// <param name="length">New length of the notes collection.</param>
        /// <param name="distanceCalculationType">Type of distance calculations.</param>
        /// <param name="tempoMap"></param>
        /// <exception cref="ArgumentNullException">
        /// <para>One of the following errors occured:</para>
        /// <list type="bullet">
        /// <item>
        /// <description><paramref name="notes"/> is <c>null</c>.</description>
        /// </item>
        /// <item>
        /// <description><paramref name="length"/> is <c>null</c>.</description>
        /// </item>
        /// <item>
        /// <description><paramref name="tempoMap"/> is <c>null</c>.</description>
        /// </item>
        /// </list>
        /// </exception>
        /// <exception cref="ArgumentException"><see cref="TimeSpanType.BarBeatTicks"/> or <see cref="TimeSpanType.BarBeatFraction"/>
        /// is used for <paramref name="distanceCalculationType"/> which is unsupported.</exception>
        /// <exception cref="InvalidEnumArgumentException"><paramref name="distanceCalculationType"/> specified an
        /// invalid value.</exception>
        public static void ResizeNotes(this IEnumerable <Note> notes,
                                       ITimeSpan length,
                                       TimeSpanType distanceCalculationType,
                                       TempoMap tempoMap)
        {
            ThrowIfArgument.IsNull(nameof(notes), notes);
            ThrowIfArgument.IsNull(nameof(length), length);
            ThrowIfArgument.IsInvalidEnumValue(nameof(distanceCalculationType), distanceCalculationType);
            ThrowIfArgument.IsNull(nameof(tempoMap), tempoMap);

            // Unable to calculate ratio between two bar/beat time spans
            if (distanceCalculationType == TimeSpanType.BarBeatTicks || distanceCalculationType == TimeSpanType.BarBeatFraction)
            {
                throw new ArgumentException("Bar/beat distance calculation type is not supported.", nameof(distanceCalculationType));
            }

            var notNullNotes = notes.Where(n => n != null);

            if (!notNullNotes.Any())
            {
                return;
            }

            //

            var minStartTime = long.MaxValue;
            var maxEndTime   = 0L;

            foreach (var note in notNullNotes)
            {
                var noteStartTime = note.Time;
                var noteEndTime   = noteStartTime + note.Length;

                minStartTime = Math.Min(minStartTime, noteStartTime);
                maxEndTime   = Math.Max(maxEndTime, noteEndTime);
            }

            var totalLength = maxEndTime - minStartTime;

            //

            var oldLength = LengthConverter.ConvertTo(totalLength, distanceCalculationType, minStartTime, tempoMap);
            var newLength = LengthConverter.ConvertTo(length, distanceCalculationType, minStartTime, tempoMap);
            var ratio     = TimeSpanUtilities.Divide(newLength, oldLength);

            var startTime = TimeConverter.ConvertTo(minStartTime, distanceCalculationType, tempoMap);

            ResizeNotesByRatio(notNullNotes, ratio, distanceCalculationType, tempoMap, startTime);
        }
Пример #24
0
        public long ConvertFrom(ITimeSpan timeSpan, long time, TempoMap tempoMap)
        {
            var mathTimeSpan = (MathTimeSpan)timeSpan;

            Func <MathTimeSpan, long, TempoMap, long> converter;

            if (Converters.TryGetValue(mathTimeSpan.Mode, out converter))
            {
                return(converter(mathTimeSpan, time, tempoMap));
            }
            else
            {
                throw new ArgumentException($"{mathTimeSpan.Mode} mode is not supported by the converter.", nameof(timeSpan));
            }
        }
Пример #25
0
        private static MathTimeSpan CheckMathTimeSpan(ITimeSpan timeSpan1, ITimeSpan timeSpan2, MathOperation operation, TimeSpanMode mode)
        {
            var mathTimeSpan = (operation == MathOperation.Add
                ? timeSpan1.Add(timeSpan2, mode)
                : timeSpan1.Subtract(timeSpan2, mode)) as MathTimeSpan;

            Assert.IsTrue(mathTimeSpan != null &&
                          mathTimeSpan.TimeSpan1.Equals(timeSpan1) &&
                          mathTimeSpan.TimeSpan2.Equals(timeSpan2) &&
                          mathTimeSpan.Operation == operation &&
                          mathTimeSpan.Mode == mode,
                          "Result is not a math time span.");

            return(mathTimeSpan);
        }
Пример #26
0
        /// <summary>
        /// Adds a snap point with the specified data at given time.
        /// </summary>
        /// <typeparam name="TData">Type of data that will be attached to a snap point.</typeparam>
        /// <param name="time">Time to add snap point at.</param>
        /// <param name="data">Data to attach to snap point.</param>
        /// <returns>An instance of the <see cref="SnapPoint{TData}"/> representing a snap point
        /// with <paramref name="data"/> at <paramref name="time"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="time"/> is <c>null</c>.</exception>
        public SnapPoint <TData> AddSnapPoint <TData>(ITimeSpan time, TData data)
        {
            ThrowIfArgument.IsNull(nameof(time), time);

            TimeSpan metricTime = TimeConverter.ConvertTo <MetricTimeSpan>(time, _tempoMap);

            if (metricTime == TimeSpan.Zero)
            {
                metricTime = new TimeSpan(1);
            }

            var snapPoint = new SnapPoint <TData>(metricTime, data);

            _snapPoints.Add(snapPoint);
            return(snapPoint);
        }
Пример #27
0
        public static double GetMinTimeSpanDistance(ITimeSpan a, ITimeSpan b)
        {
            if (IsOverlapping(a, b))
            {
                return(0);
            }

            if (a.EndTime <= b.StartTime)
            {
                return(b.StartTime - a.EndTime);
            }
            else
            {
                return(a.StartTime - b.EndTime);
            }
        }
Пример #28
0
        public static void Parse(string input, ITimeSpan expectedTimeSpan)
        {
            TimeSpanUtilities.TryParse(input, out var actualTimeSpan);
            Assert.AreEqual(expectedTimeSpan,
                            actualTimeSpan,
                            "TryParse: incorrect result.");

            actualTimeSpan = TimeSpanUtilities.Parse(input);
            Assert.AreEqual(expectedTimeSpan,
                            actualTimeSpan,
                            "Parse: incorrect result.");

            Assert.AreEqual(expectedTimeSpan,
                            TimeSpanUtilities.Parse(expectedTimeSpan.ToString()),
                            "Parse: string representation was not parsed to the original time span.");
        }
Пример #29
0
        /// <summary>
        ///     Converts the string representation of a time span to its <see cref="ITimeSpan" /> equivalent.
        ///     A return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="input">A string containing a time span to convert.</param>
        /// <param name="timeSpan">
        ///     When this method returns, contains the <see cref="ITimeSpan" />
        ///     equivalent of the time span contained in <paramref name="input" />, if the conversion succeeded, or
        ///     null if the conversion failed. The conversion fails if the <paramref name="input" /> is null or
        ///     <see cref="String.Empty" />, or is not of the correct format. This parameter is passed uninitialized;
        ///     any value originally supplied in result will be overwritten.
        /// </param>
        /// <returns>true if <paramref name="input" /> was converted successfully; otherwise, false.</returns>
        public static bool TryParse(string input, out ITimeSpan timeSpan)
        {
            timeSpan = null;

            foreach (var parser in Parsers)
            {
                var parsingResult = parser(input);
                if (parsingResult.Item1.Status == ParsingStatus.Parsed)
                {
                    timeSpan = parsingResult.Item2;
                    return(true);
                }
            }

            return(timeSpan != null);
        }
Пример #30
0
        private void SplitByGrid_MultipleSteps(IEnumerable <TObject> inputObjects,
                                               ITimeSpan gridStart,
                                               IEnumerable <ITimeSpan> gridSteps,
                                               Dictionary <TObject, IEnumerable <TimeAndLength> > expectedParts,
                                               TempoMap tempoMap)
        {
            var expectedObjects = expectedParts
                                  .SelectMany(p => p.Value.Select(tl => CloneAndChangeTimeAndLength(
                                                                      p.Key,
                                                                      TimeConverter.ConvertFrom(tl.Time, tempoMap),
                                                                      LengthConverter.ConvertFrom(tl.Length, tl.Time, tempoMap))))
                                  .ToArray();

            var actualObjects = Splitter.SplitByGrid(inputObjects, new SteppedGrid(gridStart, gridSteps), tempoMap).ToArray();

            ObjectMethods.AssertCollectionsAreEqual(expectedObjects, actualObjects);
        }
Пример #31
0
        /// <summary>
        /// Shifts events forward inside <see cref="TrackChunk"/> by the specified distance.
        /// </summary>
        /// <param name="trackChunk"><see cref="TrackChunk"/> containing events to shift.</param>
        /// <param name="distance">Distance to shift events by.</param>
        /// <param name="tempoMap">Tempo map used for internal distance conversions.</param>
        /// <exception cref="ArgumentNullException">
        /// <para>One of the following errors occured:</para>
        /// <list type="bullet">
        /// <item>
        /// <description><paramref name="trackChunk"/> is <c>null</c>.</description>
        /// </item>
        /// <item>
        /// <description><paramref name="distance"/> is <c>null</c>.</description>
        /// </item>
        /// <item>
        /// <description><paramref name="tempoMap"/> is <c>null</c>.</description>
        /// </item>
        /// </list>
        /// </exception>
        public static void ShiftEvents(this TrackChunk trackChunk, ITimeSpan distance, TempoMap tempoMap)
        {
            ThrowIfArgument.IsNull(nameof(trackChunk), trackChunk);
            ThrowIfArgument.IsNull(nameof(distance), distance);
            ThrowIfArgument.IsNull(nameof(tempoMap), tempoMap);

            var convertedDistance = TimeConverter.ConvertFrom(distance, TempoMap.Create(tempoMap.TimeDivision));

            var firstEvent = trackChunk.Events.FirstOrDefault();

            if (firstEvent == null)
            {
                return;
            }

            firstEvent.DeltaTime += convertedDistance;
        }
        /// <summary>
        /// Splits objects by the specified step so every object will be splitted at points
        /// equally distanced from each other starting from the object's start time.
        /// </summary>
        /// <remarks>
        /// Nulls, objects with zero length and objects with length smaller than <paramref name="step"/>
        /// will not be splitted and will be returned as clones of the input objects.
        /// </remarks>
        /// <param name="objects">Objects to split.</param>
        /// <param name="step">Step to split objects by.</param>
        /// <param name="tempoMap">Tempo map used to calculate times to split by.</param>
        /// <returns>Objects that are result of splitting <paramref name="objects"/> going in the same
        /// order as elements of <paramref name="objects"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="objects"/> is null. -or-
        /// <paramref name="step"/> is null. -or- <paramref name="tempoMap"/> is null.</exception>
        public IEnumerable <TObject> SplitByStep(IEnumerable <TObject> objects, ITimeSpan step, TempoMap tempoMap)
        {
            ThrowIfArgument.IsNull(nameof(objects), objects);
            ThrowIfArgument.IsNull(nameof(step), step);
            ThrowIfArgument.IsNull(nameof(tempoMap), tempoMap);

            foreach (var obj in objects)
            {
                if (obj == null)
                {
                    yield return(default(TObject));

                    continue;
                }

                if (obj.Length == 0)
                {
                    yield return(CloneObject(obj));

                    continue;
                }

                var startTime = obj.Time;
                var endTime   = startTime + obj.Length;

                var time = startTime;
                var tail = CloneObject(obj);

                while (time < endTime && tail != null)
                {
                    var convertedStep = LengthConverter.ConvertFrom(step, time, tempoMap);
                    if (convertedStep == 0)
                    {
                        throw new InvalidOperationException("Step is too small.");
                    }

                    time += convertedStep;

                    var parts = SplitObject(tail, time);
                    yield return(parts.LeftPart);

                    tail = parts.RightPart;
                }
            }
        }
 public InternalLink(ILinkableComponent1 component1Target, IInputExchangeItem target1, ITimeSpan timeHorizon, IValueSetConverterTime convertor, bool isVector)
 {
     _component1Source = new DummyComponent1Source(timeHorizon, convertor, isVector);
     _component1Target = component1Target;
     _quantity1 = target1.Quantity;
     _elementSet1 = target1.ElementSet;
 }
 public DummyComponent1Base(ITimeSpan timeHorizon)
 {
     _timeHorizon = timeHorizon;
     _earliestInputTime = _timeHorizon.Start;
 }
 public DummyComponent1Source(ITimeSpan timeHorizon, IValueSetConverterTime convertor, bool isVector)
     : base(timeHorizon)
 {
     _convertor = convertor;
     _isVector = isVector;
 }
 public DummyComponent1Target(ITimeSpan timeHorizon)
     : base(timeHorizon)
 {
 }
Пример #37
0
		/// <summary>
		/// Initializes this listener to show progress of simulation using events.
		/// </summary>
		/// <param name="simulationTimeHorizon">Time horizon of whole simulation.</param>
		/// <param name="progressBar">Progress bar where simulation progress will be shown.</param>
		/// <remarks>Typically <c>simulationTimeHorizon</c> is defined as time from earliest model start
		/// to latest model end.</remarks>
		public void Initialize( ITimeSpan simulationTimeHorizon, ProgressBar progressBar )
		{
			_progressBar = progressBar;
			_simulationTimeHorizon = simulationTimeHorizon;

			_maximumTime = simulationTimeHorizon.Start.ModifiedJulianDay;
			
			_progressBar.Minimum = 0;
			_progressBar.Maximum = ProgressBarMaximum;
		}
Пример #38
0
		/// <summary>
		/// A ValueSet corresponding to a TimeSpan is calculated using interpolation or
		/// extrapolation in corresponding lists of ValueSets and TimeStamps.
		/// </summary>
		/// <param name="requestedTime">Time for which the ValueSet is requested</param>
		/// <returns>ValueSet that corresponds to requestedTime</returns>
		private IValueSet MapFromTimeStampsToTimeSpan(ITimeSpan requestedTime)
		{
			try
      {
        int	       m  = ((IValueSet)_values[0]).Count;
			//int        N  = _times.Count;								   	      // Number of time steps in buffer
			double[][] xr = new double[m][];                                      // Values to return
			double trb    = requestedTime.Start.ModifiedJulianDay;   // Begin time in requester time interval
			double tre    = requestedTime.End.ModifiedJulianDay;    // End time in requester time interval

			int nk; // number of components (scalars has only 1 and vectors has 3 (3 axis))

			if (_values[0] is IVectorSet)
			{
				nk = 3;
			}
			else
			{
				nk = 1;
			}
				
			for (int i = 0; i < m; i++)
			{
				xr[i] = new double[nk];
			}

			for (int i = 0; i < m; i++)
			{
				for (int k = 0; k < nk; k++)
				{
					xr[i][k] = 0;
				}
			}


			for (int n = 0; n < _times.Count-1; n++)
			{
				double tbn   = ((ITimeStamp) _times[n]).ModifiedJulianDay;
				double tbnp1 = ((ITimeStamp) _times[n+1]).ModifiedJulianDay;
				

				//---------------------------------------------------------------------------
				//    B:           <-------------------------->
				//    R:        <------------------------------------->
				// --------------------------------------------------------------------------
				if (trb <= tbn && tre >= tbnp1 )
				{
					for (int k = 1; k <= nk; k++)
					{
						for (int i = 0; i < m; i++) // for all values coorsponding to the same time interval
						{
							double sbin   = Support.GetVal((IValueSet)_values[n], i, k);
							double sbinp1 = Support.GetVal((IValueSet)_values[n+1], i, k);
							xr[i][k-1] += 0.5 * (sbin + sbinp1) * (tbnp1 - tbn)/(tre - trb);
						}
					}
				}

				//---------------------------------------------------------------------------
				//           Times[i] Interval:        t1|-----------------------|t2
				//           Requested Interval:          rt1|--------------|rt2
				// --------------------------------------------------------------------------
				else if (tbn <= trb && tre <= tbnp1) //cover all
				{
					for (int k = 1; k <= nk; k++)
					{
						for (int i = 0; i < m; i++) // for all values coorsponding to the same time interval
						{
							double sbin   = Support.GetVal((IValueSet)_values[n], i, k);
							double sbinp1 = Support.GetVal((IValueSet)_values[n+1], i, k);
							xr[i][k-1] += sbin + ((sbinp1 - sbin)/(tbnp1 - tbn))*((tre + trb)/2 - tbn);
						}
					}
				}

				//---------------------------------------------------------------------------
				//           Times[i] Interval:       t1|-----------------|t2
				//           Requested Interval:                 rt1|--------------|rt2
				// --------------------------------------------------------------------------
				else if (tbn < trb && trb < tbnp1 && tre > tbnp1)
				{
					for (int k = 1; k <= nk; k++)
					{
						for (int i = 0; i < m; i++) // for all values coorsponding to the same time interval
						{
							double sbin   = Support.GetVal((IValueSet)_values[n], i, k);
							double sbinp1 = Support.GetVal((IValueSet)_values[n+1], i, k);
							xr[i][k-1] +=  (sbinp1 - (sbinp1 - sbin)/(tbnp1 - tbn)*((tbnp1 - trb)/2))* (tbnp1 - trb)/(tre - trb);
						}
					}
				}

				//---------------------------------------------------------------------------
				//           Times[i] Interval:             t1|-----------------|t2
				//           Requested Interval:      rt1|--------------|rt2
				// --------------------------------------------------------------------------
				else if (trb < tbn && tre > tbn && tre < tbnp1)
				{
					for (int k = 1; k <= nk; k++)
					{
						for (int i = 0; i < m; i++) // for all values coorsponding to the same time interval
						{
							double sbin   = Support.GetVal((IValueSet)_values[n], i, k);
							double sbinp1 = Support.GetVal((IValueSet)_values[n+1], i, k);
							xr[i][k-1] += (sbin + (sbinp1 - sbin)/(tbnp1 - tbn)*((tre - tbn)/2)) * (tre - tbn)/(tre - trb);
						}
					}
				}
			}
			//--------------------------------------------------------------------------
			//              |--------|---------|--------| B
			//        |----------------|                  R
			//---------------------------------------------------------------------------
			double tb0   = ((ITimeStamp) _times[0]).ModifiedJulianDay;
			//double tb1   = ((ITimeStamp) _times[0]).ModifiedJulianDay;
			double tb1   = ((ITimeStamp) _times[1]).ModifiedJulianDay; // line above was corrected to this Gregersen Sep 15 2004
			double tbN_1 = ((ITimeStamp) _times[_times.Count-1]).ModifiedJulianDay;
			double tbN_2 = ((ITimeStamp) _times[_times.Count-2]).ModifiedJulianDay;
			
			if (trb < tb0 && tre > tb0)
			{
				for (int k = 1; k <= nk; k++)
				{
					for (int i = 0; i < m; i++)
					{
						double sbi0 = Support.GetVal((IValueSet)_values[0], i, k);
						double sbi1 = Support.GetVal((IValueSet)_values[1], i, k);
						xr[i][k-1] += ((tb0 - trb)/(tre - trb)) * (sbi0 - (1 - _relaxationFactor) * 0.5 * ((tb0 - trb)*(sbi1 - sbi0)/(tb1 - tb0)));
					}
				}
			}
			//-------------------------------------------------------------------------------------
			//              |--------|---------|--------| B
			//                                    |----------------|                  R
			//-------------------------------------------------------------------------------------
			if (tre > tbN_1 && trb < tbN_1)
			{
				for (int k = 1; k <= nk; k++)
				{
					for (int i = 0; i < m; i++)
					{
						double sbiN_1 = Support.GetVal((IValueSet)_values[_times.Count-1], i, k);
						double sbiN_2 = Support.GetVal((IValueSet)_values[_times.Count-2], i, k);
						xr[i][k-1] += ((tre - tbN_1)/(tre - trb)) * (sbiN_1 + (1 - _relaxationFactor) * 0.5 * ((tre - tbN_1)*(sbiN_1 - sbiN_2)/(tbN_1 - tbN_2)));
					}
				}
			}
			//-------------------------------------------------------------------------------------
			//              |--------|---------|--------| B
			//                                              |----------------|   R
			//-------------------------------------------------------------------------------------
			if (trb >= tbN_1)
			{
				
				for (int k = 1; k <= nk; k++)
				{
					for (int i = 0; i < m; i++)
					{
						double sbiN_1 = Support.GetVal((IValueSet)_values[_times.Count-1], i, k);
						double sbiN_2 = Support.GetVal((IValueSet)_values[_times.Count-2], i, k);
					
						xr[i][k-1] = sbiN_1 + (1 - _relaxationFactor) * ((sbiN_1 - sbiN_2)/(tbN_1 - tbN_2)) * ( 0.5 * (trb + tre) - tbN_1);
					}
				}
			}
			//-------------------------------------------------------------------------------------
			//                           |--------|---------|--------| B
			//        |----------------|   R
			//-------------------------------------------------------------------------------------
			if (tre <= tb0)
			{
				for (int k = 1; k <= nk; k++)
				{
					for (int i = 0; i < m; i++)
					{
						double sbi0 = Support.GetVal((IValueSet)_values[0], i, k);
						double sbi1 = Support.GetVal((IValueSet)_values[1], i, k);
						xr[i][k-1] = sbi0 - (1 - _relaxationFactor) * ((sbi1 - sbi0)/(tb1- tb0))*(tb0 - 0.5 * (trb + tre));
					}
				}
			}
			//-------------------------------------------------------------------------------------
        if (_values[0] is IVectorSet)
        {
          Vector [] vectors = new Vector[m]; 

          for (int i = 0; i < m; i++)
          {
            vectors[i] = new Vector(xr[i][0],xr[i][1],xr[i][2]);
          }

          VectorSet vectorSet = new VectorSet(vectors);

          return vectorSet;
        }
        else
        {
          double[] xx = new double[m];

          for (int i = 0; i < m; i++)
          {
            xx[i] = xr[i][0];
          }
				
          ScalarSet scalarSet = new ScalarSet(xx);

          return scalarSet;
        }
      }
      catch (Exception e)
      {
        throw new Exception("MapFromTimeStampsToTimeSpan Failed",e);
      }
		}
Пример #39
0
		/// <summary>
		/// Creates a new instance of <see cref="ProgressBarListener">ProgressBarListener</see> class.
		/// </summary>
		/// <param name="simulationTimeHorizon">Time horizon of whole simulation.</param>
		/// <param name="progressBar">Progress bar.</param>
		/// <remarks>See <see cref="Initialize">Initialize</see>
		/// for more details.</remarks>
		public ProgressBarListener( ITimeSpan simulationTimeHorizon, ProgressBar progressBar )
		{
			Initialize( simulationTimeHorizon, progressBar );
		}
Пример #40
0
		/// <summary>
		/// A ValueSet corresponding to a TimeSpan is calculated using interpolation or
		/// extrapolation in corresponding lists of ValueSets and TimeSpans.
		/// </summary>
		/// <param name="requestedTime">Time for which the ValueSet is requested</param>
		/// <returns>ValueSet that corresponds to requestedTime</returns>
		private IValueSet MapFromTimeSpansToTimeSpan(ITimeSpan requestedTime)

		{
      try
      {
        int	       m  = ((IValueSet)_values[0]).Count;
        double[][] xr = new double[m][];                                       // Values to return
        double trb    = requestedTime.Start.ModifiedJulianDay;   // Begin time in requester time interval
        double tre    = requestedTime.End.ModifiedJulianDay;     // End time in requester time interval

        int nk; // number of components (scalars has only 1 and vectors has 3 (3 axis))

        if (_values[0] is IVectorSet)
        {
          nk = 3;
        }
        else
        {
          nk = 1;
        }
				
        for (int i = 0; i < m; i++)
        {
          xr[i] = new double[nk];
        }

        for (int i = 0; i < m; i++)
        {
          for (int k = 0; k < nk; k++)
          {
            xr[i][k] = 0;
          }
        }

        for (int n = 0; n < _times.Count; n++)
        {
          double tbbn = ((ITimeSpan) _times[n]).Start.ModifiedJulianDay;
          double tben = ((ITimeSpan) _times[n]).End.ModifiedJulianDay;

          //---------------------------------------------------------------------------
          //    B:           <-------------------------->
          //    R:        <------------------------------------->
          // --------------------------------------------------------------------------
          if (trb <= tbbn && tre >= tben ) //Buffered TimeSpan fully included in requested TimeSpan
          {
            for (int k = 1; k <= nk; k++)
            {
              for (int i = 0; i < m; i++) // for all values coorsponding to the same time interval
              {
                double sbin = Support.GetVal((IValueSet)_values[n], i, k);
                xr[i][k-1] += sbin * (tben - tbbn)/(tre - trb);
              }
            }
          }

            //---------------------------------------------------------------------------
            //           Times[i] Interval:        t1|-----------------------|t2
            //           Requested Interval:          rt1|--------------|rt2
            // --------------------------------------------------------------------------
          else if (tbbn <= trb && tre <= tben) //cover all
          {
            for (int k = 1; k <= nk; k++)
            {
              for (int i = 0; i < m; i++) // for all values coorsponding to the same time interval
              {
                xr[i][k-1] += Support.GetVal((IValueSet)_values[n], i, k);
              }
            }
          }

            //---------------------------------------------------------------------------
            //           Times[i] Interval:       t1|-----------------|t2
            //           Requested Interval:                 rt1|--------------|rt2
            // --------------------------------------------------------------------------
          else if (tbbn < trb && trb < tben && tre > tben)
          {
            for (int k = 1; k <= nk; k++)
            {
              for (int i = 0; i < m; i++) // for all values coorsponding to the same time interval
              {
                double sbin = Support.GetVal((IValueSet)_values[n], i, k);
                xr[i][k-1] += sbin * (tben - trb)/(tre - trb);
              }
            }
          }

            //---------------------------------------------------------------------------
            //           Times[i] Interval:             t1|-----------------|t2
            //           Requested Interval:      rt1|--------------|rt2
            // --------------------------------------------------------------------------
          else if (trb < tbbn && tre > tbbn && tre < tben)
          {
            for (int k = 1; k <= nk; k++)
            {
              for (int i = 0; i < m; i++) // for all values coorsponding to the same time interval
              {
                double sbin = Support.GetVal((IValueSet)_values[n], i, k);
                xr[i][k-1] += sbin * (tre - tbbn)/(tre - trb);
              }
            }
          }
        }

        //--------------------------------------------------------------------------
        //              |--------|---------|--------| B
        //        |----------------|                  R
        //---------------------------------------------------------------------------
        double tbb0 = ((ITimeSpan) _times[0]).Start.ModifiedJulianDay;
        double tbe0 = ((ITimeSpan) _times[0]).End.ModifiedJulianDay;
        //double tbb1 = ((ITimeSpan) _times[1]).Start.ModifiedJulianDay;
        double tbe1 = ((ITimeSpan) _times[1]).End.ModifiedJulianDay;

        if (trb < tbb0 && tre > tbb0)
        {
          for (int k = 1; k <= nk; k++)
          {
            for (int i = 0; i < m; i++)
            {
              double sbi0 = Support.GetVal((IValueSet)_values[0], i, k);
              double sbi1 = Support.GetVal((IValueSet)_values[1], i, k); 
              xr[i][k-1] += ((tbb0 - trb)/(tre - trb)) * (sbi0 - (1 - _relaxationFactor) * ((tbb0 - trb)*(sbi1 - sbi0)/(tbe1 - tbe0)));
            }
          }
        }

        //-------------------------------------------------------------------------------------
        //              |--------|---------|--------| B
        //                                    |----------------|                  R
        //-------------------------------------------------------------------------------------

        double tbeN_1 = ((ITimeSpan) _times[_times.Count-1]).End.ModifiedJulianDay;
        double tbbN_2 = ((ITimeSpan) _times[_times.Count-2]).Start.ModifiedJulianDay;

        if (tre > tbeN_1 && trb < tbeN_1)
        {
          //double tbeN_2 = ((ITimeSpan) _times[_times.Count-2]).End.ModifiedJulianDay;
          double tbbN_1 = ((ITimeSpan) _times[_times.Count-1]).Start.ModifiedJulianDay;

          for (int k = 1; k <= nk; k++)
          {
            for (int i = 0; i < m; i++)
            {
              double sbiN_1 = Support.GetVal((IValueSet)_values[_times.Count-1], i, k);
              double sbiN_2 = Support.GetVal((IValueSet)_values[_times.Count-2], i,k);
              xr[i][k-1] += ((tre - tbeN_1)/(tre - trb)) * (sbiN_1 + (1 - _relaxationFactor) * ((tre - tbbN_1)*(sbiN_1 - sbiN_2)/(tbeN_1 - tbbN_2)));
            }
          }
        }
        //-------------------------------------------------------------------------------------
        //              |--------|---------|--------| B
        //                                              |----------------|   R
        //-------------------------------------------------------------------------------------

        if (trb >= tbeN_1)
        {
          double tbeN_2 = ((ITimeSpan) _times[_times.Count-2]).End.ModifiedJulianDay;
          //double tbbN_1 = ((ITimeSpan) _times[_times.Count-1]).Start.ModifiedJulianDay;
			
          for (int k = 1; k <= nk; k++)
          {
            for (int i = 0; i < m; i++)
            {
              double sbiN_1 = Support.GetVal((IValueSet)_values[_times.Count-1], i, k);
              double sbiN_2 = Support.GetVal((IValueSet)_values[_times.Count-2], i, k);
              xr[i][k-1] = sbiN_1 + (1 - _relaxationFactor) * ((sbiN_1 - sbiN_2)/(tbeN_1 - tbbN_2)) * (trb + tre - tbeN_1 - tbeN_2);
            }
          }
        }

        //-------------------------------------------------------------------------------------
        //                           |--------|---------|--------| B
        //        |----------------|   R
        //-------------------------------------------------------------------------------------

        if (tre <= tbb0)
        {
          for (int k = 1; k <= nk; k++)
          {
            for (int i = 0; i < m; i++)
            {
              double sbi0 = Support.GetVal((IValueSet)_values[0], i, k);
              double sbi1 = Support.GetVal((IValueSet)_values[1], i, k);
              xr[i][k-1] = sbi0 - (1 - _relaxationFactor) * ((sbi1 - sbi0)/(tbe1- tbb0))*(tbe0 + tbb0 - tre - trb);
            }
          }
        }

        //-------------------------------------------------------------------------------------
        if (_values[0] is IVectorSet)
        {
          Vector [] vectors = new Vector[m]; 

          for (int i = 0; i < m; i++)
          {
            vectors[i] = new Vector(xr[i][0],xr[i][1],xr[i][2]);
          }

          VectorSet vectorSet = new VectorSet(vectors);

          return vectorSet;
        }
        else
        {
          double[] xx = new double[m];

          for (int i = 0; i < m; i++)
          {
            xx[i] = xr[i][0];
          }
				
          ScalarSet scalarSet = new ScalarSet(xx);

          return scalarSet;
        }
      }
      catch (Exception e)
      {
        throw new Exception("MapFromTimeSpansToTimeSpan Failed",e);
      }
		}
Пример #41
0
		/// <summary>
		/// Copy constructor
		/// </summary>
		/// <param name="source">The time span to copy</param>
		public TimeSpan(ITimeSpan source)
		{
			Start = new TimeStamp(source.Start);
			End = new TimeStamp(source.End);
		}
Пример #42
0
    /// <summary>
    /// Clears the buffer between start- and end- time of the time (TimeSpan).
    /// </summary>
    public void Clear(ITimeSpan time)

		//TODO: This method may not be used anywhere. Check if this is true and then remove this method
		{
			if (_times.Count > 0)
			{
				if(_times[0] is ITimeStamp)
				{
					for (int i = 0; i < _times.Count; i++)
					{
						if (((ITimeStamp)_times[i]).ModifiedJulianDay > time.Start.ModifiedJulianDay && ((ITimeStamp)_times[i]).ModifiedJulianDay < time.End.ModifiedJulianDay)
						{
							_times.RemoveAt(i);
							_values.RemoveAt(i);
						}
					}
				}
				else if (_times[0] is ITimeSpan)
				{
					for (int i = 0; i < _times.Count; i++)
					{
						if (((ITimeSpan)_times[i]).Start.ModifiedJulianDay > time.Start.ModifiedJulianDay && ((ITimeSpan)_times[i]).End.ModifiedJulianDay < time.End.ModifiedJulianDay)
						{
							_times.RemoveAt(i);
							_values.RemoveAt(i);
						}
					}
				}
			}
		}
 public InternalLink(ILinkableComponent1 component1Source, IOutputExchangeItem source1, ITimeSpan timeHorizon)
 {
     _component1Source = component1Source;
     _component1Target = new DummyComponent1Target(timeHorizon);
     _quantity1 = source1.Quantity;
     _elementSet1 = source1.ElementSet;
 }