IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Algorithmes et structures de données Discussion :

Maximisation à l'aide de l'algorithme des colonies de fourmis


Sujet :

Algorithmes et structures de données

  1. #1
    Membre à l'essai
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    17
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 28
    Localisation : Suisse

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2017
    Messages : 17
    Points : 12
    Points
    12
    Par défaut Maximisation à l'aide de l'algorithme des colonies de fourmis
    Bonjour,

    S'il vous plait j'ai un problème au meta heuristique qui consiste à maximisez la fonction f(x)=x2+y2 ou 1<= x<=15, Avec x+y=7
    mais tout ce que je trouve est sur le voyageur de commerce et je n'arrive pas à trouver le points qui lie entre les deux, et merci

  2. #2
    Membre émérite

    Homme Profil pro
    Formation: Chimie et Physique (structure de la matière)
    Inscrit en
    Décembre 2010
    Messages
    1 333
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 77
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Formation: Chimie et Physique (structure de la matière)
    Secteur : Enseignement

    Informations forums :
    Inscription : Décembre 2010
    Messages : 1 333
    Points : 2 570
    Points
    2 570
    Billets dans le blog
    9
    Par défaut Maximisation à l'aide de l'algorithme de fourmis
    Bonjour,

    Il s'agit apparemment de la recherche d'un parcours optimal sur un domaine donné, par un processus aléatoire ...

    Pourrais-tu nous donner des précisions sur le procédé en cause, et fournir un aperçu du code que tu as pu mettre sur pied ?
    D'autant que le règlement du forum n'autorise pas de donner suite à des demandes du genre
    Citation Envoyé par axelim Voir le message
    ... S'il vous plait j'ai un problème ...
    PS: Avec x + y = 7 , le chemin serait tout tracé, et l'énoncé court-circuité ... ne s'agirait-il pas plutôt de la frontière imposée au domaine ? (x + y) <= 15 , par exemple ?


    Le français, notre affaire à tous
    Grand Dictionnaire Terminologique

  3. #3
    Membre à l'essai
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    17
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 28
    Localisation : Suisse

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2017
    Messages : 17
    Points : 12
    Points
    12
    Par défaut
    voici un petit essai que j'ai pu faire mais j'arrive pas à faire le main
    Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    package test1;
     
     
    import java.util.*;
    import java.util.stream.Collectors;
     
     
    public class Ant {
        private static Random rnd = new Random();
     
        private double distance;
        private List<Integer> order;
     
        public Ant(double[][] matrix, double[][] feromon, double alpha, double beta,
                   int candidateSize, double[][] distances, List<Integer>[] candidates) {
            int size = matrix.length;
            order = new ArrayList<>();
     
            int current = rnd.nextInt(size);
            int first = current;
            order.add(current);
            Set<Integer> toVisit = new HashSet<>();
     
            for (int i = 0; i < size; ++i){
                if (i == current) continue;
                toVisit.add(i);
            }
     
            while (!toVisit.isEmpty()){
                List<Integer> neighbours = new ArrayList<>(candidates[current]);
     
                neighbours = neighbours.stream()
                                       .limit(candidateSize)
                                       .filter(toVisit::contains)
                                       .collect(Collectors.toList());
     
                int neighbourIndex = 0;
                if (neighbours.size() > 0){
                    double sum = 0;
                    for (int index : neighbours){
                        sum += matrix[current][index] * Math.pow(feromon[current][index], alpha);
                    }
     
                    double rand = rnd.nextDouble();
                    double tmpSum = 0;
     
                    neighbourIndex = 0;
                    while (tmpSum < rand){
                        int index = neighbours.get(neighbourIndex);
                        tmpSum += (matrix[current][index] * Math.pow(feromon[current][index], alpha)) / sum;
     
                        if (tmpSum > rand) {
                            neighbourIndex = index;
                            break;
                        }
                        neighbourIndex++;
                    }
     
                } else {
                    int index = rnd.nextInt(toVisit.size());
                    for (int neighbour : toVisit){
                        if (index == 0){
                            neighbourIndex = neighbour;
                            break;
                        }
                        index--;
                    }
                }
     
                toVisit.remove(neighbourIndex);
                distance += distances[current][neighbourIndex];
                current = neighbourIndex;
                order.add(neighbourIndex);
            }
     
            distance += distances[current][first];
        }
     
        public double getDistance(){
            return distance;
        }
     
        public List<Integer> getOrder() {
            return order;
        }
    }
    Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    package test1;
     
    public class Coordinate {
        private double x;
        private double y;
     
        public Coordinate(double x, double y) {
            this.x = x;
            this.y = y;
        }
     
        public double getX() {
            return x;
        }
     
        public void setX(double x) {
            this.x = x;
        }
     
        public double getY() {
            return y;
        }
     
        public void setY(double y) {
            this.y = y;
        }
     
        double distance(Coordinate other){
            double dist = 0;
     
            dist += (other.x - this.x) * (other.x - this.x);
            dist += (other.y - this.y) * (other.y - this.y);
     
            return Math.sqrt(dist);
        }
    }
    Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    package test1;
     
    public class Pair<X extends Comparable<X>, Y> implements Comparable<Pair<X, Y>> {
        private X x;
        private Y y;
     
        public Pair(X x, Y y) {
            this.x = x;
            this.y = y;
        }
     
        public X getX() {
            return x;
        }
     
        public void setX(X x) {
            this.x = x;
        }
     
        public Y getY() {
            return y;
        }
     
        public void setY(Y y) {
            this.y = y;
        }
     
        @Override
        public int compareTo(Pair<X, Y> o) {
            return this.x.compareTo(o.x);
        }
    }

    Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    package test1;
     
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.*;
    import java.util.stream.Collectors;
     
    /**
     * @author Kristijan Vulinovic
     * @version 1.0.0
     */
    public class TSPSolver {
        private static Path filepath;
        private static int candidateSize;
        private static int colonySize;
        private static int maxIter;
     
        private static double alpha = 1.2;
        private static double beta = 2.3;
        private static double a = 100;
        private static double ro = 0.02;
        private static int maxStagnation;
     
        private static int dimension;
        private static double[][] distances;
        private static double[][] matrix;
        private static double[][] feromon;
        private static List<Integer>[] candidates;
        private static double maxFeromon;
        private static double minFeromon;
     
        private static Ant bestAnt;
     
        public static void main(String[] args) {
        /*	args[0] = "C:/Users/soumaya aafif/Desktop/a/test.tx" ;
        	args[1] = "12" ;
        	args[2] = "3" ;
        	args[3] = "1000" ;
    */
        /*	if (args.length != 0){
                System.err.println("Invalid number of arguments!");
                System.exit(1);
            }*/
     
        	//Path p = Paths.get("C:/Users/soumaya aafif/Desktop/a/test.txt");
          //  filepath = Paths.get(args[0]);
            candidateSize = 12;
            colonySize = 15;
            maxIter = 200;
            maxStagnation = (int)(0.5 * maxIter);
     
            matrix = readInput();
            initFeromon();
     
            generateCandidates();
     
            solve();
        }
     
        private static void generateCandidates() {
            candidates = new ArrayList[dimension];
     
            for (int i = 0; i < dimension; ++i) {
                List<Pair<Double, Integer>> neighbours = new ArrayList<>();
                for (int j = 0; j < dimension; ++j) {
                    if (j == i) continue;
     
                    neighbours.add(new Pair(distances[i][j], j));
                }
                neighbours.sort(Comparator.naturalOrder());
                neighbours = neighbours.stream()
                        .limit(candidateSize)
                        .collect(Collectors.toList());
     
                candidates[i] = new ArrayList<>();
                for (Pair<Double, Integer> neighbour : neighbours){
                    candidates[i].add(neighbour.getY());
                }
            }
        }
     
        private static void solve() {
            int stagnationCounter = 0;
     
            for (int i = 0; i < maxIter; ++i){
                Ant currentBest = new Ant(matrix, feromon, alpha, beta, candidateSize, distances, candidates);
                for (int j = 0; j < colonySize; ++j){
                    Ant newAnt = new Ant(matrix, feromon, alpha, beta, candidateSize, distances, candidates);
                    if (newAnt.getDistance() < currentBest.getDistance()){
                        currentBest = newAnt;
                    }
     
                }
     
                updateFeromons(currentBest, i);
     
                if (bestAnt == null || currentBest.getDistance() < bestAnt.getDistance()){
                    bestAnt = currentBest;
                    stagnationCounter = 0;
                } else {
                    stagnationCounter++;
                    if (stagnationCounter > maxStagnation){
                        stagnationCounter = 0;
                        initFeromon();
                    }
                }
                System.out.println(bestAnt.getDistance());
            }
        }
     
        private static void updateFeromons(Ant currentBest, int iteration) {
            for (int i = 0; i < dimension; ++i){
                for (int j = 0; j < dimension; ++j){
                    feromon[i][j] *= (1.0 - ro);
     
                    if (feromon[i][j] < minFeromon){
                        feromon[i][j] = minFeromon;
                    }
                }
            }
     
            Ant ant;
            if (iteration > maxIter * 0.85){
                ant = bestAnt;
            } else {
                ant = currentBest;
            }
     
            double feromonChange = 1 / ant.getDistance();
     
            List<Integer> order = ant.getOrder();
            int size = order.size();
            for (int i = 0; i < size; ++i){
                int from = order.get(i);
                int nextIndex = i + 1;
                if (nextIndex >= size){
                    nextIndex = 0;
                }
                int to = order.get(nextIndex);
     
                feromon[from][to] += feromonChange;
                feromon[to][from] += feromonChange;
     
                if (feromon[from][to] > maxFeromon){
                    feromon[from][to] = maxFeromon;
                    feromon[to][from] = maxFeromon;
                }
            }
        }
     
        private static void initFeromon() {
            updateMaxFeromon();
            minFeromon = maxFeromon / a;
     
            for (int i = 0; i < dimension; ++i){
                for (int j = 0; j < dimension; ++j){
                    feromon[i][j] = maxFeromon;
                }
            }
        }
     
        private static void updateMaxFeromon() {
            double bestSolution;
     
            if (bestAnt != null){
                bestSolution = bestAnt.getDistance();
            } else {
                bestSolution = greedySolution();
            }
     
            maxFeromon = 1.0 / (ro * bestSolution);
        }
     
        private static double greedySolution() {
            double distance = 0;
     
            int current = 0;
            Set<Integer> toVisit = new HashSet<>();
     
            for (int i = 1; i < dimension; ++i){
                toVisit.add(i);
            }
     
            while (!toVisit.isEmpty()){
                double minDist = 0;
                int closest = -1;
     
                for (int next : toVisit){
                    if (closest == -1 || distances[current][next] < minDist){
                        minDist = distances[current][next];
                        closest = next;
                    }
                }
     
                toVisit.remove(closest);
                current = closest;
                distance += minDist;
            }
     
            distance += distances[current][0];
            return distance;
        }
     
        private static double[][] readInput() {
            List<String> lines = null;
            try {
                lines = Files.readAllLines(filepath);
            } catch (IOException e) {
                System.err.println("Unable to open the given file!");
                System.exit(1);
            }
     
            for (String line : lines){
                line = line.trim();
                if (line.startsWith("DIMENSION")){
                    line = line.substring("DIMENSION: ".length()).trim();
                    dimension = Integer.parseInt(line);
                    distances = new double[dimension][dimension];
                    feromon = new double[dimension][dimension];
                }
     
                if (line.startsWith("EDGE_WEIGHT_TYPE")){
                    if (line.endsWith("EXPLICIT")){
                        return readExplicit(lines);
                    } else {
                        return readEuclid(lines);
                    }
                }
            }
     
            return null;
        }
     
        private static double[][] readEuclid(List<String> lines) {
            double[][] matrix = new double[dimension][dimension];
     
            int index = 0;
            while (!lines.get(index).contains("SECTION")){
                index++;
            }
            index++;
     
            Coordinate[] coordinates = new Coordinate[dimension];
            for (int i = 0; i < dimension; ++i){
                String line = lines.get(index + i).trim();
                String[] lineNums = line.split("\\s+");
     
                if (lineNums.length != 3){
                    System.err.println("Invalid input data!");
                    System.exit(1);
                }
     
                double x = Double.parseDouble(lineNums[1]);
                double y = Double.parseDouble(lineNums[2]);
                coordinates[i] = new Coordinate(x, y);
            }
     
            for (int i = 0; i < dimension; ++i){
                for (int j = 0; j < dimension; ++j){
                    distances[i][j] = coordinates[i].distance(coordinates[j]);
     
                    matrix[i][j] = Math.pow((1.0 / distances[i][j]), beta);
                }
            }
     
            return matrix;
        }
     
        private static double[][] readExplicit(List<String> lines) {
            double[][] matrix = new double[dimension][dimension];
     
            int index = 0;
            while (!lines.get(index).contains("SECTION")){
                index++;
            }
            index++;
     
            /*lines.removeAll(lines.stream().limit(index).collect(Collectors.toList()));
            return readEuclid(lines);*/
     
            for (int i = 0; i < dimension; ++i){
                String line = lines.get(index + i).trim();
                String[] lineNums = line.split(" +");
     
                if (lineNums.length != dimension){
                    System.err.println("Invalid input data!");
                    System.exit(1);
                }
     
                for (int j = 0; j < dimension; ++j){
                    distances[i][j] = Double.parseDouble(lineNums[j]);
     
                    matrix[i][j] = Math.pow((1.0 / distances[i][j]), beta);
                }
            }
     
            return matrix;
        }
    }
    veuillez m'aider à faire une classe de test et merci

Discussions similaires

  1. Algorithme de colonies de fourmis
    Par o.sarah91 dans le forum Algorithmes et structures de données
    Réponses: 2
    Dernier message: 17/12/2011, 20h07
  2. programmation d'un algorithme de colonies de fourmis en java
    Par sabrinafr dans le forum Général Java
    Réponses: 1
    Dernier message: 12/05/2010, 09h13
  3. calcul d'une fonction de probabilité dans un algorithme de colonie de fourmis!
    Par etdmi3 dans le forum Algorithmes et structures de données
    Réponses: 1
    Dernier message: 19/02/2009, 11h21
  4. Application des colonies de fourmis au voyageur de commerce
    Par khayyam90 dans le forum Algorithmes et structures de données
    Réponses: 0
    Dernier message: 11/12/2008, 14h21

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo