-------------------------------------------------------------
-- Generic scheme to deal with Differential Evolution      --
-- The code contains a generic sequential Haskell function --
-- (deeSEQ) as well as a parallel implementation  in       --
-- Eden (dePAR).                                           --
-- Some example functions are also included (but they are  --
-- not exported).                                          --
--                                                         --
-- Created by: A.Encina, P.Rabanal, I.Rodriguez,F. Rubio   --
-- Last modified: April 2016                               --
-------------------------------------------------------------

module DE(deSEQ,                                -- Sequential De scheme
          dePAR,                                -- Parallel version of DE
          Position,Boundings,Params,Candidate   -- Auxiliary types
          ) where
import Control.Parallel.Eden
import Data.List
import Data.Array
import System.Random

{- Uncomment in case Eden is not available
process f = f
f # x = f x
using x y = x-}

----------------------------
-- Basic types to be used --
----------------------------

-- Types and functions dealing with R^n positions
type Position = [Double]            -- Assuming R^n
type Boundings = [(Double,Double)]  -- (Lower,upper) for each dimension


infixl 7 *& 
(*&) :: Double -> Position -> Position
x *& xs = map (x*) xs

infixl 6 -&
(-&) :: Position -> Position -> Position
xs -& ys = zipWith (-) xs ys


infixl 6 +&
(+&) :: Position -> Position -> Position
xs +& ys = zipWith (+) xs ys


-- Parameters
type Params = (Double,Double)      -- (F,CR) Differential weight [0,2], crossover probability [0,1]

-- Candidate: current value, current position
type Candidate = (Double,Position)


----------------------------------
-- Generic DE sequential scheme --
----------------------------------

-- General sequential bees scheme
deSEQ :: RandomGen a => a             -- Random generator
          -> Params                   -- Standard adjustment parameters
          -> Int                      -- Number of candidates to be used
          -> Int                      -- Maximum number of iterations
          -> (Position -> Double)     -- Fitness function
          -> Boundings                -- Search space boundaries 
          -> (Double,Position)        -- Value and position of best fitness
