Commit 9b952a17 authored by Dumoulin Nicolas's avatar Dumoulin Nicolas
Browse files

sources

parent e23823f4
No related merge requests found
Showing with 1957 additions and 0 deletions
+1957 -0
10
dir
0
http://trac.clermont.cemagref.fr/svn/PRIMA/AmiThreat1/src
http://trac.clermont.cemagref.fr/svn/PRIMA
add
svn:special svn:externals svn:needs-lock
6a2e9def-b413-4168-a192-dec410e7e464
src/Agent.java 0 → 100644
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* @author Sylvie.huet
*/
public class Agent {
int nbAgentThisType;
double distAutruiInit;
int id = -1;
CulturalWorldView[] myCulture; //initialisées dans ordre lecture fichier : muslims, christians, areligious
CulturalWorldView[] myCultureInit;
int nbWorldView;
float alpha;
float[] opinionGlobalOnOthers;
double[] opinionOnOtherAgents;
double[] previousOpinionOnOtherAgents;
double opOfTheExtremistOnIt;
ResistingHostility pop;
String type; // agressor or victim for message agent
String group; // areligious, muslims or christians
String openness; // inclusive or exclusive
float partInGroup; // part of this agent in the group (taux d'inclusif ou d'exclusif)
// Constructeur inutile pour permettre une initialisation provisoire
public Agent() {
}
public Agent(ResistingHostility me, int type, int id, String[] name, float[] adherence, float[] alow, float[] amax, int nbAgents, float alpha, int dimAdhesion, int nb) {
this.nbAgentThisType = nb;
this.id = id;
this.pop = me;
this.opinionGlobalOnOthers = new float[nbAgents];
this.distAutruiInit = 0.0;
opinionOnOtherAgents = new double[6];
previousOpinionOnOtherAgents = new double[6];
Arrays.fill(opinionOnOtherAgents, 0.0);
Arrays.fill(previousOpinionOnOtherAgents, 0.0);
if (type == 1) {
this.type = "inclusive";
} else {
this.type = "exclusive";
}
this.group = groupFromDimAdh(dimAdhesion);
Arrays.fill(opinionGlobalOnOthers, 0.0f);
this.nbWorldView = name.length;
this.alpha = alpha;
myCulture = new CulturalWorldView[nbWorldView];
myCultureInit = new CulturalWorldView[nbWorldView];
for (int i = 0; i < nbWorldView; i++) { // initialisées dans ordre lecture fichier : muslims, christians, areligious
myCulture[i] = new CulturalWorldView(name[i], adherence[i], alow[i], amax[i]);
myCultureInit[i] = new CulturalWorldView(name[i], adherence[i], alow[i], amax[i]);
}
}
// This is the agent constructor for the source
public Agent(ResistingHostility me, String type, float[] adherence, float[] alow, float[] amax, float alpha, int dimAdhesion, int nb) {
this.nbAgentThisType = nb;
this.distAutruiInit = 0.0;
this.type = type;
this.pop = me;
this.group = groupFromDimAdh(dimAdhesion);
this.nbWorldView = adherence.length;
this.alpha = alpha;
myCulture = new CulturalWorldView[nbWorldView];
myCultureInit = new CulturalWorldView[nbWorldView];
for (int i = 0; i < nbWorldView; i++) {
myCulture[i] = new CulturalWorldView(type, adherence[i], alow[i], amax[i]);
myCultureInit[i] = new CulturalWorldView(type, adherence[i], alow[i], amax[i]);
}
}
// This is the agent for generating relevant CWW
public Agent(String openness, float[] adherence, float[] alow, float[] amax, float alpha, int nb) {
this.nbAgentThisType = nb;
this.distAutruiInit = 0.0;
this.type = type;
this.openness = openness;
//this.pop = me;
this.nbWorldView = adherence.length;
this.alpha = alpha;
myCulture = new CulturalWorldView[nbWorldView];
for (int i = 0; i < nbWorldView; i++) {
myCulture[i] = new CulturalWorldView(type, adherence[i], alow[i], amax[i]);
}
}
public Agent(String group, String openness, float representativity, float[] adherence, float[] alow, float[] amax, float alpha, int nb) {
this.nbAgentThisType = nb;
this.distAutruiInit = 0.0;
this.group = group;
this.openness = openness;
this.partInGroup = representativity;
this.nbWorldView = adherence.length;
this.alpha = alpha;
myCulture = new CulturalWorldView[nbWorldView];
for (int i = 0; i < nbWorldView; i++) {
myCulture[i] = new CulturalWorldView(type, adherence[i], alow[i], amax[i]);
}
}
// This is the agent for generating relevant CWW
public Agent(Agent A) {
this.nbAgentThisType = A.nbAgentThisType;
this.distAutruiInit = A.distAutruiInit;
this.group = A.group;
this.openness = A.openness;
this.partInGroup = A.partInGroup;
//this.pop = me;
this.nbWorldView = A.nbWorldView;
this.alpha = A.alpha;
myCulture = new CulturalWorldView[nbWorldView];
float[] adherence = new float[nbWorldView];
float[] alow = new float[nbWorldView];
float[] amax = new float[nbWorldView];
for (int i = 0; i < nbWorldView; i++) {
adherence[i] = A.myCulture[i].maPosition;
alow[i] = A.myCulture[i].alow;
amax[i] = A.myCulture[i].amax;
}
for (int i = 0; i < nbWorldView; i++) {
myCulture[i] = new CulturalWorldView(type, adherence[i], alow[i], amax[i]);
}
}
public double computeOpinionOnOtherMAPosition(float ad, CulturalWorldView c) {
double w = 0.0f; // opinion about another agent's maPosition at the cultural worldview k
double temp = 0;
if (ad == c.maPosition) {
ad = ad + 0.000001f;
}
try {
if ((ad < c.amax) && (ad > c.alow)) {
w = 1.0;
} else if (ad <= c.alow) {
temp = Math.exp(1 + ((ad - c.maPosition) / (c.maPosition - c.alow)));
w = (float) ((temp - 1) / (temp + 1));
} else if (ad >= c.amax) {
temp = Math.exp(1 + ((c.maPosition - ad) / (c.amax - c.maPosition)));
w = (float) ((temp - 1) / (temp + 1));
}
if (Double.isNaN(w)) {
throw new Exception(" w is not a number " + c.alow + " " + c.maPosition + " " + c.amax + " ad " + ad + " w = " + w);
}
} catch (Exception error) {
error.printStackTrace();
}
return w;
}
public double computeOpinionOnOtherMAPosition(float ad, CulturalWorldView c, boolean show) {
double w = 0.0f; // opinion about another agent's maPosition at the cultural worldview k
double temp = 0;
if (ad == c.maPosition) {
ad = ad + 0.000001f;
}
try {
if ((ad < c.amax) && (ad > c.alow)) {
w = 1.0;
} else if (ad <= c.alow) {
temp = Math.exp(1 + ((ad - c.maPosition) / (c.maPosition - c.alow)));
w = (float) ((temp - 1) / (temp + 1));
} else if (ad >= c.amax) {
temp = Math.exp(1 + ((c.maPosition - ad) / (c.amax - c.maPosition)));
w = (float) ((temp - 1) / (temp + 1));
}
if (Double.isNaN(w)) {
throw new Exception(" w is not a number " + c.alow + " " + c.maPosition + " " + c.amax + " ad " + ad + " w = " + w);
}
if (show) {
System.err.print(" dot " + ad + " jugeur " + c.alow + " " + c.maPosition + " " + c.amax + " w = " + w + " ");
}
} catch (Exception error) {
error.printStackTrace();
}
return w;
}
public double opinionOnOthers(Agent A) {
double opTot = 0.0f;
double opIJ = 0.0f;
for (int i = 0; i < nbWorldView; i++) {
opIJ = opinionAboutOtherAgentForOneCWW(myCulture[i], A.myCulture[i], pop.nbPoints);
opTot = opTot + opIJ;
}
return opTot / (float) nbWorldView;
}
public double opinionOnOthers(Agent A, int nbPoints) {
double opTot = 0.0f;
double opIJ = 0.0f;
for (int i = 0; i < nbWorldView; i++) {
opIJ = opinionAboutOtherAgentForOneCWW(myCulture[i], A.myCulture[i], nbPoints);
opTot = opTot + opIJ;
}
return opTot / (float) nbWorldView;
}
public double opinionOnOthers(Agent A, boolean notfromInitState) {
// I have changed but I don't know the other has changed
double opTot = 0.0f;
double opIJ = 0.0f;
for (int i = 0; i < nbWorldView; i++) {
if (notfromInitState) {
opIJ = opinionAboutOtherAgentForOneCWW(myCulture[i], A.myCulture[i], pop.nbPoints);
} else if ((A.group.equalsIgnoreCase(this.group)) && (A.type.equalsIgnoreCase(this.type))) {
opIJ = opinionAboutOtherAgentForOneCWW(myCulture[i], myCulture[i], pop.nbPoints);
} else {
opIJ = opinionAboutOtherAgentForOneCWW(myCulture[i], A.myCultureInit[i], pop.nbPoints);
}
opTot = opTot + opIJ;
}
return opTot / (double) nbWorldView;
}
public double opinionAboutOtherAgentForOneCWW(CulturalWorldView cI, CulturalWorldView cJ, int nbPoints) { // an agent's J cultural worldview
double opI = 0.0f;
double temp = 0.0f;
float[] op = sampleTolSegmentFromGrid(nbPoints, cJ);
for (int i = 0; i < op.length; i++) {
opI = computeOpinionOnOtherMAPosition(op[i], cI);
temp = temp + opI;
}
temp = temp / (double) op.length;
return temp;
}
public double opinionAboutOtherAgentForOneCWW(CulturalWorldView cI, CulturalWorldView cJ, int nbPoints, boolean show) { // an agent's J cultural worldview
double opI = 0.0f;
double temp = 0.0f;
float[] op = sampleTolSegmentFromGrid(nbPoints, cJ);
for (int i = 0; i < op.length; i++) {
opI = Agent.this.computeOpinionOnOtherMAPosition(op[i], cI, show);
temp = temp + opI;
}
temp = temp / (double) op.length;
return temp;
}
public float[] sampleTolSegmentBugged(int nbPoints, CulturalWorldView cJ) {
float[] s = new float[nbPoints];
// we sample starting from the maPosition of the sampling segment and picked out the same number of point on the left and on the right
int countP = 0;
if (nbPoints % 2 == 1) { // nb Points est impair
// a first sampled point at the maPosition value
s[countP] = 1.0f; // by construction
countP++;
nbPoints = nbPoints - 1;
}
nbPoints = nbPoints / 2;
// sampling on the right side
float dist = cJ.amax - cJ.maPosition;
float interv = dist / (float) (nbPoints);
float depart = cJ.maPosition + (0.5f * interv);
for (int i = 0; i < nbPoints; i++) {
s[countP] = depart + (float) i * interv;
countP++;
}
// sampling on the left side
dist = cJ.maPosition - cJ.alow;
interv = dist / (float) (nbPoints);
depart = cJ.alow + (0.5f * interv);
for (int i = 0; i < nbPoints; i++) {
s[countP] = depart + (float) i * interv;
countP++;
}
return s;
}
public float[] sampleTolSegment(int nbPoints, CulturalWorldView cJ) {
float dist = cJ.amax - cJ.alow;
float interv = dist / (float) (nbPoints);
float depart = cJ.alow + (0.5f * interv);
float[] s = new float[nbPoints];
for (int i = 0; i < nbPoints; i++) {
s[i] = depart + (float) i * interv;
}
return s;
}
public float[] sampleTolSegmentFromGrid(int nbPoints, CulturalWorldView cJ) { // allow to approximate the segment using always the same dots for everyone
float interv = 2.0f / (float) (nbPoints); // this is constant
float depart = -1.0f;
float gridDot = -1.0f;
float reserv = -1.0f;
for (int i = 0; i <= nbPoints; i++) {
gridDot = depart + (float) i * interv;
if (gridDot > cJ.alow) { // we take the closer in the segment
depart = gridDot;
reserv = gridDot - interv;
i = nbPoints + 1;
}
}
ArrayList<Float> points = new ArrayList<Float>();
float gridPoint = 0.0f;
for (int i = 0; i <= nbPoints; i++) {
gridPoint = depart + (float) i * interv;
if (gridPoint <= cJ.amax) {
points.add(gridPoint);
} else {
i = nbPoints + 1;
}
}
float[] s;
if (points.size() > 0) {
s = new float[points.size()];
for (int i = 0; i < points.size(); i++) {
s[i] = points.get(i).floatValue();
}
} else {
s = new float[1];
s[0] = reserv;
}
return s;
}
public void reactionToMessage(int type, Agent emetteur) {
reactionToThreatMessageOneDim(emetteur);
}
public void reactionToThreatMessageOneDim(Agent emetteur) {
// I (this) compute what the "emetteur" think of me
opOfTheExtremistOnIt = emetteur.opinionOnOthers(this);
int dimToChange = emetteur.mainDimension();
if (opOfTheExtremistOnIt < 0.0f) {
float mu = alpha * (float) ((Math.exp(opOfTheExtremistOnIt) - 1) / (Math.exp(opOfTheExtremistOnIt) + 1));
myCulture[dimToChange].changeBoundIfThreat(mu, emetteur.myCulture[dimToChange].maPosition, pop.epsilon);
}
}
public int mainDimension() {
int dim = 0;
float adherMax = Float.MIN_VALUE;
for (int i = 0; i < myCulture.length; i++) {
if (myCulture[i].maPosition > adherMax) {
adherMax = myCulture[i].maPosition;
dim = i;
}
}
return dim;
}
public int mainCWWFromGroup() {
int cww = 0; // muslims
if (this.group.equals(new String("areligious"))) {
cww = 2;
} else if (this.group.equals(new String("christians"))) {
cww = 1;
}
return cww;
}
//
public String groupFromDimAdh(int dimAdhesion) {
String g = new String("muslims");
if (dimAdhesion == 2) {
g = new String("areligious");
} else if (dimAdhesion == 1) {
g = new String("christians");
}
return g;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Sylvie.huet
*/
public class CulturalWorldView {
//We consider a population of N agents, each agent i has an identity first defined by 3 values
// between -1 and +1, corresponding to its maPosition or rejection of a cultural world view.
// Agent's cultural worldviews: A positive value expresses maPosition while a negative one expresses rejection.
// The absolute value expresses the intensity of the maPosition of rejection.
// Tolerance: the agent is also defined by tolerance limits above and below this maPosition or rejection values.
float maPosition;
float alow;
float amax;
float exAmax ;
String name;
public CulturalWorldView(String name, float adherence, float alow, float amax) {
this.name = name;
this.maPosition = adherence;
this.alow = alow;
this.amax = amax;
if (Math.abs(adherence - amax) < 0.0000001f) { this.amax = adherence+0.00001f ; } // pour résoudre problème d'encodage de m....
if (Math.abs(adherence - alow) < 0.0000001f) { this.alow = adherence-0.00001f ; }
}
public void changeBoundIfThreat(float mu, float adherenceSource, float epsilon) {
exAmax = amax ;
float base = 0.0f;
float dist1 = Math.abs(adherenceSource - alow);
float dist2 = Math.abs(adherenceSource - amax);
float newBound = 0.0f;
if (dist1 < dist2) {
base = alow;
} else {
base = amax;
}
if (dist1 == dist2) {
if (Math.random() < 0.5) {
base = alow;
} else {
base = amax;
}
}
newBound = base + mu * (base - maPosition - epsilon * (Math.abs(base - maPosition) / (base - maPosition)));
if (base == alow) {
alow = newBound;
} else {
amax = newBound;
}
}
}
/*
* Copyright (C) 2010 Cemagref
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.List;
/**
* Utility classes for iterating on an array of Double, double, Float or float
* for retrieving a double value.
*
* @author Nicolas Dumoulin <nicolas.dumoulin@cemagref.fr>
*/
public interface DoubleCollectionIterator<T> {
public double get(T array, int index);
public int size(T array);
public final static DoubleCollectionIterator<List<Double>> fromDoubleClassList = new DoubleCollectionIterator<List<Double>>() {
@Override
public double get(List<Double> array, int index) {
return array.get(index);
}
@Override
public int size(List<Double> array) {
return array.size();
}
};
abstract static class DoubleArrayIterator<T> implements DoubleCollectionIterator<T> {
@Override
public int size(T array) {
return ((Object[]) array).length;
}
}
public final static DoubleCollectionIterator<Double[]> fromDoubleClass = new DoubleArrayIterator<Double[]>() {
@Override
public double get(Double[] array, int index) {
return array[index];
}
};
public final static DoubleCollectionIterator<double[]> fromDoublePrimitive = new DoubleArrayIterator<double[]>() {
@Override
public double get(double[] array, int index) {
return array[index];
}
@Override
public int size(double[] array) {
return array.length;
}
};
public final static DoubleCollectionIterator<Float[]> fromFloatClass = new DoubleArrayIterator<Float[]>() {
@Override
public double get(Float[] array, int index) {
return array[index];
}
};
public final static DoubleCollectionIterator<float[]> fromFloatPrimitive = new DoubleArrayIterator<float[]>() {
@Override
public double get(float[] array, int index) {
return array[index];
}
@Override
public int size(float[] array) {
return array.length;
}
};
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author sylvie.huet
*/
public class Message {
int time ; // iteration at which the message is delivered
int type ; // 1 = threat ; 2 = compassion
Agent emetteur ; // id of the agent threatening the other agent or being a victim (possibly benefiting from compassion
public Message(int time, int type, Agent emetteur) {
this.time = time ;
this.type = type;
this.emetteur = emetteur;
}
}
/*
* Copyright (C) 2010 Cemagref
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Exception that can be thrown while processing an event and
* encountering some errors.
*
* @author Nicolas Dumoulin <nicolas.dumoulin@cemagref.fr>
*/
public class ProcessingException extends Exception {
public ProcessingException(Throwable cause) {
super(cause);
}
public ProcessingException(String message, Throwable cause) {
super(message, cause);
}
public ProcessingException(String message) {
super(message);
}
}
/*
* Copyright (C) 2010 Cemagref
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import umontreal.iro.lecuyer.probdist.ExponentialDistFromMean;
import umontreal.iro.lecuyer.randvar.ExponentialGen;
import umontreal.iro.lecuyer.randvar.NormalGen;
import umontreal.iro.lecuyer.randvar.RandomVariateGen;
import umontreal.iro.lecuyer.rng.MRG32k3a;
import umontreal.iro.lecuyer.rng.RandomPermutation;
/**
* @author Nicolas Dumoulin <nicolas.dumoulin@cemagref.fr>
* @author sylvie.huet
*/
public class Random {
private MRG32k3a randomStream;
/**
* This method returns an integer picked out following a Uniform law between i and i1. The values i and i1 are included (can be picked out)
*/
public int nextInt(int i, int i1) {
return randomStream.nextInt(i, i1);
}
/**
* This method returns a double picked out following a Uniform law between 0 and 1 with 0 and 1 excluded (can't be picked out)
*/
public double nextDouble() {
return randomStream.nextDouble();
}
public int nextIndexWithDistribution(float[] distribution) {
return nextIndexWithDistribution(distribution, DoubleCollectionIterator.fromFloatPrimitive);
}
public int nextIndexWithDistribution(Double[] distribution) {
return nextIndexWithDistribution(distribution, DoubleCollectionIterator.fromDoubleClass);
}
public int nextIndexWithDistribution(List<Double> distribution) {
return nextIndexWithDistribution(distribution, DoubleCollectionIterator.fromDoubleClassList);
}
/**
* Picks out randomly an object in the given list.
* @param <T>
* @param objects
* @return
*/
public <T> T nextObject(List<T> objects) {
return nextObject(objects, false);
}
/**
* Picks out randomly an object in the given list.
* @param <T>
* @param objects
* @param remove if true, the returned object is removed from the list
* @return null if the list is null or empty.
*/
public <T> T nextObject(List<T> objects, boolean remove) {
if (objects == null || objects.isEmpty()) {
return null;
}
if (remove) {
return objects.remove(nextInt(0, objects.size() - 1));
} else {
return objects.get(nextInt(0, objects.size() - 1));
}
}
/**
* Pick out an object in the values of a map, according to the probilities stored in the keys
*/
public <T> T nextMapObjectWithDistributionInKeys(SortedMap<Double, T> map) {
double rando = nextDouble();
double value = map.firstKey();
Iterator<Double> keysIterator = map.keySet().iterator();
double sum = keysIterator.next();
while (keysIterator.hasNext()) {
sum += value;
if (sum >= rando) {
break;
}
value = keysIterator.next();
}
return map.get(value);
}
public int nextIndexWithDistribution(double[] distribution) {
return nextIndexWithDistribution(distribution, DoubleCollectionIterator.fromDoublePrimitive);
}
/**
* Pick an index in an array covered by a distribution (non-cumulative). If the sum
* of probabilities is less than 1, it may occur that the random index is out of the
* given probabilities. In this case, the last index is returned.
*
* @param distribution
* @return the selected index or -1 if out of distribution.
*/
public <T> int nextIndexWithDistribution(T distribution, DoubleCollectionIterator<T> iterator) {
double rando = nextDouble();
int index = 0;
double sum = iterator.get(distribution, index);
while (rando > sum) {
index++;
if (index == iterator.size(distribution)) {
break;
}
sum += iterator.get(distribution, index);
}
if (index == iterator.size(distribution)) {
// return the last index
index--;
}
return index;
}
/**
* Use this method to initialize a generator based on a statistical distribution.
* For example, this code create a generator from a normal distribution:
* <p><code>NormalGen normalGenerator = new NormalACRGen(null, 0, 1);<br/>
* Random.setRandomStreamInDist(normalGenerator);
* </code></p>
* @param rvg The distribution-based generator to initialize
*/
public void setRandomStreamInDist(RandomVariateGen rvg) {
rvg.setStream(randomStream);
}
/**
* This method return a random order for a sequence of
* leng numbers.
*/
public int[] randomList(int leng) {
int[] vec = new int[leng];
for (int i = 0; i < leng; i++) {
vec[i] = i;
}
RandomPermutation.shuffle(vec, randomStream);
return vec;
}
public String getSeedToString() {
StringBuilder buff = new StringBuilder();
for (long val : randomStream.getState()) {
buff.append(val);
buff.append(" ");
}
return buff.toString();
// this code make troubles in exception stacktrace formatting (don't know why…)
//return Arrays.toString(randomStream.getState());
}
/**
* This method should only be called by the simulation starter.
* The initial status for the RNG is initialized by the simulator at startup.
* @param seed
*/
public void setSeed(long[] seed) throws ProcessingException {
if (randomStream != null) {
throw new ProcessingException("Trying to reinit the seed of the RNG although it is already initialized!");
}
randomStream = new MRG32k3a();
randomStream.setSeed(seed);
}
public ExponentialGen createExponentialGenFromMean(float mean) {
return new ExponentialGen(randomStream, new ExponentialDistFromMean(mean));
}
/**
* Pick out a float following a Normal law
*/
public float pickOutNormalLaw(float m, float std) {
return (float) NormalGen.nextDouble(randomStream, m, std);
}
public double pickOutNormalLaw(double m, double std) {
return NormalGen.nextDouble(randomStream, m, std);
}
/**
* Randomly permutes list. This method permutes the whole list.
* @param list the list to process
*/
public void shuffle(List list) {
RandomPermutation.shuffle(list, randomStream);
}
/**
* Picks randomly some elements from a list.
* @param <E>
* @param list
* @param nb the number of elements to pick out
* @return null, if nb <= 0
*/
public <E> List<E> pickElements(List<E> list, int nb) {
if (nb <= 0) {
return null;
}
List<E> result = new ArrayList<E>(nb);
List<E> copy = new ArrayList<E>(list);
for (int i = 0; i < nb; i++) {
int index = nextInt(0, copy.size() - 1);
result.add(copy.remove(index));
}
return result;
}
/**
* Build an array of indexes for randomly picking elements in a matrix.
* @param elements
* @return an array of two-dimensional indexes
*/
public List<int[]> buildRandomMatrixIndexes(Object[][] elements) {
List<int[]> indexes = new ArrayList<int[]>();
for (int i = 0; i < elements.length; i++) {
for (int j = 0; j < elements[i].length; j++) {
indexes.add(new int[]{i, j});
}
}
shuffle(indexes);
return indexes;
}
}
This diff is collapsed.
src/Tools.java 0 → 100644
import cern.colt.Arrays;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author oumou-raby.dia
*/
public class Tools {
public boolean go;
public boolean endFile;
public PrintStream writResult;
public String messageFileName;
public String country; // give the name of the experiment
public Tools() {
go = true;
}
//Lecture des données d'initialisation des agents
public float[][] lireExpDesignInitPop(int firstLine, int endLine, String name, int nbDimCulturel) {
go = true;
float[][] myPop = new float[0][0];
Workbook workbook = null;
try {
/* Récupération du classeur Excel (en lecture) */
workbook = Workbook.getWorkbook(new File(name));
/* Un fichier excel est composé de plusieurs feuilles, on y accède de la manière suivante*/
Sheet sheet = workbook.getSheet(0);
int a = 0;
if (firstLine >= sheet.getRows()) {
endFile = true;
go = false;
} else {
myPop = new float[nbDimCulturel * 2][0];
for (int j = firstLine; j <= endLine; j++) {
Cell[] lineExpe = sheet.getRow(j);
myPop[a] = readLineInitPop(lineExpe, nbDimCulturel);
a++;
}
go = false;
}
workbook.close();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
/* On ferme le worbook pour libérer la mémoire */
workbook.close();
}
}
return myPop;
}
public float[] readLineInitPop(Cell[] lineExpe, int nbDimCult) {
float[] toGenere = new float[13];
String[] expe = new String[lineExpe.length];
for (int i = 0; i < lineExpe.length; i++) {
expe[i] = (lineExpe[i].getContents()).replaceAll(",", ".");
}
country = expe[0];
messageFileName = expe[1];
float taillePop = (new Integer(expe[2])).intValue();
float dimAdhesion = -1.0f;
if ((expe[3]).equals("areligious")) {
dimAdhesion = 2.0f;
} else if ((expe[3]).equals("christians")) {
dimAdhesion = 1.0f;
} else { // is muslim
dimAdhesion = 0.0f;
}
float partTypeInPop = (new Float(expe[4])).floatValue();
float type = (new Float(expe[5])).floatValue();
float CWWlow1 = (new Float(expe[6])).floatValue();
float CWWadherence1 = (new Float(expe[7])).floatValue();
float CWWup1 = (new Float(expe[8])).floatValue();
float CWWlow2 = (new Float(expe[9])).floatValue();
float CWWadherence2 = (new Float(expe[10])).floatValue();
float CWWup2 = (new Float(expe[11])).floatValue();
float CWWlow3 = (new Float(expe[12])).floatValue();
float CWWadherence3 = (new Float(expe[13])).floatValue();
float CWWup3 = (new Float(expe[14])).floatValue();
int nbDimAdhes = Math.round(taillePop * partTypeInPop);
toGenere[0] = dimAdhesion;
toGenere[1] = nbDimAdhes;
toGenere[2] = type;
toGenere[3] = CWWlow1;
toGenere[4] = CWWadherence1;
toGenere[5] = CWWup1;
toGenere[6] = CWWlow2;
toGenere[7] = CWWadherence2;
toGenere[8] = CWWup2;
toGenere[9] = CWWlow3;
toGenere[10] = CWWadherence3;
toGenere[11] = CWWup3;
toGenere[12] = taillePop;
return toGenere;
}
public int[] readLineInitPopOld(Cell[] lineExpe, int nbDimCult) {
int[] toGenere = new int[8];
String[] expe = new String[lineExpe.length];
for (int i = 0; i < lineExpe.length; i++) {
expe[i] = (lineExpe[i].getContents()).replaceAll(",", ".");
}
country = expe[0];
messageFileName = expe[1];
int taillePop = (new Integer(expe[2])).intValue();
int dimAdhesion = (new Integer(expe[3])).intValue();
float partTypeInPop = (new Float(expe[4])).floatValue();
float partInclusiveInType = (new Float(expe[5])).floatValue();
float partExclusiveInType = (new Float(expe[6])).floatValue();
float partExtremInInclusif = (new Float(expe[7])).floatValue();
float partExtremInExclusif = (new Float(expe[8])).floatValue();
int nbDimAdhes = (int) (taillePop * partTypeInPop);
int inclus = (int) (nbDimAdhes * partInclusiveInType);
int exclus = nbDimAdhes - inclus;
int inclusExtr = (int) (inclus * partExtremInInclusif);
int exclusExtr = (int) (exclus * partExtremInExclusif);
toGenere[0] = dimAdhesion;
toGenere[1] = nbDimAdhes;
toGenere[2] = inclus;
toGenere[3] = exclus;
toGenere[4] = inclusExtr;
toGenere[5] = exclusExtr;
toGenere[6] = taillePop;
toGenere[7] = nbDimCult;
return toGenere;
}
public void ecritureInFileSourceStudyFromDataAVGSTD(String nomFile) {
try {
writResult = new PrintStream(new FileOutputStream(new File(nomFile)));
writResult.print("popFile" + ";" + "messageFile" + ";" + "nomExpe" + ";" + "numReplique" + ";" + "randomizedInitCWW" + ";" + "alpha" + ";" + "epsilon" + ";" + "nbPoints" + ";" + "nbDimCWW" + ";");
writResult.print("iteration" + ";"
+ "GroupOfAgent(2=Areligious,1=Christians,0=Muslims" + ";" + "typeOfAgent" +";" + "numberOfAgentOfThisType(AreligiousInclusive)"+ ";"
+ "GroupOfAgent(2=Areligious,1=Christians,0=Muslims" + ";" + "typeOfAgent" +";" + "numberOfAgentOfThisType(AreligiousExclusive)"+ ";"
+ "GroupOfAgent(2=Areligious,1=Christians,0=Muslims" + ";" + "typeOfAgent" +";" + "numberOfAgentOfThisType(ChristiansInclusive)"+ ";"
+ "GroupOfAgent(2=Areligious,1=Christians,0=Muslims" + ";" + "typeOfAgent" +";" + "numberOfAgentOfThisType(ChristiansExclusive)"+ ";"
+ "GroupOfAgent(2=Areligious,1=Christians,0=Muslims" + ";" + "typeOfAgent" +";" + "numberOfAgentOfThisType(MuslimsInclusive)"+ ";"
+ "GroupOfAgent(2=Areligious,1=Christians,0=Muslims" + ";" + "typeOfAgent" +";" + "numberOfAgentOfThisType(MuslimsExclusive)"+ ";"
+ "AverageOpinionOfGroup0onGroup0" + ";" + "STDDevOpinionOfGroup0onGroup0" + ";" + "AverageOpinionOfGroup0onGroup1" + ";" + "STDDevOpinionOfGroup0onGroup1" + ";" + "AverageOpinionOfGroup0onGroup2" + ";" + "STDDevOpinionOfGroup0onGroup2" + ";"
+ "AverageOpinionOfGroup1onGroup0" + ";" + "STDDevOpinionOfGroup1onGroup0" + ";" + "AverageOpinionOfGroup1onGroup1" + ";" + "STDDevOpinionOfGroup1onGroup1" + ";" + "AverageOpinionOfGroup1onGroup2" + ";" + "STDDevOpinionOfGroup1onGroup2" + ";"
+ "AverageOpinionOfGroup2onGroup0" + ";" + "STDDevOpinionOfGroup2onGroup0" + ";" + "AverageOpinionOfGroup2onGroup1" + ";" + "STDDevOpinionOfGroup2onGroup1" + ";" + "AverageOpinionOfGroup2onGroup2" + ";" + "STDDevOpinionOfGroup2onGroup2" + ";"
+ "AverageOpinionOfGroup0OnAllTheAgents" + ";" + "STDDevOpinionOfGroup0OnAllTheAgents" + ";" + "AverageOpinionOfGroup1OnAllTheAgents" + ";" + "STDDevOpinionOfGroup1OnAllTheAgents" + ";" + "AverageOpinionOfGroup2OnAllTheAgents" + ";" + "STDDevOpinionOfGroup2OnAllTheAgents" + ";"
+ "AverageOpinionOfAllOnGroup0members" + ";" + "STDDevOpinionOfAllOnGroup0members" + ";" + "AverageOpinionOfAllOnGroup1members" + ";" + "STDDevOpinionOfAllOnGroup1members" + ";" + "AverageOpinionOfAllOnGroup2members" + ";" + "STDDevOpinionOfAllOnGroup2members" + ";");
writResult.println();
} catch (Exception e) {
System.err.println("Erreur création du fichier pour le résultat de l'algorithme : " + e);
}
}
public void ecritureInFileSourceStudyFromDataDetails(String nomFile) { // for the method : writeImpactMessageWithAgentDetails
try {
writResult = new PrintStream(new FileOutputStream(new File(nomFile)));
writResult.print("popFile" + ";" + "messageFile" + ";" + "nomExpe" + ";" + "numReplique" + ";" + "randomizedInitCWW" + ";" + "alpha" + ";" + "epsilon" + ";" + "nbPoints" + ";" + "nbDimCWW" + ";");
writResult.print("iteration" + ";" + "numberOfAgentOfThisType" + ";" + "typeOfAgent" + ";" + "GroupOfAgent(2=Areligious,1=Christians,0=Muslims" + ";"
+ "AgentCWW0Muslim low" + ";" + "AgentCWW0Muslim mostAcceptablePosition" + ";" + "AgentCWW0Muslim up" + ";"
+ "AgentCWW1Christian low" + ";" + "AgentCWW1Christian mostAcceptablePosition" + ";" + "AgentCWW1Christian up" + ";"
+ "AgentCWW2Areligious low" + ";" + "AgentCWW2Areligious mostAcceptablePosition" + ";" + "AgentCWW2Areligious up" + ";"
+ "messageType(1=threat)" + ";" + "sourceMessagetype" + ";" + "groupOfTheSourceMessage" + ";"
+ "sourceCWW0MuslimMuslim low" + ";" + "sourceCWW0Muslim mostAcceptablePosition" + ";" + "sourceCWW0Muslim up" + ";"
+ "sourceCWW1Christian low" + ";" + "sourceCWW1Christian mostAcceptablePosition" + ";" + "sourceCWW1Christian up" + ";"
+ "sourceCWW2Areligious low" + ";" + "sourceCWW2Areligious mostAcceptablePosition" + ";" + "sourceCWW2Areligious up" + ";"
+ "averageOpinionOfThisTypeOfAgentOnSourceBeforeMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceAfterMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceThreatBeforeMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceThreatAfterMessage" + ";"
+ "averageOpinionOfThisTypeOfAgentOnSourceMuslimInclusifBeforeMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceMuslimInclusifAfterMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceMuslimExclusifBeforeMessage" + ";"
+ "averageOpinionOfThisTypeOfAgentOnSourceMuslimExclusifAfterMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceAreligiousInclusifBeforeMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceAreligiousInclusifAfterMessage" + ";"
+ "averageOpinionOfThisTypeOfAgentOnSourceAreligiousExclusifBeforeMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceAreligiousExclusifAfterMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceChristiansInclusifBeforeMessage" + ";"
+ "averageOpinionOfThisTypeOfAgentOnSourceChristiansInclusifAfterMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceChristiansExclusifBeforeMessage" + ";" + "averageOpinionOfThisTypeOfAgentOnSourceChristiansExclusifAfterMessage" + ";"
+ "distAutruiOnlyMeChanged" + ";" + "distAutruiOtherAndMeChanged" + ";" + "distIntraGroupSeeMeOnly" + ";" + "distIntraGroupSeeOthers" + ";" + "knowsAboutOthers" + ";"
+ "averageOpinionOfThisTypeOfAgentOnEveryone" + ";" + "averageOpinionOfThisTypeOfAgentOnGroup0Muslim" + ";" + "averageOpinionOfThisTypeOfAgentOn1Christian" + ";" + "averageOpinionOfThisTypeOfAgentOnGroup2Areligious" + ";");
writResult.println();
} catch (Exception e) {
System.err.println("Erreur création du fichier pour le résultat de l'algorithme : " + e);
}
}
//label message, indiv source (ou pas), source type, source group, source cwws, opinion receiver on source avant message, opinion receiver on source après message
//Lecture des données d'initialisation des agents
public float[][] lireExpDesignInitMessages(String name) {
float[][] myMessages = new float[0][0];
Workbook workbook = null;
try {
/* Récupération du classeur Excel (en lecture) */
workbook = Workbook.getWorkbook(new File(name));
/* Un fichier excel est composé de plusieurs feuilles, on y accède de la manière suivante*/
Sheet sheet = workbook.getSheet(0);
int nbMessages = sheet.getRows() - 1;
myMessages = new float[nbMessages][0];
for (int j = 0; j < nbMessages; j++) {
Cell[] lineExpe = sheet.getRow(j + 1);
myMessages[j] = readLineInitMessage(lineExpe);
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
/* On ferme le worbook pour libérer la mémoire */
workbook.close();
}
}
return myMessages;
}
public float[] readLineInitMessage(Cell[] lineExpe) {
float[] toGenere = new float[lineExpe.length];
String[] expe = new String[lineExpe.length];
for (int i = 0; i < lineExpe.length; i++) {
expe[i] = (lineExpe[i].getContents()).replaceAll(",", ".");
}
toGenere[0] = 2; // 2 is a compassion message
if (expe[0].equals(new String("threat"))) {
toGenere[0] = 1; // 1 is a threat
}
for (int i = 1; i < lineExpe.length; i++) {
toGenere[i] = (new Float(expe[i])).floatValue(); // series of triplets : low CWW, adherence CWW, up CWW to characteriste the cultural world view of the source
}
return toGenere;
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment