Algorithm Optimisation Championship. - page 53

 
Andrey Dik:

Test script on the first version of the algorithm:

For such a simple function, you have overcomplicated the interface. A lot of unnecessary exports, while the necessary things are missing. I cannot understand your code right away, I can imagine how people who are not so good at programming feel.

Now I will think and propose my own version of simplified export and test script operation.

 

Perhaps the "evolutionary" approach of finding values of the FF equation parameters is not so much for the purpose of improving the efficiency of finding values, but rather for software modelling the process of evolution.

Well, as evolution is represented by scientists...

The approach is very consistent in its conformity to all evolutionary canons...

 

Proposition:

1. a fitness function takes an array of parameters of type double and returns a number the larger the better the parameters are chosen. The fitness function prototype is as follows:

double FF(double &array[]);

2. The fitness function has some parameters, which are specified in the FitnessParams structure. A description of the structure is given below:

//+------------------------------------------------------------------+
//| Параметры фитнес-функции (FF)                                    |
//+------------------------------------------------------------------+
struct FitnessParams
{
   int      limit_runs;          // Максимально допустимое количество вызовов FF
   int      count_params;        // Количество параметров, которое необходимо оптимизировать
   int      current_runs;        // Текущее количество вызовов функции
   double   current_max_value;   // Текущее найденное максимальное значение
   double   step_value;          // Минимальный шаг изменения параметра. 
   double   max_value;           // Максимальное значение, которое может принимать параметр
   double   min_value;           // Минимальное значение, которое может принимать параметр
   FitnessParams(void);
};
//+------------------------------------------------------------------+
//| Инициализация параметров фитнес-функции (FF) по-умолчанию        |
//+------------------------------------------------------------------+
FitnessParams::FitnessParams(void) : limit_runs(1000),
                                   count_params(2),
                                   step_value(0.1),
                                   max_value(10.0),
                                   min_value(-10.0),
                                   current_runs(0)
                                   
{
   current_max_value = min_value;
}

3. The fitness function and its parameters are protected from external influence and are stored in an independent library..\\Scripts\\\FF\\FF.ex5. The values of the parameters of the fitness function and its algorithm itself are set at the time of compilation by an independent referee and can no longer be changed by anyone.

4. A custom optimization algorithm and a checking script can find parameters of a fitness function. For this purpose file Export.mqh contains necessary prototypes of this function and its parameters. In order to obtain FF parameters, the export function, which is also located in ...\\Scripts\\\FF\\FF.ex5, is used:

void   GetFitnessParams(FitnessParams& params);

5. The user optimization algorithm is located in a separate, closed user library..\Scripts\\\FF\\UserFindExtremum.ex5 and is compiled separately, on the user side. The FindExtremum function must be exported to the user library. This function will be called by the checking script. The full prototype of the function is given below:

//+------------------------------------------------------------------+
//| Экспорт пользовательской библиотеки поиска экстремума            |
//+------------------------------------------------------------------+
#import "..\\Scripts\\FF\\UserFindExtremum.ex5"
   void FindExtremum(void);
#import

6. The checking script loads to its address space the library of the fitness function ..\\Scripts\\\FF\\FF.ex5 with its parameters, and the library of the Find Extremum member..\Scripts\\\FF\UserFindExtremum.ex5. After that it calls the FindExtremum member function.

7. after the participant function has been executed, the checking script queries the parameters of the fitness function, which contain the maximum value found by the participant function and the number of calls it took to find that maximum. Based on this data, a report of the participant's result is generated in the form of a table:

2016.06.22 13:09:48.583 TestFF (EURUSD,H1)      ———————————————————————————————————————————
2016.06.22 13:09:48.583 TestFF (EURUSD,H1)      Максимальное найденное значение: 3.1
2016.06.22 13:09:48.583 TestFF (EURUSD,H1)      Досрочное выполнение алгритма: НЕТ
2016.06.22 13:09:48.583 TestFF (EURUSD,H1)      Вызовов фитнес-функции потребовалось: 1001
2016.06.22 13:09:48.583 TestFF (EURUSD,H1)      Поиск экстремума выполнен за 0 мсек.

The following post will append the necessary files and a usage example

 

Export.mqh file - a list of available functions and parameter structure common to all participants

//+------------------------------------------------------------------+
//|                                                       Export.mq5 |
//|                                 Copyright 2016, Vasiliy Sokolov. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, Vasiliy Sokolov."
#property link      "https://www.mql5.com/ru/users/c-4"
//+------------------------------------------------------------------+
//| Параметры фитнес-функции (FF)                                    |
//+------------------------------------------------------------------+
struct FitnessParams
{
   int      limit_runs;          // Максимально допустимое количество вызовов FF
   int      count_params;        // Количество параметров, которое необходимо оптимизировать
   int      current_runs;        // Текущее количество вызовов функции
   double   current_max_value;   // Текущее найденное максимальное значение
   double   step_value;          // Шаг значений или дискретность. 
   double   max_value;           // Максимальное значение, которое может принимать ff-функция
   double   min_value;           // Минимальное значение, которое может принимать ff-функция
   FitnessParams(void);
};
//+------------------------------------------------------------------+
//| Инициализация параметров фитнес-функции (FF) по-умолчанию        |
//+------------------------------------------------------------------+
FitnessParams::FitnessParams(void) : limit_runs(1000),
                                   count_params(2),
                                   step_value(0.1),
                                   max_value(10.0),
                                   min_value(-10.0),
                                   current_runs(0)
                                   
{
   current_max_value = min_value;
}
//+------------------------------------------------------------------+
//| Экспорт библиотеки фитнесс-функций                               |
//+------------------------------------------------------------------+
#import "..\\Scripts\\FF\\FF.ex5"
   double FF(double &array[]);                       // Фитнес-функция, возвращающая значение тем больше, чем лучше подобраны значения в массиве array
   void   GetFitnessParams(FitnessParams& params);   // Возвращает параметры фитнесс-функции в виде структуры FitnessParams
#import
//+------------------------------------------------------------------+
//| Экспорт пользовательской библиотеки поиска экстремума            |
//+------------------------------------------------------------------+
#import "..\\Scripts\\FF\\UserFindExtremum.ex5"
   void FindExtremum(void);
#import

FF.mq5 file - example of a fitness function as a library.

//+------------------------------------------------------------------+
//|                                                           FF.mq5 |
//|                                 Copyright 2016, Vasiliy Sokolov. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, Vasiliy Sokolov."
#property link      "https://www.mql5.com/ru/users/c-4"
#property library
#property strict
#include "Export.mqh"
//+------------------------------------------------------------------+
//| Параметры фитнесс-функции, с которыми необходимо ознакомится     |
//| алгоритму поиска до начала работы. Получить эти параметры можно  |
//| с помощью функции GetFitnessParams                               |
//+------------------------------------------------------------------+
static FitnessParams FParams;
//+------------------------------------------------------------------+
//| Фитнес-функция, возвращающая значение тем больше, чем лучше      |
//| подобраны значения в массиве array                               |
//+------------------------------------------------------------------+
double FF(double &array[]) export
{ 
   if(FParams.current_runs > FParams.limit_runs)
      return FParams.min_value;
   FParams.current_runs++;
   if(ArraySize (array) < FParams.count_params)
      return FParams.min_value; 
   double ff_value = (-(pow (2.4 + array [0], 2.0) + pow (array [1] - 2.3, 2.0))+3.1415926);
   if(ff_value > FParams.current_max_value)
      FParams.current_max_value = ff_value;
   return ff_value;
}
//+------------------------------------------------------------------+
//| Возвращает параметры фитнесс-функции                             |
//+------------------------------------------------------------------+
void GetFitnessParams(FitnessParams& params)export
{
   params = FParams;
}
//+------------------------------------------------------------------+

TestFF.mq5 file - checking algorithm as a script

//+------------------------------------------------------------------+
//|                                                       TestFF.mq5 |
//|                                 Copyright 2016, Vasiliy Sokolov. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, Vasiliy Sokolov."
#property link      "http://www.mql5.com"
#property version   "1.00"
#include "Export.mqh"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
{
   uint begin_tiks = GetTickCount();
   // Вызываем пользовательскую функцию поиска экстремума фитнес-функции
   FindExtremum();            
   uint end_tiks = GetTickCount();
   // Получаем результаты поиска в качестве комплексного параметра
   FitnessParams params;      
   GetFitnessParams(params);
   // Подготавливаем отчет
   string yesno_count = params.current_runs >= params.limit_runs ? "НЕТ" : "ДА";
   printf("Поиск экстремума выполнен за " + (string)(end_tiks - begin_tiks) + " мсек.");
   printf("Вызовов фитнес-функции потребовалось: " + (string)params.current_runs);
   printf("Досрочное выполнение алгритма: " + yesno_count);
   printf("Максимальное найденное значение: " + DoubleToString(params.current_max_value, 1));
   printf("——————————————————————");
}
//+------------------------------------------------------------------+

UserFindExtremum.mq5 file - custom function for search of an extremum in the form of a library. A random search is used as an example