deSEQ sg p nc it f bo = obtainBestCandidate (de' sg2 p it f bo initCandidates)
  where initCandidates :: [Candidate]
        initCandidates = initializeCandidates sg1 nc bo f 
        (sg1,sg2) = split sg

-- Sequential function taking care of the execution of a given number of iterations it
-- of the basic DE algorithm. It is used both from the sequential and parallel schemes.
de' _ _ 0 _ _ cs = cs
de' sg p it f bo cs = de' sg2 p (it-1) f bo newcs 
  where newcs = oneStepDE sg1 p f bo cs
        (sg1,sg2) = split sg

-- Basic sequential function implementing one step of the basic DE algorithm
oneStepDE :: RandomGen a => a -> Params -> (Position -> Double) -> Boundings
               -> [Candidate] -> [Candidate]
oneStepDE sg (dw,cr) f bo cs = zipWith combineCandidate cs rs
 where
   (sg1,sgAux) = split sg
   (sg2,sg3) = split sgAux
   rs :: [((Int,Int,Int),Int,[Double])] -- ((Int,Int,Int),Int,[Double]): ([0..numCandidates-1],[0..numDimensions-1],[0..1])
   rs = genRanIndexDimR sg1 (length cs -1 ) (length bo)
   
   csa = array (0,nelems-1) (zip [0..nelems-1] cs) where nelems= length cs
   combineCandidate c ((ci1,ci2,ci3),dim,crps) = combc' c ncp dim crps
     where nc1 = snd(csa!ci1)
           nc2 = snd(csa!ci2)
           nc3 = snd(csa!ci3)
           ncp = limitRange bo (nc1 +& dw *& (nc2-&nc3))

   combc' (cv,cp) ncp dim crps
     | newcv < cv = (newcv,newcp)
	 | otherwise = (cv,cp)
     where newcp = zipWith4 (combc'' dim) [0..] cp ncp crps
           newcv = f newcp
		   
   combc'' dim index cpi ncpi crp
      | index == dim = ncpi
      | crp > cr = ncpi
      | otherwise = cpi


-- Obtaining random indexes and positions: 3 positions of candidates, 1 dimension, ndim doubles for crossover
genRanIndexDimR :: RandomGen a => a -> Int -> Int -> [((Int,Int,Int),Int,[Double])]
genRanIndexDimR sg numCandidates numDim = zip3 indexss dims rss
  where (sg1,sg2) = split sg
        indexs = randomRs (0,numCandidates) sg
        dims   = randomRs (0,numDim-1) sg1
        rs     = randomRs (0,1) sg2  

        rss = chunking numDim rs	
        indexss = groupsDifferent3 [0..numCandidates] indexs
		
groupsDifferent3 [] _ = []
--groupsDifferent3 (ci:cis) (x:y:z:rests) = (x,y,z): groupsDifferent3 cis rests		
groupsDifferent3 (ci:cis) xs = (a,b,c) : groupsDifferent3 cis rests
  where gd useds (x:xs) 
          | elem x useds = gd useds xs
          | length useds == 4 = (take 3 useds,xs)
          | otherwise = gd (x:useds) xs
        ([a,b,c],rests) = gd [ci] xs

-- Normalizing functions		
normalize :: [Double] -> [Double]
normalize xs = scanl1 (+) (map (/total) xs)
  where total = sum xs
indexNormalized :: [Double] -> Double -> Int
indexNormalized xs x = length (takeWhile (x>) xs) 

                
-- Initialization of candidates				
initializeCandidates sg nc bo f = zip fs pos
  where ndim = length bo
        pos :: [Position] 
        pos = take nc (randomPs (ndim*nc) bo sg)
        fs = map f pos
        
        
obtainBestCandidate :: [Candidate] -> (Double,Position)
obtainBestCandidate cs = minimum cs 


--------------------------------
-- Generic DE parallel scheme --
--------------------------------

-- General parallel DE scheme (version 1)
dePAR :: RandomGen a => a              -- Random generator
           -> Params                   -- Standard adjustment parameters
           -> Int                      -- Number of candidates to be used
           -> Int                      -- Iterations in each parallel step
           -> Int                      -- Number of parallel iterations
           -> Int                      -- Number of parallel processes
           -> (Position -> Double)     -- Fitness function
           -> Boundings                -- Search space boundaries 
           -> (Double,Position)        -- Value and position of best fitness
dePAR sg p nc pit it nPE f bo = obtainBestCandidate (last poutsFlat)
  where initCandidates :: [Candidate]
        initCandidates = initializeCandidates sg nc bo f
        
        sgs = tail (generateSGs (nPE+1) sg)
        
        pouts :: [ [[Candidate]] ] 
        pouts = spawnF [(deP (sgs!!i) p pit f bo) | i<-[0..nPE-1]]   
                       [(take (it+1) (pins!!i)) | i<-[0..nPE-1]]   
        poutsFlat = flatXsss pouts 
        pins = unFlat nPE (initCandidates : poutsFlat)

flatXsss [] = []
flatXsss ([]:_) = []
flatXsss xsss = concat{-Update-} (map head xsss) : flatXsss (map tail xsss)
unFlat np [] = replicate np []
unFlat np (xs:xss) = lzipWith (:) firsts rest
  where firsts = shuffle np xs
        rest = unFlat np xss
{-concatUpdate xss = updateBest best (concat xss)
  where best = maximum (map (global.head) xss)
-}
		
-- Basic process function used by the parallel scheme
deP :: RandomGen a => a 
        -> Params -> Int -> (Position -> Double) -> Boundings
        -> ([[Candidate]] -> [[Candidate]])
deP sg p pit f bo (bs:bss) = de' sg1 p 1 f bo bs : deP2 sg2 p pit f bo bss
  where (sg1,sg2)=split sg
deP2 sg p pit f bo [] = []
deP2 sg p pit f bo (bs:bss)
  = de' sg1 p pit f bo bs : deP2 sg2 p pit f bo bss 
  where (sg1,sg2)=split sg

  
-------------------------
-- Auxiliary functions --
-------------------------  
        
chunking n xs = lf : chunking n rg
  where (lf,rg) = splitAt n xs		
		
shuffle n xs 
  | null dr = take n (map (:[]) iz ++ repeat [])
  | otherwise = zipWith (:) iz (shuffle n dr)
  where (iz,dr) = splitAt n xs

spine [] = ()
spine (x:xs) = spine xs

position (lv,gv,pos,l) = pos
counter (lv,gv,pos,l) = l
value (lv,gv,pos,l) = lv
global (lv,gv,pos,l) = gv
        
limitRange bo xs = zipWith limit1 bo xs
limit1 (l,u) n = min (max n l) u

lzipWith f [] _ = []
lzipWith f (x:xs) ~(y:ys) = f x y : lzipWith f xs ys

fst3 (x,y,z) = x

filter' f [] = ([],[])
filter' f (x:xs)
  | f x = (x:le,ri)
  | otherwise = (le,x:ri)
  where (le,ri) = filter' f xs

generateSGs 0 sg = []
generateSGs 1 sg = [sg]
generateSGs n sg = sg1:generateSGs (n-1) sg2
  where (sg1,sg2) = split sg

randomPs n bo sg = transpose (map (take n) xss')
  where xss = map (flip randomRs sg) bo
        xss' = zipWith drop [0,n..] xss


-------------------------------
-- CONCRETE RUNNING EXAMPLES --
-------------------------------

-- Examples of fitness functions with corresponding boundings. taken from Yao et al 
-- (Evolutionary Programming made faster, IEEE Trans. on Evolutionary Computation)

bo1 = replicate 30 (-100,100)
fit1 xs = sum (map sqr xs)

bo2 = replicate 30 (-10,10)
fit2 xs = sum xs' + (foldr (*) 1 xs')
  where xs' = map abs xs

bo3 = replicate 30 (-100,100)
fit3 xs = sum [sqr (sum ys) | ys <- tail(inits xs)]

bo4 = replicate 30 (-100,100)
fit4 xs = maximum (map abs xs)

bo5 = replicate 30 (-30,30)
fit5 xs = sum (zipWith f xs1 xs)
  where xs1 = tail xs
        f x1 x = 100*sqr (x1-sqr x)+sqr(x-1)

bo6 = replicate 30 (-100,100)
fit6 xs = fromIntegral (sum (map f xs))
  where f x = sqr(floor (x+0.5))
sqr x = x*x

bo8 = replicate 30 (-500,500)
fit8 xs = sum (map fit8' xs)
  where fit8' xi = -xi * sin (sqrt (abs xi))

bo9 = replicate 30 (-5.12,5.12)
fit9 xs = sum (map fit9' xs)
  where fit9' xi = sqr xi - 10*cos(2*pi*xi) + 10

bo10 = replicate 30 (-32,32)
fit10 xs = -20*exp(-0.2*sqrt(sum (map sqr xs)/n')) - exp(sum (map f' xs) / n') + 20 + exp 1
  where n' = fromIntegral (length xs)
        f' xi = cos (2*pi*xi)

bo11 = replicate 30 (-600,600)
fit11 xs = sum (map sqr xs) / 4000 - prod (zipWith f xs [1..]) + 1
  where f x i = cos (x/sqrt i)

prod xs = foldr (*) 1 xs

bo12 = replicate 30 (-50,50)
fit12 xs = (10*sqr(sin (pi*y1))+sum (map f yn1) + sqr(yn-1) )*pi/30 + sum (map fu xs)
   where f y = sqr (y-1)
         y1 = head ys
         yn = last ys
         yn1 = init ys
         ys = map obtainY xs
         obtainY x = 1 + (x+1)/4
         fu x = uf (x,10,100,4)
uf (x,a,k,m) 
           | x > a = k * (x-a)**m
           | x < -a = k * ((-x)-a)**m
           | otherwise = 0

bo13 = replicate 30 (-50,50)
fit13 xs = 0.1*(sqr (sin (3*pi*x1)) + sum (zipWith f xs xs1) + sqr(xn-1)*(1+sqr(sin (2*pi*xn)))   ) + sum (map fu xs)
  where xs1 = tail xs
        x1 = head xs
        xn = last xs
        fu x = uf (x,5,100,4)
        f x xx = sqr (x-1) * (1+sqr(sin(3*pi*xx)))         
         
fit14 [x1,x2] = 1/(1/500 + sum (map f [0..24]))
  where f j = 1 / (fromIntegral j+1 + (x1 - fa1!!j)**6 + (x2 - fa2!!j)**6)
        fa1 = concat (replicate 5 [-32,-16,0,16,32])
        fa2 = concat (map (replicate 5) [-32,-16,0,16,32])
bo14 = replicate 2 (-65536,65536)

fit15 [x1,x2,x3,x4] = sum (zipWith f as bs)
  where f a b = sqr (a-(x1*(sqr b + b*x2)/(sqr b + b*x3 + x4)))
        as = [0.1957,0.1947,0.1735,0.16,0.0844,0.0627,0.0456,0.0342,0.0323,0.0235,0.0246]
        bs = map (1/) [0.25,0.5,1,2,4,6,8,10,12,14,16] 
bo15 = replicate 4 (-5,5)

fit16 [x,y] = 4*x^2 - 2.1*x^4 + (x^6)/3 + x*y - 4*y^2 + 4*y^4
bo16 = [(-5,5),(-5,5)]

fit17 [x,y] = (y - (5.1*x^2/(4*pi^2)) + (5*x)/pi - 6)^2 + 10*(1-1/(8*pi))*cos x +10
bo17 = [(-5,10),(0,15)]

inverseFit :: (Position -> Double) -> (Position -> Double)
inverseFit f x
  | fx < 0    = 1 + abs fx
  | otherwise = 1 / (1+fx)  
  where fx = f x
