All Downloads are FREE. Search and download functionalities are using the official Maven repository.

axle.algebra.EnrichedMetricSpace.scala Maven / Gradle / Ivy

The newest version!
package axle.algebra

import axle.enrichGenTraversable
import axle.matrix.MatrixModule
import spire.algebra.MetricSpace

abstract class EnrichedMetricSpace[T: Manifest](space: MetricSpace[T, Double]) extends MatrixModule {

  import space._

  def distanceMatrix(vectors: IndexedSeq[T]): Matrix[Double] = {
    val n = vectors.size
    matrix(n, n, (r: Int, c: Int) => distance(vectors(r), vectors(c)).toDouble)
  }

  def nMostSimilar(query: T, vectors: Iterator[T], c: Int): List[(Int, Double)] =
    vectors.zipWithIndex
      .map({ case (v, i) => (i, distance(query, v)) })
      .toList
      .sortBy(_._2)
      .take(c)

  //  def nMostSimilarReport(query: String, n: Int) = nMostSimilar(query, n)
  //    .map(is => (is._2, corpus(is._1))).map(sd => "%.4f %s".format(sd._1, sd._2)).mkString("\n")

  /**
   * triangleInequalityHolds
   *
   * Applies the Triangle Inequality using all the triples formed by the
   * given data to see if this is a true "distance"
   *
   * http://en.wikipedia.org/wiki/Triangle_inequality
   */

  def triangleInequalityHolds(data: collection.GenTraversable[T]): Boolean =
    data.triples.forall({ case (a, b, c) => distance(a, b) + distance(b, c) >= distance(a, c) })

}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy