Skip to content

Commit

Permalink
Basic DE
Browse files Browse the repository at this point in the history
Signed-off-by: Gary Pamparà <gpampara@gmail.com>
  • Loading branch information
gpampara committed Sep 10, 2017
1 parent 4608719 commit 6d6f306
Show file tree
Hide file tree
Showing 10 changed files with 178 additions and 39 deletions.
78 changes: 56 additions & 22 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,56 @@ lazy val buildSettings = Seq(
lazy val commonSettings = Seq(
autoAPIMappings := true,
scalacOptions ++= Seq(
"-deprecation",
"-encoding", "UTF-8",
"-feature",
"-language:existentials",
"-language:higherKinds",
//"-language:implicitConversions",
"-language:experimental.macros",
"-unchecked",
//"-Xfatal-warnings",
"-Xlint",
//"-Xlog-implicits",
"-Yno-adapted-args",
"-Ywarn-dead-code",
"-Ywarn-numeric-widen",
"-Ywarn-value-discard",
// "-Yno-predef",
// "-Yno-imports",
"-Xfuture",
"-Ypartial-unification"
"-deprecation", // Emit warning and location for usages of deprecated APIs.
"-encoding", "utf-8", // Specify character encoding used by source files.
"-explaintypes", // Explain type errors in more detail.
"-feature", // Emit warning and location for usages of features that should be imported explicitly.
"-language:existentials", // Existential types (besides wildcard types) can be written and inferred
"-language:experimental.macros", // Allow macro definition (besides implementation and application)
"-language:higherKinds", // Allow higher-kinded types
"-language:implicitConversions", // Allow definition of implicit functions called views
"-unchecked", // Enable additional warnings where generated code depends on assumptions.
"-Xcheckinit", // Wrap field accessors to throw an exception on uninitialized access.
"-Xfatal-warnings", // Fail the compilation if there are any warnings.
"-Xfuture", // Turn on future language features.
"-Xlint:adapted-args", // Warn if an argument list is modified to match the receiver.
"-Xlint:by-name-right-associative", // By-name parameter of right associative operator.
"-Xlint:constant", // Evaluation of a constant arithmetic expression results in an error.
"-Xlint:delayedinit-select", // Selecting member of DelayedInit.
"-Xlint:doc-detached", // A Scaladoc comment appears to be detached from its element.
"-Xlint:inaccessible", // Warn about inaccessible types in method signatures.
"-Xlint:infer-any", // Warn when a type argument is inferred to be `Any`.
"-Xlint:missing-interpolator", // A string literal appears to be missing an interpolator id.
"-Xlint:nullary-override", // Warn when non-nullary `def f()' overrides nullary `def f'.
"-Xlint:nullary-unit", // Warn when nullary methods return Unit.
"-Xlint:option-implicit", // Option.apply used implicit view.
"-Xlint:package-object-classes", // Class or object defined in package object.
"-Xlint:poly-implicit-overload", // Parameterized overloaded implicit methods are not visible as view bounds.
"-Xlint:private-shadow", // A private field (or class parameter) shadows a superclass field.
"-Xlint:stars-align", // Pattern sequence wildcard must align with sequence component.
"-Xlint:type-parameter-shadow", // A local type parameter shadows a type already in scope.
"-Xlint:unsound-match", // Pattern match may not be typesafe.
"-Yno-adapted-args", // Do not adapt an argument list (either by inserting () or creating a tuple) to match the receiver.
"-Ypartial-unification", // Enable partial unification in type constructor inference
"-Ywarn-dead-code", // Warn when dead code is identified.
"-Ywarn-extra-implicit", // Warn when more than one implicit parameter section is defined.
"-Ywarn-inaccessible", // Warn about inaccessible types in method signatures.
"-Ywarn-infer-any", // Warn when a type argument is inferred to be `Any`.
"-Ywarn-nullary-override", // Warn when non-nullary `def f()' overrides nullary `def f'.
"-Ywarn-nullary-unit", // Warn when nullary methods return Unit.
"-Ywarn-numeric-widen", // Warn when numerics are widened.
"-Ywarn-unused:implicits", // Warn if an implicit parameter is unused.
"-Ywarn-unused:imports", // Warn if an import selector is not referenced.
"-Ywarn-unused:locals", // Warn if a local definition is unused.
"-Ywarn-unused:params", // Warn if a value parameter is unused.
"-Ywarn-unused:patvars", // Warn if a variable bound in a pattern is unused.
"-Ywarn-unused:privates", // Warn if a private member is unused.
"-Ywarn-value-discard" // Warn when non-Unit expression results are unused.
),
scalacOptions in (Compile, console) ~= (_.filterNot(Set(
"-Ywarn-unused:imports",
"-Xfatal-warnings"
))),
resolvers ++= Seq(
Resolver.sonatypeRepo("releases"),
"bintray/non" at "http://dl.bintray.com/non/maven"
Expand Down Expand Up @@ -125,8 +155,8 @@ lazy val cilibSettings = buildSettings ++ commonSettings ++ publishSettings// ++
lazy val cilib = project.in(file("."))
.settings(cilibSettings)
.settings(noPublishSettings)
.aggregate(core, docs, example, exec, ga, moo, pso, tests)
.dependsOn(core, docs, example, exec, ga, moo, pso, tests)
.aggregate(core, de, docs, example, exec, ga, moo, pso, tests)
.dependsOn(core, de, docs, example, exec, ga, moo, pso, tests)

lazy val core = project
.settings(cilibSettings ++ Seq(
Expand All @@ -135,7 +165,8 @@ lazy val core = project
"org.scalaz" %% "scalaz-core" % scalazVersion,
"org.scalaz" %% "scalaz-concurrent" % scalazVersion,
"org.spire-math" %% "spire" % spireVersion,
"com.github.julien-truffaut" %% "monocle-core" % monocleVersion
"com.github.julien-truffaut" %% "monocle-core" % monocleVersion,
"com.chuusai" %% "shapeless" % "2.3.2"
/*),
wartremoverErrors ++= Seq(
//Wart.Any,
Expand Down Expand Up @@ -214,6 +245,9 @@ lazy val pso = project.dependsOn(core)
lazy val ga = project.dependsOn(core)
.settings(Seq(moduleName := "cilib-ga") ++ cilibSettings)

lazy val de = project.dependsOn(core)
.settings(Seq(moduleName := "cilib-de") ++ cilibSettings)

lazy val tests = project
.dependsOn(core)
.settings(cilibSettings ++ noPublishSettings ++ Seq(
Expand Down
6 changes: 3 additions & 3 deletions core/src/main/scala/cilib/Fitness.scala
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ final case object Min extends Opt {
case (Feasible(a), Feasible(b)) => { /*println("in feasible") ;*/ D.order(a, b) }
case (Infeasible(_,_), Adjusted(_,_)) => LT
case (Infeasible(_,_), Feasible(_)) => LT
case (Infeasible(a,as), Infeasible(b,bs)) =>
case (Infeasible(_,as), Infeasible(_,bs)) =>
if (as < bs) LT else if (as > bs) GT else EQ
}

Expand Down Expand Up @@ -129,14 +129,14 @@ final case object Max extends Opt {
case (Feasible(_), Infeasible(_,_)) => GT
case (Infeasible(_,_), Adjusted(_,_)) => LT
case (Infeasible(_,_), Feasible(_)) => LT
case (Infeasible(a, as), Infeasible(b, bs)) =>
case (Infeasible(_, as), Infeasible(_, bs)) =>
if (as < bs) GT else if (as > bs) LT else EQ
}

def objectiveOrder[A] = new Order[Objective[A]] {
def order(x: Objective[A], y: Objective[A]) =
(x, y) match {
case (Single(f1, v1), Single(f2, v2)) => fitCompare(f1, f2)
case (Single(f1, _), Single(f2, _)) => fitCompare(f1, f2)
case (Multi(xs), Multi(ys)) =>
val z = xs.zip(ys)
val x = z.forall { case (a,b) =>
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/scala/cilib/Iteration.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ object Iteration {

def sync_[M[_]:Applicative,A,B](f: List[A] => A => M[B]): Kleisli[M,List[A],List[B]] = //List[A] => M[List[B]] =
// (l: List[A]) => Functor[M].map(l traverseU f(l))(_.suml)
Kleisli.kleisli((l: List[A]) => l traverseU f(l))
Kleisli.kleisli((l: List[A]) => l traverse f(l))

def sync[A,B,C](f: List[B] => B => Step[A,C]) =
sync_[Step[A,?],B,C](f)
Expand Down
8 changes: 4 additions & 4 deletions core/src/main/scala/cilib/Position.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cilib
import scalaz._
import Scalaz._

import spire.algebra.{Module,Ring}
import spire.algebra.{Module,Rng}
import spire.implicits._
import spire.math._

Expand Down Expand Up @@ -95,7 +95,7 @@ object Position {
}

implicit class PositionVectorOps[A](val x: Position[A]) extends AnyVal {
def zeroed(implicit A: Ring[A]): Position[A] =
def zeroed(implicit A: Rng[A]): Position[A] =
x.map(_ => A.zero)

def + (other: Position[A])(implicit M: Module[Position[A],A]): Position[A] =
Expand All @@ -110,7 +110,7 @@ object Position {
def unary_-(implicit M: Module[Position[A],A]): Position[A] =
M.negate(x)

def isZero(implicit R: Ring[A]) = {
def isZero(implicit R: Rng[A]) = {
def test(xs: IList[A]): Boolean =
xs match {
case INil() => true
Expand Down Expand Up @@ -158,7 +158,7 @@ object Position {
RVar.point(x)
}

private[cilib] def apply[A](xs: NonEmptyList[A], b: NonEmptyList[Interval[Double]]): Position[A] =
/*private[cilib]*/ def apply[A](xs: NonEmptyList[A], b: NonEmptyList[Interval[Double]]): Position[A] =
Point(xs, b)

def createPosition[A](domain: NonEmptyList[Interval[Double]]) =
Expand Down
96 changes: 96 additions & 0 deletions de/src/main/scala/DE.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package cilib
package de

import spire.math._
import spire.algebra._
import spire.implicits._

import scalaz._
import Scalaz._
import monocle._
import Monocle._

object DE {

def de[A:Numeric:Rng](
p_r: Double,
p_m: Double,
targetSelection: List[Individual[A]] => RVar[Individual[A]]
//y: N,
//z: Int
): List[Individual[A]] => Individual[A] => Step[A,Individual[A]] =
collection => x => for {
evaluated <- Entity.eval((a: Position[A]) => a)(x)
trial <- Step.pointR(basicMutation(Numeric[A].fromDouble(p_m), targetSelection, collection, x))
pivots <- Step.pointR(bin(p_r, evaluated))
offspring = crossover(x, trial, pivots)
evaluatedOffspring <- Entity.eval((a: Position[A]) => a)(offspring)
fittest <- better(evaluated, evaluatedOffspring)
} yield fittest


// Duplicated from PSO.....
def better[A](a: Individual[A], b: Individual[A]): Step[A,Individual[A]] =
Step.withCompare(comp => RVar.point(Comparison.compare(a, b).apply(comp)))


def basicMutation[A:Rng](
p_m: A,
selection: List[Individual[A]] => RVar[Individual[A]],
collection: List[Individual[A]],
x: Individual[A]): RVar[Position[A]] = {
def createPairs[Z](acc: List[(Z, Z)], xs: List[Z]): List[(Z, Z)] =
xs match {
case Nil => acc
case a :: b :: xss => createPairs((a, b) :: acc, xss)
case _ => sys.error("ugg")
}

val target: RVar[Individual[A]] = selection(collection)
val filtered = target.map(t => collection.filterNot(a => List(t,x).contains(a)))
val pairs: RVar[List[Position[A]]] =
filtered.flatMap(RVar.shuffle)
.map(a => createPairs(List.empty[(Individual[A],Individual[A])], a.take(2))
.map(z => z._1.pos - z._2.pos))

for {
t <- target
p <- pairs
} yield p.foldLeft(t.pos)((a,c) => a + (p_m *: c))
}


def crossover[A](target: Individual[A], trial: Position[A], pivots: NonEmptyList[Boolean]) =
target.copy(
pos = {
target.pos.zip(trial).zip(Position(pivots, trial.boundary)).map { case ((a,b), p) => // Position apply function :(
if (p) b else a
}
})


// This is not a nice implementation ??? -> it feels far too low level and inelegant
def bin[A:Rng](
p_r: Double,
parent: Individual[A]
): RVar[NonEmptyList[Boolean]] =
for {
j <- Dist.uniformInt(spire.math.Interval(0, parent.pos.pos.size - 1))
l <- parent.pos.pos.toList.traverse(_ => Dist.stdUniform.map(_ < p_r))
} yield {
val t: List[Boolean] = l.applyOptional(index(j)).set(true)
NonEmptyList(t.head, t.tail: _*)
}

// def exp[A:Rng](
// p_r: Double,
// parent: Individual[A]
// ): RVar[List[Boolean]] =
// for {
// start <- Dist.uniformInt(0, parent.pos.pos.size - 1)
// length = parent.pos.pos.size - 1
// circular = Stream.continually((0 to length).toList).drop(start).take(length)
// list <-


}
6 changes: 6 additions & 0 deletions de/src/main/scala/package.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package cilib

package object de {

type Individual[A] = Entity[Unit, A]
}
11 changes: 7 additions & 4 deletions docs/src/main/tut/docs/design/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@ without having to worry about the manner in which such an action may be performe
however, true that we do need to worry about the execution semantics at some point so that
the algorithm is executed correctly.

The sections that follow will explain different aspects of CIlib, each required to build the
structure that follows.
The sections that follow will explain different aspects of CIlib, which is a
progression of different types to build up the needed structures.

For all usage samples, the following imports are required within the REPL
session:
session, but will be ignored to favor discussion:

```scala
import scalaz._
import Scalaz._

```tut:
import cilib._
```
6 changes: 3 additions & 3 deletions example/src/main/scala/cilib/example/QuantumPSO.scala
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ object QuantumPSO extends SafeApp {

f match {
case Adjusted(_,_) => sys.error("???? HOW??")
case a @ Feasible(_) => e//sys.error("Asdasd")
case Feasible(_) => e//sys.error("Asdasd")
case i @ Infeasible(_,_) =>
(_position[S,Double] composeOptional _singleFitness[Double]).modify((x: Fit) =>
i.adjust(v => opt match {
Expand Down Expand Up @@ -174,7 +174,7 @@ object QuantumPSO extends SafeApp {

object MPB {

def initialPeaks(s: Double, domain: NonEmptyList[spire.math.Interval[Double]]): RVar[NonEmptyList[Problems.PeakCone]] =
def initialPeaks(/*s: Double,*/ domain: NonEmptyList[spire.math.Interval[Double]]): RVar[NonEmptyList[Problems.PeakCone]] =
Problems.initPeaks(5, domain)//(1 to 2).toList.traverse(_ => Problems.defaultPeak(domain, s))

def iteration(
Expand All @@ -186,7 +186,7 @@ object QuantumPSO extends SafeApp {
}

import scalaz.StateT
def mpb(heightSeverity: Double, widthSeverity: Double): StateT[RVar, (NonEmptyList[Problems.PeakCone],List[cilib.Entity[cilib.example.QuantumPSO.QuantumState,Double]]), Eval[Double]] =
def mpb(/*heightSeverity: Double, widthSeverity: Double*/): StateT[RVar, (NonEmptyList[Problems.PeakCone],List[cilib.Entity[cilib.example.QuantumPSO.QuantumState,Double]]), Eval[Double]] =
StateT { case (peaks, pop) => {
val newPeaks: RVar[NonEmptyList[Problems.PeakCone]] = RVar.point(peaks)//.traverse(_.update(heightSeverity, widthSeverity))
newPeaks.map(np => ((np, pop), Problems.peakEval(np).constrainBy(EnvConstraints.centerEllipse)))
Expand Down
2 changes: 1 addition & 1 deletion project/build.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
sbt.version=0.13.13
sbt.version=0.13.15
2 changes: 1 addition & 1 deletion pso/src/main/scala/cilib/pso/Heterogeneous.scala
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ sealed abstract class PoolItem[A] {
}

def change(a: A) = this match {
case PoolItemR(i, s) => PoolItemR(a, s)
case PoolItemR(_, s) => PoolItemR(a, s)
case _ => this
}
}
Expand Down

0 comments on commit 6d6f306

Please sign in to comment.