// // Math.NET Numerics, part of the Math.NET Project // http://mathnet.opensourcedotnet.info // Copyright (c) 2009 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // using MathNet.Numerics.Threading; namespace MathNet.Numerics.LinearAlgebra.Double { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using MathNet.Numerics.Properties; /// /// Defines the base class for Vector classes. /// [Serializable] public abstract class Vector : IFormattable, IEnumerable, ICloneable, IEquatable { /// /// Initializes a new instance of the class. /// Constructs a Vector with the given size. /// /// /// The size of the Vector to construct. /// /// /// If is less than one. /// protected Vector(int size) { if (size < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "size"); } Count = size; } /// /// Gets he number of elements in the vector. /// public int Count { get; private set; } /// Gets or sets the value at the given . /// The index of the value to get or set. /// The value of the vector at the given . /// If is negative or /// greater than the size of the vector. public abstract double this[int index] { get; set; } /// /// Returns a deep-copy clone of the vector. /// /// /// A deep-copy clone of the vector. /// public Vector Clone() { var retrunVector = CreateVector(Count); CopyTo(retrunVector); return retrunVector; } /// /// Copies the values of this vector into the target vector. /// /// /// The vector to copy elements into. /// /// /// If is . /// /// /// If is not the same size as this vector. /// public virtual void CopyTo(Vector target) { if (target == null) { throw new ArgumentNullException("target"); } if (Count != target.Count) { throw new ArgumentException("target", Resources.ArgumentVectorsSameLength); } if (ReferenceEquals(this, target)) { return; } for (var index = 0; index < Count; index++) { target[index] = this[index]; } } /// /// Copies the requested elements from this vector to another. /// /// /// The vector to copy the elements to. /// /// /// The element to start copying from. /// /// /// The element to start copying to. /// /// /// The number of elements to copy. /// public virtual void CopyTo(Vector destination, int offset, int destinationOffset, int count) { if (destination == null) { throw new ArgumentNullException("destination"); } if (offset >= Count) { throw new ArgumentOutOfRangeException("offset"); } if (offset + count > Count) { throw new ArgumentOutOfRangeException("count"); } if (destinationOffset >= destination.Count) { throw new ArgumentOutOfRangeException("destinationOffset"); } if (destinationOffset + count > destination.Count) { throw new ArgumentOutOfRangeException("count"); } if (ReferenceEquals(this, destination)) { var tmpVector = destination.CreateVector(destination.Count); CopyTo(tmpVector, offset, destinationOffset, count); tmpVector.CopyTo(destination); } else { for (var index = 0; index < count; index++) { destination[destinationOffset + index] = this[offset + index]; } } } /// /// Creates a matrix with the given dimensions using the same storage type /// as this vector. /// /// /// The number of rows. /// /// /// The number of columns. /// /// /// A matrix with the given dimensions. /// public abstract Matrix CreateMatrix(int rows, int columns); /// /// Creates a Vector of the given size using the same storage type /// as this vector. /// /// /// The size of the Vector to create. /// /// /// The new Vector. /// public abstract Vector CreateVector(int size); /// /// Returns an that contains the position and value of the element. /// /// /// An over this vector that contains the position and value of each /// non-zero element. /// /// /// The enumerator returns a /// /// with the key being the element index and the value /// being the value of the element at that index. For sparse vectors, the enumerator will exclude all elements /// with a zero value. /// [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Needed to support sparse vectors.")] public virtual IEnumerable> GetIndexedEnumerator() { for (var index = 0; index < Count; index++) { yield return new KeyValuePair(index, this[index]); } } /// /// Returns an over the specified elements. /// /// /// The element to start copying from. /// /// /// The number of elements to enumerate over. /// /// /// An over a range of this vector. /// /// /// If or + /// is greater than the vector's length. /// /// /// The enumerator returns a /// /// with the key being the element index and the value /// being the value of the element at that index. /// /// /// [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Needed to support sparse vectors.")] public virtual IEnumerable> GetIndexedEnumerator(int startIndex, int length) { if (startIndex > Count) { throw new ArgumentOutOfRangeException("startIndex"); } if (startIndex + length > Count) { throw new ArgumentOutOfRangeException("length"); } for (var index = startIndex; index < length; index++) { yield return new KeyValuePair(index, this[index]); } } /// /// Returns a that represents this instance. /// /// /// A that represents this instance. /// public override string ToString() { return ToString(null, null); } /// /// Adds a scalar to each element of the vector. /// /// The scalar to add. public virtual void Add(double scalar) { if (scalar.AlmostZero()) { return; } Parallel.For(0, Count, i => this[i] += scalar); } /// /// Adds a scalar to each element of the vector and stores the result in the result vector. /// /// The scalar to add. /// The vector to store the result of the addition. /// If the result vector is . /// If this vector and are not the same size. public virtual void Add(double scalar, Vector result) { if (result == null) { throw new ArgumentNullException("result"); } if (Count != result.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "result"); } CopyTo(result); result.Add(scalar); } /// /// Returns a clone of this vector. /// /// A clone of this vector. /// Added as an alternative to the unary addition operator. public virtual Vector Plus() { return this; } /// /// Adds another vector to this vector. /// /// The vector to add to this one. /// If the other vector is . /// If this vector and are not the same size. public virtual void Add(Vector other) { if (other == null) { throw new ArgumentNullException("other"); } if (Count != other.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "other"); } Parallel.For(0, Count, i => this[i] += other[i]); } /// /// Adds another vector to this vector and stores the result into the result vector. /// /// The vector to add to this one. /// The vector to store the result of the addition. /// If the other vector is . /// If the result vector is . /// If this vector and are not the same size. /// If this vector and are not the same size. public virtual void Add(Vector other, Vector result) { if (result == null) { throw new ArgumentNullException("result"); } if (Count != result.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "result"); } if (ReferenceEquals(this, result) || ReferenceEquals(other, result)) { var tmp = result.CreateVector(result.Count); Add(other, tmp); tmp.CopyTo(result); } else { CopyTo(result); result.Add(other); } } /// /// Returns a Vector containing the same values of rightSide. /// /// This method is included for completeness. /// The vector to get the values from. /// A vector containing a the same values as . /// If is . public static Vector operator +(Vector rightSide) { if (rightSide == null) { throw new ArgumentNullException("rightSide"); } return rightSide.Plus(); } /// /// Adds two Vectors together and returns the results. /// /// One of the vectors to add. /// The other vector to add. /// The result of the addition. /// If and are not the same size. /// If or is . public static Vector operator +(Vector leftSide, Vector rightSide) { if (rightSide == null) { throw new ArgumentNullException("rightSide"); } if (leftSide == null) { throw new ArgumentNullException("leftSide"); } if (leftSide.Count != rightSide.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "rightSide"); } var ret = leftSide.Clone(); ret.Add(rightSide); return ret; } #region Implemented Interfaces #region ICloneable /// /// Creates a new object that is a copy of the current instance. /// /// /// A new object that is a copy of this instance. /// object ICloneable.Clone() { return Clone(); } #endregion #region IEnumerable /// /// Returns an enumerator that iterates through a collection. /// /// /// An object that can be used to iterate through the collection. /// IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region IEnumerable /// /// Returns an enumerator that iterates through the collection. /// /// /// A that can be used to iterate through the collection. /// /// /// For sparse vectors, will perform better. /// [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Needed to support sparse vectors.")] public virtual IEnumerator GetEnumerator() { for (var index = 0; index < Count; index++) { yield return this[index]; } } #endregion #region IEquatable /// /// Indicates whether the current object is equal to another object of the same type. /// /// /// An object to compare with this object. /// /// /// true if the current object is equal to the parameter; otherwise, false. /// public bool Equals(Vector other) { // Reject equality when the argument is null or has a different length. if (other == null) { return false; } if (Count != other.Count) { return false; } // Accept if the argument is the same object as this. if (ReferenceEquals(this, other)) { return true; } // If all else fails, perform element wise comparison. for (var index = 0; index < Count; index++) { if (this[index] != other[index]) { return false; } } return true; } #endregion #region IFormattable /// /// Returns a that represents this instance. /// /// /// The format to use. /// /// /// The format provider to use. /// /// /// A that represents this instance. /// public string ToString(string format, IFormatProvider formatProvider) { var stringBuilder = new StringBuilder(); for (var index = 0; index < Count; index++) { stringBuilder.Append(this[index].ToString(format, formatProvider)); if (index != Count - 1) { stringBuilder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); } } return stringBuilder.ToString(); } #endregion #endregion } }