//+------------------------------------------------------------------+
//|                                             UserFindExtremum.mq5 |
//|                                 Copyright 2016, Vasiliy Sokolov. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, Vasiliy Sokolov."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property library
#property strict
#include "Export.mqh"
//+------------------------------------------------------------------+
//| Алгоритм поиска экстремума, который будет вызван проверяющим    |
//| скриптом                                                         |
//+------------------------------------------------------------------+
void FindExtremum(void)export
{
   FitnessParams params;
   while(params.current_runs < params.limit_runs)
   {
      GetFitnessParams(params);
      if(params.current_max_value >= params.max_value)
         break;
      double values[];
      ArrayResize(values, params.count_params);
      for(int i = 0; i < params.count_params; i++) 
      {
        double random = RandomDouble(params.min_value, params.max_value);
        values[i] = SeInDiSp (random, params.min_value, params.max_value, params.step_value);
      }
      FF(values);
   }
}
//+------------------------------------------------------------------+
//| Выбор в дескретном пространстве                                  |
//+------------------------------------------------------------------+
double SeInDiSp (double in, double inMin, double inMax, double step) 
{ 
  if(in <= inMin) 
    return (inMin); 
  if(in >= inMax) 
    return (inMax); 
  if(step == 0.0) 
    return (in); 
  else 
    return (inMin + step * (double)MathRound ((in - inMin) / step));
}

//+------------------------------------------------------------------+
//| ГСЧ в заданном интервале                                         |
//+------------------------------------------------------------------+
double RandomDouble(double min, double max) 
{ 
   if(min == max) 
     return (min); 
   double Min, Max; 
   if(min > max) 
   {
     Min = max; 
     Max = min;
   }
   else 
   {
     Min = min; 
     Max = max;
   }
   return (double(Min + ((Max - Min) * (double)MathRand () / 32767.0)));
}
Files:
Export.mqh  3 kb
FF.mq5  2 kb
TestFF.mq5  2 kb
 
Vasiliy Sokolov:

Export.mqh file - a list of available functions and parameter structure common to all participants

FF.mq5 file - example of a fitness function as a library.

TestFF.mq5 file - checking algorithm as a script

UserFindExtremum.mq5 file - custom function for search of an extremum in the form of a library. A random search is used as an example

All the examples are very clear and understandable. Thank you very much for your work. )
 
Vasiliy Sokolov:

For such a simple function, you have overcomplicated the interface. A lot of unnecessary exports, while the necessary things on the contrary are missing. I haven't understood your code at the first attempt, I can imagine what people who are not so good at programming feel.

I will think about it and propose my own version of simplified export and test script.

Why is it not necessary?

What kind of things are missing?

After all, not just to make life as difficult as possible for the participants so I did it all, and not the first day I thought about it all, and not even the second.

 
Andrey Dik:

Why not the right ones?

Which ones are missing?

After all, not just to make life as difficult as possible for the participants so I did everything, and not the first day I thought about it all, and not even the second.

Andrew, I do not know about others, but personally, I liked the example of Vasily more. No offense. This is just my subjective perception.

To be fair, I propose to put the question about the choice of connection interface (yours or Vasiliy's) to a vote.

What do you think?

 
Реter Konow:

Andrew, I don't know about others, but personally, I liked Vasily's example better. No offence. It's just my subjective perception...

To be fair, I propose to put the question of choosing a connection interface (yours or Vasiliy's) to a vote.

What do you think?

What exactly do you like better?
And Vassily's example to the second type of connection, and where on the first?
 
Andrey Dik:

Why not the right ones?

Which ones are missing?

It's not just to make life as difficult as possible for the participants that's how I did it, and it wasn't the first day I thought about it, or even the second.

In your example, the task of searching is partially delegated to the checker script. This is incorrect. The checker script should call the search and check the result and nothing else.

Not all FF parameters are available. For example, how to get the parameter step (value 0.1), possible maximum and minimum? It's great, of course, that every user should read this forum and understand that the step turns out to be 0.1, the minimum -10.0 and the maximum +10.0, then enter these constants into his code and hope that the FF function thinks the same way. But this is not the way to do it in a good way.

Many export functions like ServiceFunc1 are only used in specific search algorithms. For example they should not be used in random search. So why should a user library export them? It's enough to separate the testing task from the search task to realize that all this complicated combination of export functions is unnecessary.

There are many more things that make add-ons unnecessary.

 
Andrey Dik:
What exactly do you like better?
And Basil's example of the second type of connection, and where on the first?
You don't need the second, third, 110 connection type. You only need one, but a universal connection type. Without using unnecessary syntactic constructions. Nobody wants to puzzle over the abbreviated meaning of the ServiceFunc1 function. Instead one should give a fitness function and rules of filling its parameters. And nothing else.
Reason: