Appel d'une matrice dans une classe extérieur(java)

[Résolu/Fermé]
Signaler
Messages postés
45
Date d'inscription
dimanche 19 août 2012
Statut
Membre
Dernière intervention
6 décembre 2012
-
Messages postés
45
Date d'inscription
dimanche 19 août 2012
Statut
Membre
Dernière intervention
6 décembre 2012
-
Bonjour,

jai une classe CLASS1 java qui contenant des centaines des lignes de codes et qui remplie une matrice appelé chromsosome[][].
Une fois la matrice est remplie, je l'affiche normalement dans la meme classe avec ces lignes de code:

for(int i=0;i<size;i++){//begin for

for(int j=0;j<=((numWaste+numObstacles)*2)+7;j++){
System.out.print(chromosome[i][j]+"\t");

}
System.out.println("\n");

}

Je veux recuperer cette matrice chromosome dans une autre classe CLASS2(dans un autre package de mem projet) mais jarrive pas :'(.
Dans CLASS1, jai deja créer un getter de matrice comme suit:
Public double[][] getchromsome()
{
return chromosome;
}

Pour afficher et recuprer cette chromosome dans CLASS2 sans refaire tte les operations de CLASS1, jai tapé ce code dans CLASS2:


CLASS1 j= null;
double [][] t = j.getchromosome();
System.out.println(t);

mais toujours il ya rien comme resultat, stp , qui peut maider????????? c trés urgent

1 réponse

Messages postés
16410
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
24 octobre 2021
2 903
Tu fais j.getchromosome() alors que tu as initialisé j avec null !?
Il faudrait peut-être créer un objet avant d'utiliser des méthodes, c'est la base !
Et puis on affiche pas un tableau directement avec println(t) car ça n'affichera que la valeur de l'objet pas le contenu du tableau !
Il faut que tu réutilises ton code avec tes deux boucles for, exemple :

// dans CLASS1

public void afficherChromosome()
{
    for(int i=0; i<size; i++)
    {
        for(int j=0; j<=((numWaste+numObstacles)*2)+7; j++)
            System.out.printf("%d\t",chromosome[i][j]);
        System.out.println("\n");
    }
}

// dans CLASS2

CLASS1 j = new CLASS1();
j.afficherChromosome();
Messages postés
45
Date d'inscription
dimanche 19 août 2012
Statut
Membre
Dernière intervention
6 décembre 2012

merci pour ta reponse :) voila le pb est içi :/ il naccepte pas ce ligne de code
CLASS1 j = new CLASS1(); ,toujours une erreur .bon dans la class1 , il ya une methode class1(int,int) .jai essayé comme ça:
class1 = new class1(int,int) mé rien de special :'(
Messages postés
45
Date d'inscription
dimanche 19 août 2012
Statut
Membre
Dernière intervention
6 décembre 2012

voici quelques instructions dans class1(qui est MockWasteOfRealProblem)
/*============================================================================================================
* My Adapted Version
============================================================================================================*/
package jadex.examples.cleanerworld.multi.mocks;

import jadex.examples.cleanerworld.multi.Chargingstation;
import jadex.examples.cleanerworld.multi.Cleaner;
import jadex.examples.cleanerworld.multi.Location;
import jadex.examples.cleanerworld.multi.Obstacle;
import jadex.examples.cleanerworld.multi.TestCase;
import jadex.examples.cleanerworld.multi.Waste;
import jadex.examples.cleanerworld.multi.Wastebin;
import jadex.examples.cleanerworld.multi.testenvironment.ga.ITestCaseDecoder;
import jadex.examples.cleanerworld.multi.utils.CommonUtil;
import jadex.examples.cleanerworld.multi.utils.MyConstants;
import jmetal.base.DecisionVariables;
import jmetal.base.Problem;
import jmetal.base.Solution;
import jmetal.base.Configuration.SolutionType_;
import jmetal.base.Configuration.VariableType_;
import jmetal.util.JMException;


