1
0
This commit is contained in:
2025-10-10 02:12:44 +02:00
commit dac3abf431
212 changed files with 475579 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
package adda.ej1;
import java.util.Locale;
import adda.ej1.common.InRangeVerdurasAG;
import adda.util.Titles;
import us.lsi.ag.agchromosomes.AlgoritmoAG;
import us.lsi.ag.agstopping.StoppingConditionFactory;
public class TestHuertosAG {
@SuppressWarnings({ "rawtypes" })
private static void test(String fichero) {
Locale.setDefault(Locale.of("en", "US"));
AlgoritmoAG.ELITISM_RATE = 0.10;
AlgoritmoAG.CROSSOVER_RATE = 0.95;
AlgoritmoAG.MUTATION_RATE = 0.8;
AlgoritmoAG.POPULATION_SIZE = 1000;
StoppingConditionFactory.NUM_GENERATIONS = 1000;
StoppingConditionFactory.stoppingConditionType =
StoppingConditionFactory.StoppingConditionType.GenerationCount;
InRangeVerdurasAG p = new InRangeVerdurasAG(fichero);
AlgoritmoAG alg = AlgoritmoAG.of(p);
alg.ejecuta();
System.out.println("================================");
System.out.println(alg.bestSolution());
System.out.println("================================");
}
public static void main(String[] args) {
System.out.println(Titles.F1);
test("ficheros/ej1/Ejercicio1DatosEntrada1.txt");
System.out.println(Titles.F2);
test("ficheros/ej1/Ejercicio1DatosEntrada2.txt");
System.out.println(Titles.F3);
test("ficheros/ej1/Ejercicio1DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,30 @@
package adda.ej1;
import java.io.IOException;
import java.util.Locale;
import adda.ej1.common.DatosHuertos;
import adda.util.Titles;
import us.lsi.gurobi.GurobiLp;
import us.lsi.gurobi.GurobiSolution;
import us.lsi.solve.AuxGrammar;
public class TestHuertosPLE {
public static void model(String fichero) throws IOException {
DatosHuertos.iniDatos(fichero);
AuxGrammar.generate(DatosHuertos.class, "modelos/ej1.lsi", "modelos/gurobi/ej1.lp");
Locale.setDefault(Locale.of("en", "US"));
GurobiSolution solution = GurobiLp.gurobi("modelos/gurobi/ej1.lp");
System.out.println(solution.toString());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.of("en", "US"));
System.out.println(Titles.F1);
model("ficheros/ej1/Ejercicio1DatosEntrada1.txt");
System.out.println(Titles.F2);
model("ficheros/ej1/Ejercicio1DatosEntrada2.txt");
System.out.println(Titles.F3);
model("ficheros/ej1/Ejercicio1DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,90 @@
package adda.ej1.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import us.lsi.common.Files2;
import us.lsi.common.String2;
public class DatosHuertos {
public static int N;
public static int M;
private static List<Verdura> verduras;
private static List<Huerto> huertos;
public static record Huerto(String nombre, Integer metrosDisponibles) {
public static Huerto of(String s) {
s = s.replace(";", "");
String[] partes = s.split(": metrosdisponibles=");
return new Huerto(partes[0], Integer.valueOf(partes[1]));
}
}
public static record Verdura(String nombre, Integer metrosRequeridos, List<String> incompatibles) {
public static Verdura of(String s) {
s = s.replace(" -> metrosrequeridos=", ";").replace(" incomp=", "");
String[] partes = s.split(";");
return new Verdura(partes[0], Integer.valueOf(partes[1]), Arrays.asList(partes[2].split(",")));
}
}
public static void toConsole() {
String2.toConsole(huertos, "Huertos de verdura:");
String2.toConsole(verduras, "Verduras:");
String2.toConsole(String2.linea());
}
public static void iniDatos(String fichero) {
List<String> lineas = Files2.linesFromFile(fichero);
Integer aux = lineas.indexOf("// VARIEDADES");
List<String> h = lineas.subList(1, aux);
List<String> v = lineas.subList(aux + 1, lineas.size());
huertos = new ArrayList<>();
for(String huerto : h) {
huertos.add(Huerto.of(huerto));
}
verduras = new ArrayList<>();
for(String verdura : v) {
verduras.add(Verdura.of(verdura));
}
N = verduras.size();
M = huertos.size();
// toConsole();
}
public static Verdura getVerdura(Integer i) {
return verduras.get(i);
}
public static Huerto getHuerto(Integer j) {
return huertos.get(j);
}
public static Integer getN() {
return N;
}
public static Integer getM() {
return M;
}
public static Integer getMetrosRequeridos(Integer i) {
return verduras.get(i).metrosRequeridos();
}
public static Integer getMetrosDisponibles(Integer j) {
return huertos.get(j).metrosDisponibles();
}
public static Integer incompatible(Integer i, Integer k) {
return verduras.get(i).incompatibles().contains(verduras.get(k).nombre()) ? 1 : 0;
}
public static void main(String[] args) {
iniDatos("ficheros/ej1/Ejercicio1DatosEntrada1.txt");
}
}

View File

@@ -0,0 +1,98 @@
package adda.ej1.common;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import adda.ej1.common.DatosHuertos.Huerto;
import adda.ej1.common.DatosHuertos.Verdura;
import us.lsi.ag.ValuesInRangeData;
import us.lsi.ag.agchromosomes.ChromosomeFactory.ChromosomeType;
public class InRangeVerdurasAG implements ValuesInRangeData<Integer, SolucionHuertos>{
public InRangeVerdurasAG(String fichero) {
DatosHuertos.iniDatos(fichero);
}
@Override
public Integer size() {
// TODO Auto-generated method stub
return DatosHuertos.getN();
}
@Override
public ChromosomeType type() {
// TODO Auto-generated method stub
return ChromosomeType.Range;
}
@Override
public Double fitnessFunction(List<Integer> ls) {
// TODO Auto-generated method stub
Double goal = (double) ls.stream().filter(n -> n > 0).count();
Double error = 0.;
Map<Huerto, List<Verdura>> huertoVerduras = new HashMap<>();
for(int i = 0; i < size(); i++) {
if(ls.get(i) > 0) {
Huerto huerto = DatosHuertos.getHuerto(ls.get(i) - 1);
if(huertoVerduras.containsKey(huerto)) {
Verdura verdura = DatosHuertos.getVerdura(i);
huertoVerduras.get(huerto).add(verdura);
} else {
Verdura verdura = DatosHuertos.getVerdura(i);
huertoVerduras.put(huerto, new ArrayList<>(List.of(verdura)));
}
}
}
error += penalizacionIncompatibilidad(huertoVerduras);
error += huertoVerduras.entrySet().stream()
.mapToInt(
e -> Math.abs(e.getKey().metrosDisponibles() -
e.getValue().stream()
.mapToInt(Verdura::metrosRequeridos)
.sum())
).sum();
return goal - 100000 * error;
}
private double penalizacionIncompatibilidad(Map<Huerto, List<Verdura>> huertoVerduras) {
double error = 0.;
for(Entry<Huerto, List<Verdura>> e: huertoVerduras.entrySet()) {
for(int i = 0; i < e.getValue().size() - 1; i++) {
List<Verdura> vs = e.getValue();
boolean b = vs.get(i).incompatibles().contains(vs.get(i+1).nombre());
error += b ? 1000 : 0;
}
}
return error;
}
@Override
public SolucionHuertos solucion(List<Integer> ls) {
// TODO Auto-generated method stub
return SolucionHuertos.of_range(ls);
}
@Override
public Integer max(Integer i) {
// TODO Auto-generated method stub
return DatosHuertos.getM() + 1;
}
@Override
public Integer min(Integer i) {
// TODO Auto-generated method stub
return 0;
}
}

View File

@@ -0,0 +1,50 @@
package adda.ej1.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import adda.ej1.common.DatosHuertos.Huerto;
import adda.ej1.common.DatosHuertos.Verdura;
import us.lsi.common.Pair;
public class SolucionHuertos {
private static int index;
private static Integer distintas;
private static List<Pair<Verdura, Huerto>> solucion;
public static SolucionHuertos of_range(List<Integer> ls) {
return new SolucionHuertos(ls);
}
public SolucionHuertos() {
distintas = 0;
solucion = new ArrayList<>();
}
public SolucionHuertos(List<Integer> ls) {
index = 0;
solucion = new ArrayList<>();
ls.stream().forEach(hue -> {
if(hue > 0) {
Verdura v = DatosHuertos.getVerdura(index);
Huerto h = DatosHuertos.getHuerto(hue - 1);
solucion.add(Pair.of(v, h));
}
index++;
});
distintas = (int) solucion.stream()
.map(p -> p.first())
.distinct().count();
}
public String toString() {
String verduras = solucion.stream()
.map(p -> p.first().nombre() + ": Huerto " + p.second().nombre().replace("H", ""))
.collect(Collectors.joining("\n ", "Reparto de verduras y huerto en el que es plantada " +
"cada una de ellas (si procede):\n ", "\n"));
return String.format("%sVariedades cultivadas: %d", verduras, distintas);
}
}

View File

@@ -0,0 +1,40 @@
package adda.ej2;
import java.util.Locale;
import adda.ej2.common.BinaryCestaAG;
import adda.util.Titles;
import us.lsi.ag.agchromosomes.AlgoritmoAG;
import us.lsi.ag.agstopping.StoppingConditionFactory;
public class TestCestaAG {
@SuppressWarnings({ "rawtypes" })
private static void test(String fichero) {
Locale.setDefault(Locale.of("en", "US"));
AlgoritmoAG.ELITISM_RATE = 0.10;
AlgoritmoAG.CROSSOVER_RATE = 0.9;
AlgoritmoAG.MUTATION_RATE = 0.75;
AlgoritmoAG.POPULATION_SIZE = 1000;
StoppingConditionFactory.NUM_GENERATIONS = 1000;
StoppingConditionFactory.stoppingConditionType = StoppingConditionFactory.StoppingConditionType.GenerationCount;
BinaryCestaAG p = new BinaryCestaAG(fichero);
AlgoritmoAG alg = AlgoritmoAG.of(p);
alg.ejecuta();
System.out.println("================================");
System.out.println(alg.bestSolution());
System.out.println("================================");
}
public static void main(String[] args) {
System.out.println(Titles.F1);
test("ficheros/ej2/Ejercicio2DatosEntrada1.txt");
System.out.println(Titles.F2);
test("ficheros/ej2/Ejercicio2DatosEntrada2.txt");
System.out.println(Titles.F3);
test("ficheros/ej2/Ejercicio2DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,30 @@
package adda.ej2;
import java.io.IOException;
import java.util.Locale;
import adda.ej2.common.DatosCesta;
import adda.util.Titles;
import us.lsi.gurobi.GurobiLp;
import us.lsi.gurobi.GurobiSolution;
import us.lsi.solve.AuxGrammar;
public class TestCestaPLE {
public static void model(String fichero) throws IOException {
DatosCesta.iniDatos(fichero);
AuxGrammar.generate(DatosCesta.class, "modelos/ej2.lsi", "modelos/gurobi/ej2.lp");
Locale.setDefault(Locale.of("en", "US"));
GurobiSolution solution = GurobiLp.gurobi("modelos/gurobi/ej2.lp");
System.out.println(solution.toString());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.of("en", "US"));
System.out.println(Titles.F1);
model("ficheros/ej2/Ejercicio2DatosEntrada1.txt");
System.out.println(Titles.F2);
model("ficheros/ej2/Ejercicio2DatosEntrada2.txt");
System.out.println(Titles.F3);
model("ficheros/ej2/Ejercicio2DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,85 @@
package adda.ej2.common;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import adda.ej2.common.DatosCesta.Producto;
import us.lsi.ag.BinaryData;
public class BinaryCestaAG implements BinaryData<SolucionCesta>{
public BinaryCestaAG(String fichero) {
DatosCesta.iniDatos(fichero);
}
@Override
public Integer size() {
// TODO Auto-generated method stub
return DatosCesta.getN();
}
@Override
public Double fitnessFunction(List<Integer> ls) {
double goal = 0., error = 0.;
List<Producto> productos = new ArrayList<>();
if(ls.stream().filter(p -> p == 1).count() < DatosCesta.getM()) {
error += 1000000000;
} else {
// goal de precio
goal += getGoal(ls, productos);
// no cubrir todas las categorias
error += cumpleOrErrorSquared(productos.stream()
.map(Producto::categoria).distinct().count(),
p -> p.equals((long) DatosCesta.getM()));
// no cumplir media > 3
error += cumpleOrErrorSquared(productos.stream()
.mapToDouble(Producto::valoracion).sum()
- 3 * ls.stream().filter(p -> p > 0).count(), p -> p > 0);
// superar limite de presupuesto por categoria
error += cumpleOrError(
productos.stream().collect(
Collectors.groupingBy(Producto::categoria, Collectors.summingInt(Producto::precio))),
p -> p <= DatosCesta.getPresupuesto());
}
return -goal - 1000000000 * error;
}
private double getGoal(List<Integer> ls, List<Producto> productos) {
double res = 0.;
for(int i = 0; i < ls.size(); i++) {
if(ls.get(i) > 0) {
Producto p = DatosCesta.getProducto(i);
productos.add(p);
res += p.precio();
}
}
return res;
}
private <T extends Number> double cumpleOrErrorSquared(T res, Predicate<T> p) {
return p.test(res) ? 0. : Math.pow(res.doubleValue() * 10, 2);
}
private double cumpleOrError(Map<Integer, Integer> res, Predicate<Double> p) {
double ac = 0.;
for(Entry<Integer, Integer> e : res.entrySet()) {
double sum = e.getValue();
ac += p.test(sum) ? 0 : sum;
}
return Math.pow(ac, 2);
}
@Override
public SolucionCesta solucion(List<Integer> ls) {
// TODO Auto-generated method stub
return SolucionCesta.of_list(ls);
}
}

View File

@@ -0,0 +1,85 @@
package adda.ej2.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import us.lsi.common.Files2;
import us.lsi.common.String2;
public class DatosCesta {
public static int N; // productos
public static int M; // categorias
public static int PRES;
private static List<Producto> productos;
private static List<Integer> categorias;
public static record Producto(Integer id, Integer precio, Integer categoria, Integer valoracion) {
public static Producto of(String s) {
List<Integer> datos = Stream.of(s.split(":"))
.map(Integer::valueOf).toList();
return new Producto(datos.get(0), datos.get(1), datos.get(2), datos.get(3));
}
}
public static void toConsole() {
String2.toConsole("Presupuesto: %d", PRES);
String2.toConsole(productos, "Cesta de productos:");
String2.toConsole(String2.linea());
}
public static void iniDatos(String fichero) {
List<String> lineas = Files2.linesFromFile(fichero);
List<String> productosStrings = lineas.subList(2, lineas.size());
PRES = Integer.valueOf(lineas.get(0).replace("Presupuesto = ", ""));
productos = new ArrayList<>();
for(String producto : productosStrings) {
productos.add(Producto.of(producto));
}
categorias = productos.stream().map(Producto::categoria).distinct().toList();
N = productos.size();
M = (int) productos.stream()
.map(Producto::categoria)
.distinct().count();
}
public static Integer getN() {
return N;
}
public static Integer getM() {
return M;
}
public static Integer getPrecio(Integer i) {
return productos.get(i).precio();
}
public static Integer getValoracion(Integer i) {
return productos.get(i).valoracion();
}
public static Integer getCategoria(Integer i) {
return productos.get(i).categoria();
}
public static Integer tieneCategoria(Integer i, Integer j) {
return productos.get(i).categoria.equals(categorias.get(j)) ? 1 : 0;
}
public static Integer getPresupuesto() {
return PRES;
}
public static Producto getProducto(int i) {
return productos.get(i);
}
public static void main(String[] args) {
iniDatos("ficheros/ej2/Ejercicio2DatosEntrada1.txt");
}
}

View File

@@ -0,0 +1,37 @@
package adda.ej2.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class SolucionCesta {
private static Integer precioTotal;
private static List<Integer> solucion;
public static SolucionCesta of_list(List<Integer> ls) {
return new SolucionCesta(ls);
}
public SolucionCesta() {
precioTotal = 0;
solucion = new ArrayList<>();
}
public SolucionCesta(List<Integer> ls) {
solucion = new ArrayList<>();
precioTotal = 0;
for(int i = 0; i < ls.size(); i++) {
if(ls.get(i) > 0) {
precioTotal += DatosCesta.getProducto(i).precio();
solucion.add(DatosCesta.getProducto(i).id());
}
}
}
public String toString() {
String productos = solucion.stream()
.map(x -> "Producto " + x)
.collect(Collectors.joining(", ", "Productos elegidos: {", "}\n"));
return String.format("%sPrecio total de la cesta: %d", productos, precioTotal);
}
}

View File

@@ -0,0 +1,40 @@
package adda.ej3;
import java.util.Locale;
import adda.ej3.common.InRangeProductosTransportesAG;
import adda.util.Titles;
import us.lsi.ag.agchromosomes.AlgoritmoAG;
import us.lsi.ag.agstopping.StoppingConditionFactory;
public class TestProductosTransportesAG {
@SuppressWarnings({ "rawtypes" })
private static void test(String fichero) {
Locale.setDefault(Locale.of("en", "US"));
AlgoritmoAG.ELITISM_RATE = 0.20;
AlgoritmoAG.CROSSOVER_RATE = 0.95;
AlgoritmoAG.MUTATION_RATE = 0.8;
AlgoritmoAG.POPULATION_SIZE = 1000;
StoppingConditionFactory.NUM_GENERATIONS = 1000;
StoppingConditionFactory.stoppingConditionType = StoppingConditionFactory.StoppingConditionType.GenerationCount;
InRangeProductosTransportesAG p = new InRangeProductosTransportesAG(fichero);
AlgoritmoAG alg = AlgoritmoAG.of(p);
alg.ejecuta();
System.out.println("================================");
System.out.println(alg.bestSolution());
System.out.println("================================");
}
public static void main(String[] args) {
System.out.println(Titles.F1);
test("ficheros/ej3/Ejercicio3DatosEntrada1.txt");
System.out.println(Titles.F2);
test("ficheros/ej3/Ejercicio3DatosEntrada2.txt");
System.out.println(Titles.F3);
test("ficheros/ej3/Ejercicio3DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,30 @@
package adda.ej3;
import java.io.IOException;
import java.util.Locale;
import adda.ej3.common.DatosProductosTransportes;
import adda.util.Titles;
import us.lsi.gurobi.GurobiLp;
import us.lsi.gurobi.GurobiSolution;
import us.lsi.solve.AuxGrammar;
public class TestProductosTransportesPLE {
public static void model(String fichero) throws IOException {
DatosProductosTransportes.iniDatos(fichero);
AuxGrammar.generate(DatosProductosTransportes.class, "modelos/ej3.lsi", "modelos/gurobi/ej3.lp");
Locale.setDefault(Locale.of("en", "US"));
GurobiSolution solution = GurobiLp.gurobi("modelos/gurobi/ej3.lp");
System.out.println(solution.toString());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.of("en", "US"));
System.out.println(Titles.F1);
model("ficheros/ej3/Ejercicio3DatosEntrada1.txt");
System.out.println(Titles.F2);
model("ficheros/ej3/Ejercicio3DatosEntrada2.txt");
System.out.println(Titles.F3);
model("ficheros/ej3/Ejercicio3DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,90 @@
package adda.ej3.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import us.lsi.common.Files2;
import us.lsi.common.String2;
public class DatosProductosTransportes {
public static int N; // productos
public static int M; // destinos
public static List<Destino> destinos;
public static List<Producto> productos;
public static record Destino(Integer id, Integer demanda) {
public static Destino of(String s) {
String[] partes = s.replaceAll("D(\\d+): demandaminima=(\\d+);", "$1,$2").split(",");
return new Destino(Integer.valueOf(partes[0]), Integer.valueOf(partes[1]));
}
}
public static record Producto(Integer id, Integer cantidad, List<Integer> coste) {
public static Producto of(String s) {
String[] partes = s.replace(" -> uds=", ";").replace(" coste_almacenamiento=", "").split(";");
String[] costes = partes[2].replaceAll("\\([0-9]+:", "").replace(")", "").split(",");
return new Producto(Integer.valueOf(partes[0].substring(1)), Integer.valueOf(partes[1]),
Stream.of(costes).map(Integer::valueOf).collect(Collectors.toList()));
}
}
public static void toConsole() {
String2.toConsole(destinos, "Destinos posibles:");
String2.toConsole(productos, "Productos del distribuidor:");
String2.toConsole(String2.linea());
}
public static void iniDatos(String fichero) {
List<String> lineas = Files2.linesFromFile(fichero);
Integer aux = lineas.indexOf("// PRODUCTOS Id_producto -> unidades=integer;coste_almacenamiento=(destino:coste)");
List<String> d = lineas.subList(1, aux);
List<String> p = lineas.subList(aux + 1, lineas.size());
destinos = new ArrayList<>();
for(String destino : d) {
destinos.add(Destino.of(destino));
}
productos = new ArrayList<>();
for(String producto : p) {
productos.add(Producto.of(producto));
}
N = productos.size();
M = destinos.size();
}
public static Integer getN() {
return N;
}
public static Integer getM() {
return M;
}
public static Integer getCantidad(Integer i) {
return productos.get(i).cantidad();
}
public static Integer getDemanda(Integer j) {
return destinos.get(j).demanda();
}
public static Integer getCoste(Integer i, Integer j) {
return productos.get(i).coste().get(j);
}
public static Producto getProducto(int i) {
return productos.get(i);
}
public static List<Destino> getDestinos() {
return destinos;
}
public static void main(String[] args) {
iniDatos("ficheros/ej3/Ejercicio3DatosEntrada1.txt");
}
}

View File

@@ -0,0 +1,100 @@
package adda.ej3.common;
import java.util.List;
import us.lsi.ag.AuxiliaryAg;
import us.lsi.ag.ValuesInRangeData;
import us.lsi.ag.agchromosomes.ChromosomeFactory.ChromosomeType;
public class InRangeProductosTransportesAG implements ValuesInRangeData<Integer, SolucionProductosTransportes> {
private static Integer prods;
private static Integer dests;
public InRangeProductosTransportesAG(String fichero) {
DatosProductosTransportes.iniDatos(fichero);
prods = DatosProductosTransportes.getN();
dests = DatosProductosTransportes.getM();
}
@Override
public Integer size() {
// TODO Auto-generated method stub
return prods * dests;
}
@Override
public ChromosomeType type() {
// TODO Auto-generated method stub
return ChromosomeType.Range;
}
@Override
public Double fitnessFunction(List<Integer> ls) {
double goal = getCoste(ls);
double errorDem = penalizaDemanda(ls);
double errorProd = penalizaProductos(ls);
double error = errorDem + errorProd;
return -goal - 100000000 * error;
}
private double getCoste(List<Integer> ls) {
double res = 0.;
for(int i = 0; i < prods; i++) {
for(int j = 0; j < dests; j++) {
int pos = i * dests + j;
res += ls.get(pos) * DatosProductosTransportes.getCoste(i, j);
}
}
return res;
}
private double penalizaDemanda(List<Integer> ls) {
double res = 0.;
for(int j = 0; j < dests; j++) {
double dem = 0.;
for(int i = 0; i < prods; i++) {
int pos = i * dests + j;
dem += ls.get(pos);
}
res += AuxiliaryAg.distanceToEqZero(dem -
DatosProductosTransportes.getDestinos().get(j).demanda());
res += 1000 * AuxiliaryAg.distanceToGeZero(dem -
DatosProductosTransportes.getDestinos().get(j).demanda());
}
return res;
}
private double penalizaProductos(List<Integer> ls) {
double res = 0.;
for(int i = 0; i < prods; i++) {
double cantDest = 0.;
for(int j = 0; j < dests; j++) {
int pos = i * dests + j;
cantDest += ls.get(pos);
}
res += AuxiliaryAg.distanceToLeZero(cantDest -
DatosProductosTransportes.getProducto(i).cantidad());
}
return res;
}
@Override
public SolucionProductosTransportes solucion(List<Integer> ls) {
// TODO Auto-generated method stub
return SolucionProductosTransportes.of_range(ls);
}
@Override
public Integer max(Integer i) {
// TODO Auto-generated method stub
return DatosProductosTransportes.getProducto(i / DatosProductosTransportes.getM()).cantidad() + 1;
}
@Override
public Integer min(Integer i) {
// TODO Auto-generated method stub
return 0;
}
}

View File

@@ -0,0 +1,45 @@
package adda.ej3.common;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class SolucionProductosTransportes {
private static Map<Integer, List<Integer>> solucion;
private static Integer costeTotal;
public static SolucionProductosTransportes of_range(List<Integer> ls) {
return new SolucionProductosTransportes(ls);
}
public SolucionProductosTransportes() {
solucion = new HashMap<>();
costeTotal = 0;
}
public SolucionProductosTransportes(List<Integer> ls) {
solucion = new HashMap<>();
costeTotal = 0;
for(int i = 0; i < DatosProductosTransportes.getN(); i++) {
solucion.put(i, new ArrayList<>());
for(int j = 0; j < DatosProductosTransportes.getM(); j++) {
solucion.get(i).add(ls.get(i * DatosProductosTransportes.getM() + j));
costeTotal += ls.get(i * DatosProductosTransportes.getM() + j) *
DatosProductosTransportes.getCoste(i, j);
}
}
}
public String toString() {
String productos = solucion.entrySet().stream()
.map(e -> e.getKey() + ": " + e.getValue())
.collect(Collectors.joining("\n",
"Reparto obtenido (cantidad de producto repartido a cada destino):\n" +
"//Destino m:[cantidad de producto n, cantidad de producto n+1, ...]\n",
"\n"));
return String.format("%sCoste total de almacenamiento: %d", productos, costeTotal);
}
}

View File

@@ -0,0 +1,40 @@
package adda.ej4;
import java.util.Locale;
import adda.ej4.common.PermutationPersonasAG;
import adda.util.Titles;
import us.lsi.ag.agchromosomes.AlgoritmoAG;
import us.lsi.ag.agstopping.StoppingConditionFactory;
public class TestPersonasAG {
@SuppressWarnings({ "rawtypes" })
private static void test(String fichero) {
Locale.setDefault(Locale.of("en", "US"));
AlgoritmoAG.ELITISM_RATE = 0.20;
AlgoritmoAG.CROSSOVER_RATE = 0.95;
AlgoritmoAG.MUTATION_RATE = 0.8;
AlgoritmoAG.POPULATION_SIZE = 1000;
StoppingConditionFactory.NUM_GENERATIONS = 1000;
StoppingConditionFactory.stoppingConditionType = StoppingConditionFactory.StoppingConditionType.GenerationCount;
PermutationPersonasAG p = new PermutationPersonasAG(fichero);
AlgoritmoAG alg = AlgoritmoAG.of(p);
alg.ejecuta();
System.out.println("================================");
System.out.println(alg.bestSolution());
System.out.println("================================");
}
public static void main(String[] args) {
System.out.println(Titles.F1);
test("ficheros/ej4/Ejercicio4DatosEntrada1.txt");
System.out.println(Titles.F2);
test("ficheros/ej4/Ejercicio4DatosEntrada2.txt");
System.out.println(Titles.F3);
test("ficheros/ej4/Ejercicio4DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,83 @@
package adda.ej4.common;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import us.lsi.common.Files2;
import us.lsi.common.String2;
public class DatosPersonas {
private static int N;
private static List<Persona> personas;
public static record Persona(Integer id, Integer edad, Set<String> idiomas,
String nacionalidad, List<Integer> afinidades) {
public static Persona of(String s) {
String[] partes = s.replaceAll("P(\\d+) -> ", "$1; ")
.replaceAll("\\s\\w+=","").split(";");
return new Persona(
Integer.valueOf(partes[0]),
Integer.valueOf(partes[1]),
Set.of(partes[2].replaceAll("[()\\s]","").split(",")),
partes[3],
List.of(partes[4].replaceAll("\\((\\d+):(\\d+)\\)", "$2").split(",")).stream()
.map(Integer::valueOf)
.toList()
);
}
}
public static void toConsole() {
String2.toConsole(personas, "Personas posibles:");
String2.toConsole(String2.linea());
}
public static void iniDatos(String fichero) {
List<String> lineas = Files2.linesFromFile(fichero);
List<String> personasStrings = lineas.subList(1, lineas.size());
personas = new ArrayList<>();
for(String persona : personasStrings) {
personas.add(Persona.of(persona));
}
N = personas.size();
}
public static Integer getN() {
return N;
}
public static Integer getAfinidad(Integer i, Integer j) {
j = i > j ? j : j - 1;
return personas.get(i).afinidades().get(j);
}
public static Integer getEdad(Integer i) {
return personas.get(i).edad();
}
public static Set<String> getIdiomas(Integer i) {
return personas.get(i).idiomas();
}
public static String getNacionalidad(Integer i) {
return personas.get(i).nacionalidad();
}
public static Boolean idiomaComun(Integer i, Integer j) {
Set<String> idiomas = new HashSet<>(personas.get(i).idiomas());
idiomas.retainAll(personas.get(j).idiomas());
return idiomas.size() >= 1;
}
public static Boolean mismaNacionalidad(Integer i, Integer j) {
return personas.get(i).nacionalidad().equals(personas.get(j).nacionalidad());
}
public static Boolean maximaDiferenciaEdad(Integer i, Integer j) {
return Math.abs(personas.get(i).edad() - personas.get(j).edad()) <= 5;
}
}

View File

@@ -0,0 +1,46 @@
package adda.ej4.common;
import java.util.List;
import us.lsi.ag.SeqNormalData;
import us.lsi.ag.agchromosomes.ChromosomeFactory.ChromosomeType;
public class PermutationPersonasAG implements SeqNormalData<SolucionPersonas> {
public PermutationPersonasAG(String fichero) {
DatosPersonas.iniDatos(fichero);
}
@Override
public ChromosomeType type() {
// TODO Auto-generated method stub
return ChromosomeType.Permutation;
}
@Override
public Double fitnessFunction(List<Integer> ls) {
double error = 0., goal = 0.;
for(int i = 0; i < ls.size() - 1; i+=2) {
goal += DatosPersonas.getAfinidad(ls.get(i), ls.get(i+1));
if(!DatosPersonas.idiomaComun(ls.get(i), ls.get(i+1))
|| DatosPersonas.mismaNacionalidad(ls.get(i), ls.get(i+1))
|| DatosPersonas.maximaDiferenciaEdad(ls.get(i), ls.get(i+1))) {
error += 10000;
}
}
return goal - 1000000 * error;
}
@Override
public SolucionPersonas solucion(List<Integer> ls) {
// TODO Auto-generated method stub
return SolucionPersonas.of_list(ls);
}
@Override
public Integer itemsNumber() {
// TODO Auto-generated method stub
return DatosPersonas.getN();
}
}

View File

@@ -0,0 +1,37 @@
package adda.ej4.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import us.lsi.common.Pair;
public class SolucionPersonas {
private static List<Pair<Integer,Integer>> solucion;
private static Integer sumaAf;
public static SolucionPersonas of_list(List<Integer> ls) {
return new SolucionPersonas(ls);
}
public SolucionPersonas() {
sumaAf = 0;
solucion = new ArrayList<>();
}
public SolucionPersonas(List<Integer> ls) {
sumaAf = 0;
solucion = new ArrayList<>();
for(int i = 0; i < ls.size() - 1; i+=2) {
solucion.add(Pair.of(ls.get(i), ls.get(i+1)));
sumaAf += DatosPersonas.getAfinidad(ls.get(i), ls.get(i+1));
}
}
public String toString() {
String personas = solucion.stream()
.map(p -> "(" + p.first() + ", " + p.second() + ")")
.collect(Collectors.joining(", ", "Relación de parejas:\n[", "]\n"));
return String.format("%sSuma de afinidades: %d", personas, sumaAf);
}
}

View File

@@ -0,0 +1,41 @@
package adda.util;
public class Titles {
public static String F1 =
"""
####### ### # ####### #
# # # # ##
# # # # # #
##### # # ##### #
# # # # #
# # # # #
# ### ####### ####### #####
""";
public static String F2 =
"""
\n\n\n
####### ### # ####### #####
# # # # # #
# # # # #
##### # # ##### #####
# # # # #
# # # # #
# ### ####### ####### #######
""";
public static String F3 =
"""
\n\n\n
####### ### # ####### #####
# # # # # #
# # # # #
##### # # ##### #####
# # # # #
# # # # # #
# ### ####### ####### #####
""";
}

10
PI4/src/module-info.java Normal file
View File

@@ -0,0 +1,10 @@
module PI4 {
requires solve;
requires partecomun;
requires geneticos;
requires datos_compartidos;
exports adda.ej1;
exports adda.ej2;
exports adda.ej3;
exports adda.ej4;
}