//
// 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.
//
namespace MathNet.Numerics.LinearAlgebra.Double
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Properties;
using Threading;
///
/// Defines the base class for Vector classes.
///
#if !SILVERLIGHT
[Serializable]
#endif
public abstract class Vector :
#if SILVERLIGHT
IFormattable, IEnumerable, IEquatable
#else
IFormattable, IEnumerable, IEquatable, ICloneable
#endif
{
///
/// 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;
}
///
/// 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);
#region Elementary operations
///
/// Adds a scalar to each element of the vector.
///
/// The scalar to add.
public virtual void Add(double scalar)
{
if (scalar == 0.0)
{
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");
}
if (!ReferenceEquals(this, result))
{
CopyTo(result);
}
result.Add(scalar);
}
///
/// Returns this vector.
///
/// 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);
}
}
///
/// Subtracts a scalar from each element of the vector.
///
/// The scalar to subtract.
public virtual void Subtract(double scalar)
{
if (scalar == 0.0)
{
return;
}
Parallel.For(0, Count, i => this[i] -= scalar);
}
///
/// Subtracts a scalar from each element of the vector and stores the result in the result vector.
///
/// The scalar to subtract.
/// The vector to store the result of the subtraction.
/// If the result vector is .
/// If this vector and are not the same size.
public virtual void Subtract(double scalar, Vector result)
{
if (result == null)
{
throw new ArgumentNullException("result");
}
if (Count != result.Count)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength, "result");
}
if (!ReferenceEquals(this, result))
{
CopyTo(result);
}
result.Subtract(scalar);
}
///
/// Returns a negated vector.
///
/// The negated vector.
/// Added as an alternative to the unary negation operator.
public virtual Vector Negate()
{
return this * -1;
}
///
/// Subtracts another vector from this vector.
///
/// The vector to subtract from this one.
/// If the other vector is .
/// If this vector and are not the same size.
public virtual void Subtract(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]);
}
///
/// Subtracts another vector to this vector and stores the result into the result vector.
///
/// The vector to subtract from this one.
/// The vector to store the result of the subtraction.
/// 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 Subtract(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);
Subtract(other, tmp);
tmp.CopyTo(result);
}
else
{
CopyTo(result);
result.Subtract(other);
}
}
///
/// Multiplies a scalar to each element of the vector.
///
/// The scalar to multiply.
public virtual void Multiply(double scalar)
{
if (scalar.AlmostEqual(1.0))
{
return;
}
Parallel.For(0, Count, index => this[index] *= scalar);
}
///
/// Multiplies a scalar to each element of the vector and stores the result in the result vector.
///
/// The scalar to multiply.
/// The vector to store the result of the multiplication.
/// If the result vector is .
/// If this vector and are not the same size.
public virtual void Multiply(double scalar, Vector result)
{
if (result == null)
{
throw new ArgumentNullException("result");
}
if (Count != result.Count)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength, "result");
}
if (!ReferenceEquals(this, result))
{
CopyTo(result);
}
result.Multiply(scalar);
}
///
/// Divides each element of the vector by a scalar.
///
/// The scalar to divide with.
public virtual void Divide(double scalar)
{
if (scalar.AlmostEqual(1.0))
{
return;
}
Multiply(1.0 / scalar);
}
///
/// Divides each element of the vector by a scalar and stores the result in the result vector.
///
/// The scalar to divide with.
/// The vector to store the result of the division.
/// If the result vector is .
/// If this vector and are not the same size.
public virtual void Divide(double scalar, Vector result)
{
if (result == null)
{
throw new ArgumentNullException("result");
}
if (Count != result.Count)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength, "result");
}
if (!ReferenceEquals(this, result))
{
CopyTo(result);
}
result.Multiply(1.0 / scalar);
}
#endregion
#region Arithmetic Operator Overloading
///
/// 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 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;
}
///
/// Returns a Vector containing the negated values of rightSide.
///
/// The vector to get the values from.
/// A vector containing the negated values as .
/// If is .
public static Vector operator -(Vector rightSide)
{
if (rightSide == null)
{
throw new ArgumentNullException("rightSide");
}
return rightSide.Negate();
}
///
/// Subtracts two Vectors and returns the results.
///
/// The vector to subtract from.
/// The vector to subtract.
/// The result of the subtraction.
/// 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.Subtract(rightSide);
return ret;
}
///
/// Multiplies a vector with a scalar.
///
/// The vector to scale.
/// The scalar value.
/// The result of the multiplication.
/// If is .
public static Vector operator *(Vector leftSide, double rightSide)
{
if (leftSide == null)
{
throw new ArgumentNullException("leftSide");
}
var ret = leftSide.Clone();
ret.Multiply(rightSide);
return ret;
}
///
/// Multiplies a vector with a scalar.
///
/// The scalar value.
/// The vector to scale.
/// The result of the multiplication.
/// If is .
public static Vector operator *(double leftSide, Vector rightSide)
{
if (rightSide == null)
{
throw new ArgumentNullException("rightSide");
}
var ret = rightSide.Clone();
ret.Multiply(leftSide);
return ret;
}
///
/// Divides a vector with a scalar.
///
/// The vector to divide.
/// The scalar value.
/// The result of the division.
/// If is .
public static Vector operator /(Vector leftSide, double rightSide)
{
if (leftSide == null)
{
throw new ArgumentNullException("leftSide");
}
var ret = leftSide.Clone();
ret.Multiply(1.0 / rightSide);
return ret;
}
#endregion
#region Vector Norms
///
/// Euclidean Norm also known as 2-Norm.
///
///
/// Scalar ret = sqrt(sum(this[i]^2))
///
public virtual double Norm()
{
return NormP(2);
}
///
/// Squared Euclidean 2-Norm.
///
///
/// Scalar ret = sum(this[i]^2)
///
public virtual double SquaredNorm()
{
var norm = Norm();
return norm * norm;
}
///
/// 1-Norm also known as Manhattan Norm or Taxicab Norm.
///
///
/// Scalar ret = sum(abs(this[i]))
///
public virtual double Norm1()
{
return NormP(1);
}
///
/// Computes the p-Norm.
///
/// The p value.
/// Scalar ret = (sum(abs(this[i])^p))^(1/p)
public virtual double NormP(int p)
{
if (1 > p)
{
throw new ArgumentOutOfRangeException("p");
}
var sum = 0.0;
var syncLock = new object();
Parallel.For(
0,
Count,
() => 0.0,
(index, localData) =>
{
localData += Math.Pow(Math.Abs(this[index]), p);
return localData;
},
localResult =>
{
lock (syncLock)
{
sum += localResult;
}
});
return Math.Pow(sum, 1.0 / p);
}
///
/// Infinity Norm.
///
///
/// Scalar ret = max(abs(this[i]))
///
public virtual double NormInfinity()
{
var max = 0.0;
var syncLock = new object();
Parallel.For(
0,
Count,
() => 0.0,
(index, localData) =>
{
localData = Math.Max(localData, Math.Abs(this[index]));
return localData;
},
localResult =>
{
lock (syncLock)
{
max = Math.Max(localResult, max);
}
});
return max;
}
///
/// Normalizes this vector to a unit vector with respect to the Eucliden 2-Norm.
///
/// This vector normalized to a unit vector with respect to the Eucliden 2-Norm.
public virtual Vector Normalize()
{
var norm = Norm();
var clone = Clone();
if (norm == 0.0)
{
return clone;
}
clone.Multiply(1.0 / norm);
return clone;
}
#endregion
#region Coping and Conversion
///
/// 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;
}
Parallel.For(0, 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
{
Parallel.For(0, count, index => destination[destinationOffset + index] = this[offset + index]);
}
}
#endregion
#region Implemented Interfaces
#if !SILVERLIGHT
#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
#endif
#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.
///
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].AlmostEqual(other[index]))
{
return false;
}
}
return true;
}
#endregion
#region IFormattable
///
/// Returns a that represents this instance.
///
///
/// An that supplies culture-specific formatting information.
///
///
/// A that represents this instance.
///
public string ToString(IFormatProvider formatProvider)
{
return ToString(null, formatProvider);
}
///
/// Returns a that represents this instance.
///
///
/// The format to use.
///
///
/// An that supplies culture-specific formatting information.
///
///
/// 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(formatProvider.GetTextInfo().ListSeparator);
}
}
return stringBuilder.ToString();
}
#endregion
#endregion
#region System.Object overrides
///
/// Determines whether the specified is equal to this instance.
///
/// The to compare with this instance.
///
/// true if the specified is equal to this instance; otherwise, false.
///
public override bool Equals(object obj)
{
return Equals(obj as Vector);
}
///
/// Returns a hash code for this instance.
///
///
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
///
public override int GetHashCode()
{
var hashNum = Math.Min(Count, 20);
long hash = 0;
for (var i = 0; i < hashNum; i++)
{
#if SILVERLIGHT
hash ^= Precision.DoubleToInt64Bits(this[i]);
#else
hash ^= BitConverter.DoubleToInt64Bits(this[i]);
#endif
}
return BitConverter.ToInt32(BitConverter.GetBytes(hash), 4);
}
///
/// Returns a that represents this instance.
///
///
/// A that represents this instance.
///
public override string ToString()
{
return ToString(null, null);
}
#endregion
}
}