!***********************************************************************************
! Modul Simul_Famous is the main fortan module used to generate simulated          !
! data to learn how to use FAMOUS or to investigate properties of the              !
! time sampling and frequency analysis                                             !
! This software is offered without warranty of any kind, either expressed          !
! or implied.  The author would appreciate, however, any reports of bugs           !
! or other difficulties that may be encountered.                                   !
!                                                                                  !
! Author : F. Mignard, OCA/Cassiopee                                               !
! francois.mignard@obs-nice.fr                                                     !
!***********************************************************************************
! 
! Version : 18/04/05 - replaces previous of 28/03/05
! Version : 11/07/05 - replaces previous of 18/04/05
!***************************************************
!
!*********************
  module  simul_famous
!*********************

   real(kind=8), parameter :: pi        = 3.141592653589793238462643d0
   real(kind=8), parameter :: deupi     = 6.283185307179586476925286d0

!
! Dedicated routines to simulate quasi periodic series
! this can be used to practice with FAMOUS 
! but also to get  insights with purposedly built series on the properties 
! of the time sampling in frequency mapping 
!
! There are three kinds of routines designed to generate various signals :
!
! - 1 -
!
!  signal_nominal(n,x,y) 
!                  generate n data points sampled at x(k) with values y(k)
!                  typically y =  Sum of a*cos(omega*x) 
!                  Purpose : test the properties of the application
!                            test the aliasing effect with regular and non regular sampling
!                            test the period recovery according to noise and sampling
!                            test the ability to recover high-frequency signal with irregular sampling
!                            test the resolution in frequency for closely packed lines
!                  Sampling in x can be regular, uniform random, Poisson random, Gaia like.
!                  noise can be added.
!                  Setting : list of parameters in the routine to be set up by the user
!
! - 2 -
!
! signal_lines(n,x,y)
!                  read a list of amplitudes and frequencies in a file
!                  and then generates the corresponding quasi periodic signal y(k)
!                  over the time sampling x(k) 
!                  Purpose : test the effect of the noise in the recovery of a complex signal
!                          : test the spectral analysis of a complex quasi periodic signal with a large dynamics in the frequencies and amplitudes
!                  main  use : synthetic theories in celestial mechanics from numerical integration
!                  Sampling in x can be regular, uniform random, Poisson random, Gaia like.
!                  noise can be added.
!                  Setting : list of parameters in the routine to be set up by the user
! - 3 -
!
!  signal_time(n,x,y)
!                  reads a time sampling in a file (x(k)) and samples the signal accordingly
!                  a quasi-periodic signal on this window.
!                  Purpose : test the spectral properties of an observation window.
!                          : test the recovery of variable stars for a given time sampling
!                  noise can be added.
!                  Setting : list of parameters in the routine to be set up by the user
contains
!***************************************************************
   Subroutine signal_nominal(npts,x,y)
!***************************************************************
!
!     Simulation of lines with given frequencies and amplitudes
!     to generate a signal y(k) sampled at x(k)
!     Periods are filled in the code. The model is given explicitely and
!     must be customized by the user. 
!
!     Four time samplings are available :
!     - sampling at regular step : n samples, one every tau
!     - uniform, but random sampling over the interval
!     - Gaia-like with short term repetition and gaps between epochs
!     - Poisson sampling (exponential waiting time) over the interval
! 
!     The interval covers alpha times the basic period p1.
! 
!     Time and signal are stored in x and y
! 
!     A gaussian noise can be added to the deterministic signal
! 
!     Users of this routine must adapt the parameters to their own needs.
! 
!     F. Mignard  OCA/Cassiopee   
!
!*INPUT
!           npts       : number of data points 
!        
!*OUTPUT
!           X[npts]    : Array with the independant variable (nominally : time)
!           Y[npts]    : Array with the data points y_i
!
!*EXTERNAL
!           no external called
!****************************************************************************
!
      implicit none
      integer,      intent(in)   :: npts
      real(kind=8), intent(out)  :: x(*), y(*)

!
!     user_defined : alpha, sigma, range, isample
! 
!      real(kind=8), parameter    :: alpha   = 152.315d0      ! number of periods covered by the sampling
      real(kind=8), parameter    :: alpha   =  80.000d0      ! number of periods covered by the sampling
      real(kind=8), parameter    :: sigma   = 0.0000d0        ! standard deviation used to add a gaussian noise to the signal
      real(kind=8), parameter    :: range   = 0.5d0          ! fractional random perturbation of the length of the intervals to general Gaia-like sampling  (must be < 1 and > 0)
      integer,      parameter    :: isample = 1              ! kind of sampling (1: regular, 2: uniform random, 3 : gaia-like, 4: poisson)
 
      integer                    :: ind(npts), iseed, k
      real(kind=8)               :: tau, p1, p2, p3, p4
      
      iseed = 2*int(10000*secnds(0d0))+1 