public class MockWasteObsRealProblem extends Problem implements ITestCaseDecoder {

//***************************************************
//Looking for the location of wastes and obstacles
//**************************************************
private static final long serialVersionUID = 1L;

private final Waste[] wastes;
private final Wastebin[] wastebins;
private final Chargingstation[] stations;
private final Obstacle[] obstacles;

private TestCase tc = new TestCase();
private int numWaste;
private int numObstacles;
public int m=0;
public int s1=0;
public double dmin;
public double dmax;
public int p=0;
public int k = 0;
public static int size = 4;
public double[][] S= new double[10][10];
public double chromosome[][]= new double[20][50];


public double f0[]= new double[size];
public double f1[]= new double [size];
public double f2[]= new double [size];
public double f3[]= new double[size];
public double f4[]= new double [size];
public double f5[]= new double [size];
public double f6[]= new double [size];

public double fmin[]=new double[7];//7 is the number of obj
public double fmax[]= new double [7];




private static final String SOLUTION_TYPE = "Real";
private static final String EXPORT_PATH = "/Users/Sabrina/TMP/";
private static int testCaseCount = 1;

public MockWasteObsRealProblem(int _numObstacles, int _numWaste) {



numberOfObjectives_ = 7;


problemName_ = "WASTE-OBS-REAL-EVOLTEST";

numObstacles = _numObstacles;
numWaste = _numWaste;

numberOfVariables_ = numObstacles * 2 + numWaste * 2; // x, y coordinates of waste and obstacles

upperLimit_ = new double[numberOfVariables_];
lowerLimit_ = new double[numberOfVariables_];

for (int i = 0; i < numberOfVariables_; i++) {
lowerLimit_[i] = 0.02;
upperLimit_[i] = 0.98;
}

solutionType_ = Enum.valueOf(SolutionType_.class, SOLUTION_TYPE);

// All the variables are of the same type
variableType_ = new VariableType_[numberOfVariables_];
for (int var = 0; var < numberOfVariables_; var++) {
variableType_[var] = Enum.valueOf(VariableType_.class, SOLUTION_TYPE);
}

// fix the locations of wastes, wastebin, and station
Location[] wastebinLocs = MyConstants.WB_LOCATIONS.toArray(
new Location[MyConstants.WB_LOCATIONS.size()]);
wastebins = new Wastebin[wastebinLocs.length];
for (int i = 0; i < wastebinLocs.length; i++) {
wastebins[i] = new Wastebin(wastebinLocs[i], MyConstants.WB_SIZE);
tc.addWastebin(wastebins[i]);
}

Location[] stationsLocs = MyConstants.CS_LOCATIONS.toArray(
new Location[MyConstants.CS_LOCATIONS.size()]);
stations = new Chargingstation[stationsLocs.length];
for (int i = 0; i < stationsLocs.length; i++) {
stations[i] = new Chargingstation(stationsLocs[i]);
tc.addStation(stations[i]);
}

wastes = new Waste[numWaste];
for (int i = 0; i < numWaste; i++) {
wastes[i] = new Waste(new Location(0.5,0.5));
tc.addWaste(wastes[i]);
}


obstacles = new Obstacle[numObstacles];
for (int i = 0; i < numObstacles; i++){
obstacles[i] = new Obstacle(new Location(0.5,0.5));
obstacles[i].setRadius(MyConstants.OBSTACLE_SIZE);
tc.addObstacle(obstacles[i]);
}

// initiate the test case
tc.setDaytime(true); // fix this value
Cleaner cl = new Cleaner();
cl.setLocation(MyConstants.STARTUP_LOCATION); // fix starting location
tc.addCleaner(cl);

}













//===========================
//Evaluate solution
//===========================
@Override
public void evaluate(Solution solution) throws JMException {
// decode the solution
int tcId = testCaseCount++;
decode(solution);

tc.setId(String.valueOf(tcId));

// reset wastebins
for (Wastebin wb : tc.getWastebins()) {
wb.empty();
}

TestCase activeTc = (TestCase) tc.clone();


//====SOFT-Goal 1: Robustness===

double fit0 = 1; //fitness function of obstacles
double fit1 = 1; //fitness function of power

//====SOFT-Goal 2: Efficiency====

double fit2= 1; //the fitness of the amount of waste collected by the agent

//====SOFT-Goal 3 : Stability====

double fit3=1; //the fitnes related to the dist between the location of the agent and the collected waste
double fit4=1; //the fitness related to the dist between the location of the agent and the chosen wastebin to put collected waste
double fit5=1; //the fitness related to the dist between the agent and the chosen chargin station

//=== SOFT-Goal 4 : Safety
double fit6=1;//the fitness related to the dist between th elocation of the agent and obstacle

//+++++ execute test case++++++

if (CommonUtil.isDeadTestCase(activeTc, MyConstants.STARTUP_LOCATION)) {
fit0 = 1;
fit1 = 1;
fit2 = 1;
fit3 = 1;
fit4 = 1;
fit5 = 1;
fit6 = 1;
} else {

MockAgent agent = new MockAgent(1.0, 1000, MyConstants.STARTUP_LOCATION);

int totalTime = agent.run(activeTc);

//***************************
//Compute fitness functions
//***************************

//0//===============

double totalPower = agent.getTotalPower();
if (totalPower > 0) {
fit0 = 1.0 / (totalPower * 100);


}
//1//===============

int numObsEncounterd = agent.getNumbObsEncountered();
if (numObsEncounterd > 0) {
fit1 = 1.0 / (double)(numObsEncounterd * 2);


}
//2//===============

int numWasteCollected =agent.getnumWasteCollected();
if(numWasteCollected > 0){
fit2= 1.0/ (double) numWasteCollected;

}
//3//===============

double DROPcollectnearestwaste= agent.getDROPcollectnearestwaste();
if(DROPcollectnearestwaste > 0){
fit3 = 1.0 / (double)DROPcollectnearestwaste;

//fitness[p][3]=fit3;
}
//4//===============
double DropmovingtonearestBin = agent.getDropmovingtonearestBin();
if( DropmovingtonearestBin > 0){
fit4 = 1.0 / (double) DropmovingtonearestBin;

}

//5//===============
double Dropmovingtonearestcs = agent.getDropmovingtonearestcs();
if(Dropmovingtonearestcs > 0 )
{
fit5 = 1.0 /(double) Dropmovingtonearestcs;

}
//6//===============
double NumberAvoidingobs = agent.getNumberAvoidingobs();
if(NumberAvoidingobs > 0 )
{
fit6= 1.0 / (double)NumberAvoidingobs;


}

if(p<size)
{
System.out.println("p = "+p);


f0[p]=floor(fit0,4);
f1[p]=floor(fit1,4);
f2[p]=floor(fit2,4);
f3[p]=floor(fit3,4);
f4[p]=floor(fit4,4);
f5[p]=floor(fit5,4);
f6[p]=floor(fit6,4)
;

S[p][0]=f0[p];
S[p][1]=f1[p];
S[p][2]=f2[p];
S[p][3]=f3[p];
S[p][4]=f4[p];
S[p][5]=f5[p];
S[p][6]=f6[p];
chromosome[p][(numWaste+numObstacles)*2]=f0[p];
chromosome[p][(numWaste+numObstacles)*2+1]=f1[p];
chromosome[p][(numWaste+numObstacles)*2+2]=f2[p];
chromosome[p][(numWaste+numObstacles)*2+3]=f3[p];
chromosome[p][(numWaste+numObstacles)*2+4]=f4[p];
chromosome[p][(numWaste+numObstacles)*2+5]=f5[p];
chromosome[p][(numWaste+numObstacles)*2+6]=f6[p];


}
if(p==size - 1)
{
.......................





//Distance to reference assignement
distance_to_reference_assignement(numWaste,numObstacles,S,chromosome,7,fmin,fmax);

dmin=chromosome[0][(numWaste+numObstacles)*2+7];
dmax=chromosome[0][(numWaste+numObstacles)*2+7];
for(int i=0;i<=(size-2);i++)
{
if(chromosome[i+1][(numWaste+numObstacles)*2+7] < dmin)
{
dmin=chromosome[i+1][(numWaste+numObstacles)*2+7];
}
if(chromosome[i+1][(numWaste+numObstacles)*2+7] > dmax)
{
dmax=chromosome[i+1][(numWaste+numObstacles)*2+7];
}

}

/* //affichage de chromosome
System.out.println("======================================================");
System.out.println("chromosome= DV+FF+Distance X");
System.out.println("======================================================");


for(int i=0;i<size;i++){//begin for

for(int j=0;j<=((numWaste+numObstacles)*2)+7;j++){
System.out.print(chromosome[i][j]+"\t");

}
System.out.println("\n");

}
System.out.println("dmin = " + dmin);
System.out.println("dmax = " + dmax);
// System.out.println("================================================"*/


}


p++;

}


if(p== size)
{
//affichage de chromosome aprés l'ajout de distance de reference
System.out.println("======================================================");
System.out.println("chromosome= DV+FF+Distance X");
System.out.println("======================================================");


for(int i=0;i<size;i++){//begin for

for(int j=0;j<=((numWaste+numObstacles)*2)+7;j++){
System.out.print(chromosome[i][j]+"\t");

}
System.out.println("\n");

}
System.out.println("dmin = " + dmin);
System.out.println("dmax = " + dmax);
System.out.println("================================================");

}
solution.setObjective(0, fit0);
solution.setObjective(1, fit1);
solution.setObjective(2, fit2);
solution.setObjective(3, fit3);
solution.setObjective(4, fit4);
solution.setObjective(5,fit5);
solution.setObjective(6,fit6);



}

public static double distance_to_reference_assignement(int numWaste,int numObstacles,double[][] S,double[][]chromosome,int M,double[] fmin,double[] fmax)
{
double x = 0;
// int i=0;
for(int j=0;j<size;j++)
{

double result;
double sum = 0;

for (int i1=0;i1<M;i1++)
{
if(i1 % 2 == 0)
{
double B= carre((S[j][i1] - 0.3) / (fmax[i1]-fmin[i1]));

sum= sum +floor(B/7,4);

}else{

double B= carre((S[j][i1] - 0.4) / (fmax[i1]-fmin[i1]));
sum = sum + floor(B/7,4);
}
}


result=Math.sqrt(sum);
x=floor(result,4);
S[j][7]=x;
chromosome[j][(numWaste+numObstacles)*2+7]=x;


}
return x;


}


public static double floor(double a, int n) {
double p = Math.pow(10.0, n);
return Math.floor((a*p)+0.5) / p;
}
//A fonction to compute the carre
public static double carre(double x)
{
double y = x * x;
return y;
}



//*****************************
//TestCase decode
//*****************************

public TestCase decode(Solution s) {
DecisionVariables decisionVariables = s.getDecisionVariables();
int mid = numberOfVariables_ / 2;


try {
System.out.println("s1 = "+s1);
// System.out.println("remplissage de chromosome avec des variables de decisions");
// System.out.println("s1 = " + s1);
for (int i = 0; i < numObstacles; i++) {
double x = decisionVariables.variables_[i].getValue();
chromosome[s1][i]=x;
//System.out.println("chromosome["+s1+"]["+i+"] = "+chromosome[s1][i]);
double y = decisionVariables.variables_[i+mid].getValue();
chromosome[s1][i+mid]=y;
//System.out.println("chromosome["+s1+"]["+(i+mid)+"] = "+chromosome[s1][i+mid]);
Location loc = new Location(x, y);

Obstacle obs = obstacles[i];
obs.setLocation(loc);
}

for (int i = 0; i < numWaste; i++) {
double x = decisionVariables.variables_[numObstacles + i].getValue();
chromosome[s1][numObstacles + i]= x;
//System.out.println("chromosome["+s1+"]["+(numObstacles + i)+"] = "+chromosome[s1][numObstacles + i]);

double y = decisionVariables.variables_[numObstacles + i +mid].getValue();
// System.out.println("chromosome["+s1+"]["+(numObstacles +i +mid)+"] = "+chromosome[s1][numObstacles + i +mid]);
chromosome[s1][numObstacles + i +mid]= y;

Location loc = new Location(x, y);
Waste w = wastes[i];
w.setLocation(loc);
}

s1++;
//System.out.println("s1 = " + s1);
} catch (JMException e) {
e.printStackTrace();
}

return tc;
}

public double[][] getS()
{
return S;
}
public double[][] getchromosome()
{
return chromosome;
}

public double getdmin ()
{
return dmin;
}
public double getElement(int index) {
return chromosome[5][index];
}

}
Messages postés
16410
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
24 octobre 2021
2 903
"jai essayé comme ça: class1 = new class1(int,int) mé rien de special"
C'est parce que ton constructeur n'utilises pas le tableau "chromosome", il faut appeler evaluate et/ou decode pour que la matrice soit modifiée.