!
!     user_defined : the periods below, according to the analytic signal near the bottom
! 
      
      p1 = 125.0d0               ! fundamental period
      p2 = 7500d0
      p3 = 2.0d0
      p4 = 1.0d0

      tau = alpha*p1/npts       !mean timestep 
      do k = 1, npts
         select case (isample)
         case(1) 
!
!     regular sampling
!
            x(k) = (k-0.5d0)*tau

         case(2) 
!
!     uniform random sampling over the interval
!
            x(k) = alpha*p1*rand(iseed)            
              
         case(3) 
!
!      slight random sampling with random interval having tau as expectation and width range*tau
!      and large random intervals at random epochs ( ~ Gaia situation for photometry}
!
            if(k==1) then
               x(k) = 0d0
            else
               x(k) =  x(k-1) +  tau*((1 - range/2d0) +range*rand(iseed)) 
               if( modulo(k, int(100d0*rand(iseed))+5) == 0) then       ! large intervals
                  x(k) =   x(k) + (50d0*tau*rand(iseed)) 
               endif         
            endif

         case(4) 
!
!     Poisson sampling (exponential waiting time) or bounded Poisson sampling
!

            if(k.eq.1) then                          
               x(k) =0d0
            else
               x(k) = x(k-1) + max(0.3*tau, -tau*log(rand(iseed)))  ! to avoid too small intervals between two consecutive samples
            endif

         end select
      enddo
      call quicksort(npts,x,ind)  ! sorting in increasing order the time sampling
!
!     user_defined : Generation of the signal.  User must adapt to his fancy
!
      do k = 1,npts  
         y(k) =   2.5d0*cos(deupi/p1*x(k)) - 0.5d0*sin(deupi/p1*x(k))      &
                + 2.5d0*cos(deupi/p2*x(k)) - 0.5d0*sin(deupi/p2*x(k))      &
                + 0.5d0*cos(deupi/p3*x(k)) - 0.3d0*sin(deupi/p3*x(k))      &
                + 1.0d0*cos(deupi/p4*x(k)) + 2.0d0*sin(deupi/p4*x(k))

          y(k)  =  1d0*cos(deupi/p1*x(k)) + 1d0*cos(deupi/p2*x(k))

         y(k)  = gauss(y(k), sigma,iseed)         ! gaussian noise - no noise with sigma = 0d0
      enddo
      return
      end subroutine signal_nominal
         
!***********************************************************************************
      subroutine signal_lines(npts,x,y)
!***********************************************************************************
!
!     Read on an external unit a list of amplitudes, phases and frequencies
!     to generate a signal y(k) sampled at x(k)
! 
!     Time and signal are stored in x and y
!     Number of data points is limited by the storage allocation of x and y
!     set in the main program.
!     actual nfreq is min(nfreq,nrecord) nrecord : number of records in the file
!
!     Four time samplings are available :
!     - sampling at regular step : n samples, one every tau
!     - uniform, but random sampling over the interval
!     - Gaia-like with short term repetition and gaps between epochs
!     - Poisson sampling (exponential waiting time) over the interval
! 
!     Time and signal are stored in x and y
! 
!     A gaussian noise can be added to the deterministic signal
! 
!     
!     F. Mignard  OCA/Cassiopee   
!
!*INPUT
!           NPTS    : number of data points
!*OUTPUT
!           X[npts] : Array with the independant variable (nominally : time)
!           Y[npts] : Array with the data points y_i
!
!*EXTERNAL
!           no external called
! 
!***********************************************************************************
      implicit none
      integer,      intent(in)       :: npts
      real(kind=8), intent(out)      :: x(*), y(*)

!
!     user_defined : nfreq, tmax, sigma, range, isample
!  
      integer,      parameter        :: nfreq   = 10             ! control the number of frequencies in the generated signal. Could be less than the records of the file. If larger min(nrec,nfreq) is used.
      real(kind=8), parameter        :: tmax    = 2000d0         ! duration in unit of time used for the frequencies
      real(kind=8), parameter        :: sigma   = 0.500d0        ! standard deviation used to add a gaussian noise to the signal
      real(kind=8), parameter        :: range   = 0.5d0          ! fractional random perturbation of the length of the intervals to general Gaia-like sampling  (must be < 1 and > 0)
      integer,      parameter        :: isample = 1              ! kind of sampling (1: regular, 2: uniform random, 3 : gaia-like, 4: poisson)

      integer,      parameter        :: iunit   = 99             ! unit opened for the input file

      integer                        :: ind(npts), iseed, k, j, mfreq
      real(kind=8)                   :: tau, sum
      real(kind=8), dimension(nfreq) :: amp, phase, xnu
      
      iseed = 2*int(10000*secnds(0d0))+1 

      tau    = tmax/npts
        
!
!     Load of the lines  (amplitudes, phases, frequencies)
!     name, and data columns to be adapted by the user
!     user_defined : filename and record structure
!
      open(unit = iunit, file ='myfile.txt', status ='old')

      do k = 1, nfreq
         read(iunit,*,end=100) amp(k), phase(k), xnu(k)
      enddo
      close(iunit)

100   continue
      mfreq = k-1    ! actual number of frequencies <= nfreq . Allows for the end of file before nfreq

!
!     time sampling
!
      do k = 1, npts
         select case (isample)
         case(1) 
!
!     regular sampling
!
            x(k) = (k-0.5d0)*tau

         case(2) 
!
!     uniform random sampling over the interval
!
            x(k) = tmax*rand(iseed)            
              
         case(3) 
!
!      slight random sampling with random interval having tau as expectation and width range*tau
!      and large random intervals at random epochs ( ~ Gaia situation for photometry}
!
            if(k==1) then
               x(k) = 0d0
            else
               x(k) =  x(k-1) +  tau*((1 - range/2d0) +range*rand(iseed)) 
               if( modulo(k, int(100d0*rand(iseed))+5) == 0) then       ! large intervals
                  x(k) =   x(k) + (50d0*tau*rand(iseed)) 
               endif         
            endif

         case(4) 
!
!     Poisson sampling (exponential waiting time) or bounded Poisson sampling
!

            if(k.eq.1) then                          
               x(k) =0d0
            else
               x(k) = x(k-1) -tau*log(rand(iseed))
!               x(k) = x(k-1) + max(0.3*tau, -tau*log(rand(iseed)))     ! too avoid too small interval
            endif

         end select
      enddo
      call quicksort(npts,x,ind)  ! sorting in increasing order the time sampling

!
!  signal sampled at x(k)
!
      do k = 1, npts
         sum = 0d0
         
         do j = 1, mfreq
            sum = sum + amp(j)*cos(xnu(j)*x(k)/1000d0+phase(j))
         enddo
!
!     signal
!
         y(k) = sum
        

         y(k)  = gauss(y(k), sigma,iseed)    ! gaussian noise
      enddo

      return
      end  subroutine signal_lines
!***********************************************************************************
      subroutine signal_time(npts,x,y)
!***********************************************************************************
!
!     Action : Load a time window and adjust the data in the array Y.
!     Purpose: Testing a white noise or a simulated periodic signal
!             with the same time window as the signal to be analysed.
!             This allows to characterize the effect of the window on the results.
!  
!     Read on an external unit, column number ncolx stored in x,
!     The external unit is assumed to be open for reading
!     It is closed after all data are read.
!     Number of data points is limited by the storage allocation of x
!     set in the main program, but loosely protected.
!     The signal must be customized by the user.
!     
!     F. Mignard  OCA/Cassiopee   
!
!*OUTPUT
!           NPTS    : number of data points
!           X[npts] : Array with the independant variable (nominally :time)
!           Y[npts] : Array with the data points y_i
!
!*EXTERNAL
!           no external called
! 
!***********************************************************************************
! 
      implicit none

      integer,      intent(inout)  :: npts

!
!     user_defined : sigma, period
! 
      real(kind=8), parameter   :: sigma  = 0.0002d0     ! standard deviation of the white noise
      real(kind=8), parameter   :: period = 3d0
      real(kind=8)              :: x(*), y(*)

      integer,      parameter   :: iunit   = 99        ! unit opened for the input file
      integer,      parameter   :: ncolx   = 1         ! column with the time sampling in the file

      integer                   :: iseed, k, i, nrec
      real(kind=8)              :: p1, p2, p3, p4, p5, xxx


      iseed  = 2*int(10000*secnds(0d0))+1 
      iseed  = 123

!
!     user defined  : list of periods :: to be adapted to user needs
!    
      p1 = 5000d0
      p2 = 500d0
      p3 = 90000d0
      p4 = 55000d0
      p5 = 160000d0
!
!
!     Load of the reference time sampling
!     name, and data column to be adapted by the user
!

      open(unit =iunit, file ='gps_sampling.txt', status ='old')

      call numrec(iunit, nrec)   ! how many records in the input file (time sampling data)
      npts     = min(npts, nrec) ! must be <= npts given in the settings and <= number of records

 10   continue
      do k = 1, npts   

         read(iunit,*,end=100) (xxx,i=1,ncolx)
         x(k) = xxx
!
!     user_defined : Generation of the signal.  User must adapt to his fancy
!

         y(k) = 1d0 + 1.0d0*cos(deupi/p1*x(k)) + 2.0d0*sin(deupi/p1*x(k))+ &
                      1.0d0*cos(deupi/p2*x(k)) + 1.5d0*sin(deupi/p2*x(k))+  &    
                      0.5d0*cos(deupi/p3*x(k)) - 0.5d0*sin(deupi/p3*x(k))+  &
                      0.5d0*cos(deupi/p4*x(k)) - 0.1d0*sin(deupi/p4*x(k))

         y(k)  =  2*cos(deupi/p1*x(k))+ 1.5*cos(deupi/p2*x(k))+ 10*cos(deupi/p3*x(k))+ 8*cos(deupi/p4*x(k))+ 0.7*cos(deupi/p5*x(k))
!         y(k)  =  4*cos(deupi/p1*x(k))+ 1.5*cos(deupi/p2*x(k))
!         y(k)  = 1d0

         y(k) = gauss(y(k), sigma,iseed)    ! gaussian noise or introduce your signal

       enddo
 100  continue
      close(iunit)
      return
      end subroutine signal_time
!**************************************************************************
      function secnds(x)
!**************************************************************************
!     This function returns the elapsed time since the time x
!     x : number of seconds since 0h in the system clock
!     seconds(0.0d0) : number of seconds elapsed since 0h of the system clock
!     accuracy : 0.001 s
!
!     F. Mignard  OCA/Cassiopee
!     20 March 2005
!
!     INPUT
!        x     : time offset since 0h in seconds
!
!     OUTPUT
!     seconds  : elapsed time since x in seconds
!
!***************************************************************************
      implicit none

      integer,   parameter      :: dp        = selected_real_kind(12, 60)
      integer,   dimension(8)   :: ivalues
      real(kind=dp)             :: secnds, x

      call date_and_time(values=ivalues)

      secnds = 3600d0*ivalues(5)+60d0*ivalues(6)+ivalues(7) +0.001d0*ivalues(8) - x

      return
      end function secnds
!*************************************************************************
!**************************************************
    function rand(iseed)
!**************************************************
!   random number generation
!   same interface as f77 ran(iseed) and F90 compatible
!   
!   F. Mignard  18/04/05
!
!   Input/ouptut
!       iseed   : current seed  integer(4)
!
!   Output
!       rand    : uniform rando number ]0,1[ double precision
!
!***************************************************

      implicit none

      integer,       parameter     :: dp    = selected_real_kind(12, 60)
      integer, save                :: id                    ! size of the random seed array
      logical, save                :: first = .true.        ! first is a 'save' variable and its value is saved at each call (f90 property)
      integer                      :: k, iseed
      integer, save, allocatable   :: seed(:)
      real(kind=dp)                :: rand

      if(first) then                                    ! initialisations at the first call
         first   = .false.        
         call random_seed(SIZE = id)                    ! determine the size of the seed array
         allocate(seed(id))
      endif

      do k = 1, id
         seed(k) = iseed + 2*(k-1)                      ! load the seed array. (outside the if loop to allow reinitialisation during a run)
      enddo

      call random_seed(put = seed(1:id))                ! load the random seed in the generator
      call random_number(rand)                          ! random number
      call random_seed(get = seed(1:id))                ! update iseed for the routine

      iseed  = seed(1)

      return
      end  function rand
!***********************************************************
      function gauss(aver,sigma,iseed)
!***********************************************************
!     Drawing of a gaussian random variable N(aver, sigma)
!
!     F. Mignard  OCA
!     Version 1 September 1991
!     Proteced against  rand(i) = 0 ( September 99)
!     method  : Kinderman - Monahan
!     Ref :: nuth : the art of computer programming vol . 2
!     Mistake in the Knuth algortihm corrected in this  programme
!
!     INPUT
!        aver   :: E(X)
!        sigma  :: Standard deviation 
!        iseed  :: odd integer to start the random generator
!
!     OUTPUT
!        gauss  :: result of the drawing
!
!
!        iseed is updated at each call of rand(.)
!
!     coef = sqrt(8/exp(1))
!***********************************************************
! 
      implicit none
       
      real(kind=8), intent(in)   :: aver, sigma
      integer     , intent(in)   :: iseed
       
      real(kind=8)               :: gauss
       
      real(kind=8), parameter    :: coef =  1.71552776992141d0

      real(kind=8)               :: u, v,x
       
10    continue
         u = rand(iseed)
         v = rand(iseed)
 
         if (v.gt.0.0) then
            x=  coef*(u-0.5)/v
            if ((x*x).lt.(4*(1.-v))) then
               gauss = sigma*x +aver
            else if((x*x).lt.(-4.*log(v)))  then
               gauss = sigma*x +aver
            else
               go to 10
            endif
         else
            go to 10
         endif

      return
      end function gauss
!***********************************************************
      recursive subroutine quicksort(n, list, order)
!***********************************************************
!
!     The routine sorts the real array x(n) in increasing order
!     with the quicksort algorithm in n*log(n) 
!
!*** INPUT    n     : size of data
!            list   : real array to be sorted
!
!
!*** OUTPUT   list  : sorted array
!            order  : permutation table of the sorting
!
!     list  is altered by the subroutine
!
!     Comment  :   order : sequence of indices 1,...,n
!                          permuted in the same way  as x
!                          would be.  Thus, the ordering on
!                          x is defined by y(i) = x(order(i)).
!************************************************************
! Quicksort routine from:
! Brainerd, W.S., Goldberg, C.H. & Adams, J.C. (1990) "programmer's guide to
! Fortran 90", mcgraw-hill  isbn 0-07-000248-7, pages 149-150.
! modified by Alan Miller to include an associated integer array which gives
! the positions of the elements in the original order.
!***********************************************************

      implicit none

      integer,                    intent(in)     ::  n
      real(kind=8), dimension(n), intent(inout)  ::  list
      integer,      dimension(n), intent(out)    ::  order

      integer :: i

      do i = 1, n
         order(i) = i
      end do

      call quick_sort_1(1, size(list))

      contains

      recursive subroutine quick_sort_1(left_end, right_end)

      integer, intent(in) :: left_end, right_end

      integer             :: i, j, itemp
      real(kind=8)        :: reference, temp

      integer, parameter  :: max_simple_sort_size = 6

      if (right_end < left_end + max_simple_sort_size) then    ! use interchange sort for small lists

         call interchange_sort(left_end, right_end)

      else                                                     ! use partition ("quick") sort
         reference = list((left_end + right_end)/2)
         i = left_end - 1
         j = right_end + 1

         do                                                    ! scan list from left end until element >= reference is found
            do
               i = i + 1
               if (list(i) >= reference) exit
            enddo                                              ! scan list from right end until element <= reference is found
            do
               j = j - 1
               if (list(j) <= reference) exit
            enddo
            if (i < j) then           ! swap two out-of-order elements
               temp = list(i); list(i) = list(j); list(j) = temp
               itemp = order(i); order(i) = order(j); order(j) = itemp
            else if (i == j) then
               i = i + 1
               exit
            else
               exit
            endif
         enddo

         if (left_end < j) call quick_sort_1(left_end, j)
         if (i < right_end) call quick_sort_1(i, right_end)
      endif

      end subroutine quick_sort_1

      subroutine interchange_sort(left_end, right_end)

      integer, intent(in)    :: left_end, right_end
 
      integer                :: i, j, itemp
      real(kind=8)           :: temp

      do i = left_end, right_end - 1
         do j = i+1, right_end
            if (list(i) > list(j)) then
               temp = list(i); list(i) = list(j); list(j) = temp
               itemp = order(i); order(i) = order(j); order(j) = itemp
            endif
         enddo
      enddo

      end subroutine interchange_sort

      end subroutine quicksort
!***********************************************************************************
      subroutine numrec(luin, nrec)
!***********************************************************************************
!
!     read a text file on the unit luin to determine the number of records
!
!     luin   :  logical unit of the file
!     nrec   :  number of records found
!
!***********************************************************************************
      implicit none
      integer  luin, k , nrec
      real     aa

      k = 0
5     continue
         read(luin, *,end=500)  aa   ! useful to read a number to avoid counting empty lines with cr at the end of the file
         k = k+1
      go to 5
500   continue
      nrec = k
      rewind(luin)
      end subroutine numrec
!*************************************************************************
end module simul_famous