Alors je ne sais pas ce que c'est censé faire, mais voici un "exemple" :

int numObstacles = ???
int numWaste = ???
Solution solution = ???

MockWasteObsRealProblem rp = new MockWasteObsRealProblem(numObstacles, numWaste);
rp.evaluate(solution);
TestCase tc = rp.decode(solution);

rp.afficherChromosome();
Messages postés
45
Date d'inscription
dimanche 19 août 2012
Statut
Membre
Dernière intervention
6 décembre 2012

Bonsoir, c la classe ou je veux faire laffichage et aussi surtout la recuperation des valeurs de cette matrice chromosome,stp ,quesque je dois faire , je suis vraiment bloquée :( .jai deja problem_.evaluate(solution) ,si s'ajoute rp.evaluate(solution)il yaura une redondance


package jadex.examples.cleanerworld.multi.testenvironment.ga;



import jadex.examples.cleanerworld.multi.Obstacle;
import jadex.examples.cleanerworld.multi.TestCase;
import jadex.examples.cleanerworld.multi.Waste;
import jadex.examples.cleanerworld.multi.testenvironment.export.TestCase2XML;
import jadex.examples.cleanerworld.multi.utils.CommonUtil;
import jadex.examples.cleanerworld.multi.mocks.MockWasteObsRealProblem;

import java.io.File;

import jmetal.base.*;
import jmetal.util.*;

/**
* This class implements the NSGA-II algorithm.
*/
public class ModifiedNSGAII extends Algorithm {

/**
* stores the problem to solve
*/
private Problem problem_;

/**
* Constructor
* @param problem Problem to solve
*/
public ModifiedNSGAII(Problem problem){
this.problem_ = problem;
} // NSGAII

/**
* Runs of the NSGA-II algorithm.
* @return a
SolutionSet
that is a set of non dominated solutions
* as a result of the algorithm execution
* @throws JMException
*/

// MockWasteObsRealProblem j= null;
public SolutionSet execute() throws JMException {
int populationSize ;
int maxEvaluations ;
int evaluations ;
//MockWasteObsRealProblem s = null;

SolutionSet population ;
SolutionSet offspringPopulation ;
SolutionSet union ;

Operator mutationOperator ;
Operator crossoverOperator ;
Operator selectionOperator ;

Distance distance = new Distance() ;

//Read the parameters
populationSize = ((Integer)this.getInputParameter("populationSize")).intValue();
maxEvaluations = ((Integer)this.getInputParameter("maxEvaluations")).intValue();

//Initialize the variables
population = new SolutionSet(populationSize);
evaluations = 0;

//Read the operators
mutationOperator = this.operators_.get("mutation");
crossoverOperator = this.operators_.get("crossover");
selectionOperator = this.operators_.get("selection");

// Create the initial solutionSet
Solution newSolution;


// String pathPrefix = "/idacox0/sra/cunduy/workspace3.5/jadex-cleaning-robot/inputs/";
String pathPrefix = CommonUtil.getProjectPath() + File.separatorChar + "inputs" + File.separatorChar;
// int l1=0;
for (int i = 0; i < populationSize; i++) {
newSolution = new Solution(problem_);

// TODO comment the following 2 lines if you dont want the algo to load the
// initial test cases
String fullPath = pathPrefix + "tc" + String.valueOf(i+1) + ".xml";
loadPredefiedTestCase(newSolution, fullPath);
//===================

rp.evaluate(newSolution);
rp.evaluateConstraints(newSolution);

// l1++;
//=====================
// problem_.evaluate(newSolution);
// problem_.evaluateConstraints(newSolution);
evaluations++;
System.out.println("============evaluations = "+ evaluations+"========================");
population.add(newSolution);
} //for




// Generations ...
while (evaluations < maxEvaluations) {

// Create the offSpring solutionSet
offspringPopulation = new SolutionSet(populationSize);
Solution [] parents = new Solution[2];
for (int i = 0; i < (populationSize/2); i++){
//obtain parents
parents[0] = (Solution)selectionOperator.execute(population);
System.out.print("parents[0]="+ parents[0].getDecisionVariables());
System.out.println("\n");
System.out.println("parents[0] = "+parents[0]);
parents[1] = (Solution)selectionOperator.execute(population);
System.out.print("parents[1]="+ parents[1].getDecisionVariables());
System.out.println("\n");
System.out.println("parents[1] = "+parents[1]);
if (evaluations < maxEvaluations) {
Solution [] offSpring = (Solution []) crossoverOperator.execute(parents);
System.out.print("offsprings[0] aprés croissement ="+ offSpring[0].getDecisionVariables());
System.out.println("\n");
System.out.print("offSpring[1] aprés croissement ="+ offSpring[1].getDecisionVariables());
System.out.println("\n");
mutationOperator.execute(offSpring[0]);
mutationOperator.execute(offSpring[1]);
problem_.evaluate(offSpring[0]);
problem_.evaluateConstraints(offSpring[0]);
problem_.evaluate(offSpring[1]);
problem_.evaluateConstraints(offSpring[1]);
offspringPopulation.add(offSpring[0]);
offspringPopulation.add(offSpring[1]);
evaluations += 2;
System.out.println("============evaluations = "+ evaluations+"========================");

} else {
offspringPopulation.add(new Solution(parents[0]));
offspringPopulation.add(new Solution(parents[1]));
} // if
} // for


// Create the solutionSet union of solutionSet and offSpring
union = ((SolutionSet)population).union(offspringPopulation);

// Ranking the union
Ranking ranking = new Ranking(union);

int remain = populationSize;
int index = 0;
SolutionSet front = null;
population.clear();

// Obtain the next front
front = ranking.getSubfront(index);

while ((remain > 0) && (remain >= front.size())){
//Assign crowding distance to individuals
distance.crowdingDistanceAssignment(front, problem_.getNumberOfObjectives());
//Add the individuals of this front
for (int k = 0; k < front.size(); k++ ) {
population.add(front.get(k));
} // for

//Decrement remain
remain = remain - front.size();

//Obtain the next front
index++;
if (remain > 0) {
front = ranking.getSubfront(index);
} // if
} // while

// remain is less than front(index).size, insert only the best one
if (remain > 0) { // front contains individuals to insert
distance.crowdingDistanceAssignment(front,problem_.getNumberOfObjectives());
front.sort(new jmetal.base.operator.comparator.CrowdingComparator());
for (int k = 0; k < remain; k++) {
population.add(front.get(k));
} // for

remain = 0;
} // if
} // while

// Return the first non-dominated front
Ranking ranking = new Ranking(population);
return ranking.getSubfront(0);
} // execute



} // NSGA-II