repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedHomoQuantizedSpikingNonDirectionalDistributed.java
package it.units.erallab.evolution.builder.robot; import it.units.erallab.evolution.builder.PrototypedFunctionBuilder; import it.units.erallab.hmsrobots.core.controllers.DistributedSensingNonDirectional; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedDistributedSpikingSensing; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedLIFNeuron; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedMultivariateSpikingFunction; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedValueToSpikeTrainConverter; import it.units.erallab.hmsrobots.core.objects.Robot; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.SerializationUtils; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; /** * @author eric */ public class FixedHomoQuantizedSpikingNonDirectionalDistributed implements PrototypedFunctionBuilder<QuantizedMultivariateSpikingFunction, Robot<? extends SensingVoxel>> { private final int signals; private final QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter; private final QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter; public FixedHomoQuantizedSpikingNonDirectionalDistributed(int signals, QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter, QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter) { this.signals = signals; this.valueToSpikeTrainConverter = valueToSpikeTrainConverter; this.spikeTrainToValueConverter = spikeTrainToValueConverter; } @Override public Function<QuantizedMultivariateSpikingFunction, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) { int[] dim = getIODim(robot); Grid<? extends SensingVoxel> body = robot.getVoxels(); int nOfInputs = dim[0]; int nOfOutputs = dim[1]; return function -> { if (function.getInputDimension() != nOfInputs) { throw new IllegalArgumentException(String.format( "Wrong number of function input args: %d expected, %d found", nOfInputs, function.getInputDimension() )); } if (function.getOutputDimension() != nOfOutputs) { throw new IllegalArgumentException(String.format( "Wrong number of function output args: %d expected, %d found", nOfOutputs, function.getOutputDimension() )); } QuantizedDistributedSpikingSensing controller = new QuantizedDistributedSpikingSensing(body, signals, new QuantizedLIFNeuron(), valueToSpikeTrainConverter, spikeTrainToValueConverter); for (Grid.Entry<? extends SensingVoxel> entry : body) { if (entry.getValue() != null) { controller.getFunctions().set(entry.getX(), entry.getY(), SerializationUtils.clone(function)); } } return new Robot<>( controller, SerializationUtils.clone(body) ); }; } @Override public QuantizedMultivariateSpikingFunction exampleFor(Robot<? extends SensingVoxel> robot) { int[] dim = getIODim(robot); return QuantizedMultivariateSpikingFunction.build(d -> d, dim[0], dim[1]); } private int[] getIODim(Robot<? extends SensingVoxel> robot) { Grid<? extends SensingVoxel> body = robot.getVoxels(); SensingVoxel voxel = body.values().stream().filter(Objects::nonNull).findFirst().orElse(null); if (voxel == null) { throw new IllegalArgumentException("Target robot has no voxels"); } int nOfInputs = DistributedSensingNonDirectional.nOfInputs(voxel, signals); int nOfOutputs = DistributedSensingNonDirectional.nOfOutputs(voxel, signals); List<Grid.Entry<? extends SensingVoxel>> wrongVoxels = body.stream() .filter(e -> e.getValue() != null) .filter(e -> DistributedSensingNonDirectional.nOfInputs(e.getValue(), signals) != nOfInputs) .collect(Collectors.toList()); if (!wrongVoxels.isEmpty()) { throw new IllegalArgumentException(String.format( "Cannot build %s robot mapper for this body: all voxels should have %d inputs, but voxels at positions %s have %s", getClass().getSimpleName(), nOfInputs, wrongVoxels.stream() .map(e -> String.format("(%d,%d)", e.getX(), e.getY())) .collect(Collectors.joining(",")), wrongVoxels.stream() .map(e -> String.format("%d", DistributedSensingNonDirectional.nOfInputs(e.getValue(), signals))) .collect(Collectors.joining(",")) )); } return new int[]{nOfInputs, nOfOutputs}; } }
4,845
46.048544
202
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedHomoQuantizedSpikingDistributed.java
package it.units.erallab.evolution.builder.robot; import it.units.erallab.evolution.builder.PrototypedFunctionBuilder; import it.units.erallab.hmsrobots.core.controllers.DistributedSensing; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedDistributedSpikingSensing; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedLIFNeuron; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedMultivariateSpikingFunction; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedValueToSpikeTrainConverter; import it.units.erallab.hmsrobots.core.objects.Robot; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.SerializationUtils; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; /** * @author eric */ public class FixedHomoQuantizedSpikingDistributed implements PrototypedFunctionBuilder<QuantizedMultivariateSpikingFunction, Robot<? extends SensingVoxel>> { private final int signals; private final QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter; private final QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter; public FixedHomoQuantizedSpikingDistributed(int signals, QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter, QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter) { this.signals = signals; this.valueToSpikeTrainConverter = valueToSpikeTrainConverter; this.spikeTrainToValueConverter = spikeTrainToValueConverter; } @Override public Function<QuantizedMultivariateSpikingFunction, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) { int[] dim = getIODim(robot); Grid<? extends SensingVoxel> body = robot.getVoxels(); int nOfInputs = dim[0]; int nOfOutputs = dim[1]; return function -> { if (function.getInputDimension() != nOfInputs) { throw new IllegalArgumentException(String.format( "Wrong number of function input args: %d expected, %d found", nOfInputs, function.getInputDimension() )); } if (function.getOutputDimension() != nOfOutputs) { throw new IllegalArgumentException(String.format( "Wrong number of function output args: %d expected, %d found", nOfOutputs, function.getOutputDimension() )); } QuantizedDistributedSpikingSensing controller = new QuantizedDistributedSpikingSensing(body, signals, new QuantizedLIFNeuron(), valueToSpikeTrainConverter, spikeTrainToValueConverter); for (Grid.Entry<? extends SensingVoxel> entry : body) { if (entry.getValue() != null) { controller.getFunctions().set(entry.getX(), entry.getY(), SerializationUtils.clone(function)); } } return new Robot<>( controller, SerializationUtils.clone(body) ); }; } @Override public QuantizedMultivariateSpikingFunction exampleFor(Robot<? extends SensingVoxel> robot) { int[] dim = getIODim(robot); return QuantizedMultivariateSpikingFunction.build(d -> d, dim[0], dim[1]); } private int[] getIODim(Robot<? extends SensingVoxel> robot) { Grid<? extends SensingVoxel> body = robot.getVoxels(); SensingVoxel voxel = body.values().stream().filter(Objects::nonNull).findFirst().orElse(null); if (voxel == null) { throw new IllegalArgumentException("Target robot has no voxels"); } int nOfInputs = DistributedSensing.nOfInputs(voxel, signals); int nOfOutputs = DistributedSensing.nOfOutputs(voxel, signals); List<Grid.Entry<? extends SensingVoxel>> wrongVoxels = body.stream() .filter(e -> e.getValue() != null) .filter(e -> DistributedSensing.nOfInputs(e.getValue(), signals) != nOfInputs) .collect(Collectors.toList()); if (!wrongVoxels.isEmpty()) { throw new IllegalArgumentException(String.format( "Cannot build %s robot mapper for this body: all voxels should have %d inputs, but voxels at positions %s have %s", getClass().getSimpleName(), nOfInputs, wrongVoxels.stream() .map(e -> String.format("(%d,%d)", e.getX(), e.getY())) .collect(Collectors.joining(",")), wrongVoxels.stream() .map(e -> String.format("%d", DistributedSensing.nOfInputs(e.getValue(), signals))) .collect(Collectors.joining(",")) )); } return new int[]{nOfInputs, nOfOutputs}; } }
4,747
45.097087
190
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/SensorCentralized.java
package it.units.erallab.evolution.builder.robot; import it.units.erallab.evolution.builder.PrototypedFunctionBuilder; import it.units.erallab.hmsrobots.core.controllers.CentralizedSensing; import it.units.erallab.hmsrobots.core.controllers.RealFunction; import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction; import it.units.erallab.hmsrobots.core.objects.Robot; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.core.sensors.Sensor; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.SerializationUtils; import java.util.List; import java.util.Objects; import java.util.function.Function; /** * @author eric on 2021/01/02 for VSREvolution */ public class SensorCentralized implements PrototypedFunctionBuilder<List<TimedRealFunction>, Robot<? extends SensingVoxel>> { @Override public Function<List<TimedRealFunction>, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) { List<Sensor> prototypeSensors = SensorAndBodyAndHomoDistributed.getPrototypeSensors(robot); int nOfVoxels = (int) robot.getVoxels().values().stream().filter(Objects::nonNull).count(); int sensorDim = prototypeSensors.get(0).getDomains().length; return pair -> { if (pair.size() != 2) { throw new IllegalArgumentException(String.format( "Wrong number of functions: 2 expected, %d found", pair.size() )); } TimedRealFunction sensorizingFunction = pair.get(0); TimedRealFunction brainFunction = pair.get(1); //check function sizes if (sensorizingFunction.getInputDimension() != 2 || sensorizingFunction.getOutputDimension() != prototypeSensors.size()) { throw new IllegalArgumentException(String.format( "Wrong number of sensorizing function args: 2->%d expected, %d->%d found", prototypeSensors.size(), sensorizingFunction.getInputDimension(), sensorizingFunction.getOutputDimension() )); } if (brainFunction.getInputDimension() != nOfVoxels * sensorDim) { throw new IllegalArgumentException(String.format( "Wrong number of brain function input args: %d expected, %d found", nOfVoxels * sensorDim, brainFunction.getInputDimension() )); } if (brainFunction.getOutputDimension() != nOfVoxels) { throw new IllegalArgumentException(String.format( "Wrong number of brain function output args: %d expected, %d found", nOfVoxels, brainFunction.getOutputDimension() )); } //sensorize body int w = robot.getVoxels().getW(); int h = robot.getVoxels().getH(); Grid<double[]> values = Grid.create( w, h, (x, y) -> sensorizingFunction.apply(0, new double[]{(double) x / ((double) w - 1d), (double) y / ((double) h - 1d)}) ); Grid<? extends SensingVoxel> body = Grid.create( w, h, (x, y) -> { if (robot.getVoxels().get(x, y) == null) { return null; } List<Sensor> availableSensors = robot.getVoxels().get(x, y).getSensors(); return new SensingVoxel(List.of( SerializationUtils.clone(availableSensors.get(SensorAndBodyAndHomoDistributed.indexOfMax(values.get(x, y)))) )); } ); return new Robot<>(new CentralizedSensing(body, brainFunction), body); }; } @Override public List<TimedRealFunction> exampleFor(Robot<? extends SensingVoxel> robot) { List<Sensor> prototypeSensors = SensorAndBodyAndHomoDistributed.getPrototypeSensors(robot); int nOfVoxels = (int) robot.getVoxels().values().stream().filter(Objects::nonNull).count(); int sensorDim = prototypeSensors.get(0).getDomains().length; return List.of( RealFunction.build(d -> d, 2, prototypeSensors.size()), RealFunction.build(d -> d, nOfVoxels * sensorDim, nOfVoxels) ); } }
4,043
42.021277
128
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedCentralized.java
package it.units.erallab.evolution.builder.robot; import it.units.erallab.evolution.builder.PrototypedFunctionBuilder; import it.units.erallab.hmsrobots.core.controllers.CentralizedSensing; import it.units.erallab.hmsrobots.core.controllers.RealFunction; import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction; import it.units.erallab.hmsrobots.core.objects.Robot; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.SerializationUtils; import java.util.function.Function; /** * @author eric */ public class FixedCentralized implements PrototypedFunctionBuilder<TimedRealFunction, Robot<? extends SensingVoxel>> { @Override public Function<TimedRealFunction, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) { Grid<? extends SensingVoxel> body = robot.getVoxels(); return function -> { if (function.getInputDimension() != CentralizedSensing.nOfInputs(body)) { throw new IllegalArgumentException(String.format( "Wrong number of function input args: %d expected, %d found", CentralizedSensing.nOfInputs(body), function.getInputDimension() )); } if (function.getOutputDimension() != CentralizedSensing.nOfOutputs(body)) { throw new IllegalArgumentException(String.format( "Wrong number of function output args: %d expected, %d found", CentralizedSensing.nOfOutputs(body), function.getOutputDimension() )); } return new Robot<>( new CentralizedSensing(body, function), SerializationUtils.clone(body) ); }; } @Override public TimedRealFunction exampleFor(Robot<? extends SensingVoxel> robot) { Grid<? extends SensingVoxel> body = robot.getVoxels(); return RealFunction.build( d -> d, CentralizedSensing.nOfInputs(body), CentralizedSensing.nOfOutputs(body) ); } }
2,021
35.763636
118
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/phenotype/FGraph.java
package it.units.erallab.evolution.builder.phenotype; import it.units.erallab.evolution.builder.PrototypedFunctionBuilder; import it.units.erallab.hmsrobots.core.controllers.RealFunction; import it.units.erallab.hmsrobots.util.SerializableFunction; import it.units.malelab.jgea.representation.graph.Graph; import it.units.malelab.jgea.representation.graph.Node; import it.units.malelab.jgea.representation.graph.numeric.functiongraph.FunctionGraph; import it.units.malelab.jgea.representation.graph.numeric.functiongraph.ShallowSparseFactory; import java.util.Random; import java.util.function.Function; /** * @author eric */ public class FGraph implements PrototypedFunctionBuilder<Graph<Node, Double>, RealFunction> { @Override public Function<Graph<Node, Double>, RealFunction> buildFor(RealFunction function) { return graph -> { FunctionGraph functionGraph = FunctionGraph.builder().apply(graph); return RealFunction.build( (SerializableFunction<double[], double[]>) functionGraph::apply, function.getInputDimension(), function.getOutputDimension() ); }; } @Override public Graph<Node, Double> exampleFor(RealFunction function) { return new ShallowSparseFactory(0d, 0d, 1d, function.getInputDimension(), function.getOutputDimension()).build(new Random(0)); } }
1,344
36.361111
130
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/phenotype/MLP.java
package it.units.erallab.evolution.builder.phenotype; import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;import it.units.erallab.hmsrobots.core.controllers.MultiLayerPerceptron; import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction; import java.util.Collections; import java.util.List; import java.util.function.Function; /** * @author eric */ public class MLP implements PrototypedFunctionBuilder<List<Double>, TimedRealFunction> { private final double innerLayerRatio; private final int nOfInnerLayers; private final MultiLayerPerceptron.ActivationFunction activationFunction; public MLP(double innerLayerRatio, int nOfInnerLayers) { this(innerLayerRatio, nOfInnerLayers, MultiLayerPerceptron.ActivationFunction.TANH); } public MLP(double innerLayerRatio, int nOfInnerLayers, MultiLayerPerceptron.ActivationFunction activationFunction) { this.innerLayerRatio = innerLayerRatio; this.nOfInnerLayers = nOfInnerLayers; this.activationFunction = activationFunction; } private int[] innerNeurons(int nOfInputs, int nOfOutputs) { int[] innerNeurons = new int[nOfInnerLayers]; int centerSize = (int) Math.max(2, Math.round(nOfInputs * innerLayerRatio)); if (nOfInnerLayers > 1) { for (int i = 0; i < nOfInnerLayers / 2; i++) { innerNeurons[i] = nOfInputs + (centerSize - nOfInputs) / (nOfInnerLayers / 2 + 1) * (i + 1); } for (int i = nOfInnerLayers / 2; i < nOfInnerLayers; i++) { innerNeurons[i] = centerSize + (nOfOutputs - centerSize) / (nOfInnerLayers / 2 + 1) * (i - nOfInnerLayers / 2); } } else if (nOfInnerLayers > 0) { innerNeurons[0] = centerSize; } return innerNeurons; } @Override public Function<List<Double>, TimedRealFunction> buildFor(TimedRealFunction function) { return values -> { int nOfInputs = function.getInputDimension(); int nOfOutputs = function.getOutputDimension(); int[] innerNeurons = innerNeurons(nOfInputs, nOfOutputs); int nOfWeights = MultiLayerPerceptron.countWeights(nOfInputs, innerNeurons, nOfOutputs); if (nOfWeights != values.size()) { throw new IllegalArgumentException(String.format( "Wrong number of values for weights: %d expected, %d found", nOfWeights, values.size() )); } return new MultiLayerPerceptron( activationFunction, nOfInputs, innerNeurons, nOfOutputs, values.stream().mapToDouble(d -> d).toArray() ); }; } @Override public List<Double> exampleFor(TimedRealFunction function) { return Collections.nCopies( MultiLayerPerceptron.countWeights( MultiLayerPerceptron.countNeurons( function.getInputDimension(), innerNeurons(function.getInputDimension(), function.getOutputDimension()), function.getOutputDimension()) ), 0d ); } }
2,987
35
140
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/phenotype/PruningMLP.java
package it.units.erallab.evolution.builder.phenotype; import it.units.erallab.evolution.builder.PrototypedFunctionBuilder; import it.units.erallab.hmsrobots.core.controllers.MultiLayerPerceptron; import it.units.erallab.hmsrobots.core.controllers.PruningMultiLayerPerceptron; import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction; import java.util.Collections; import java.util.List; import java.util.function.Function; /** * @author eric */ public class PruningMLP implements PrototypedFunctionBuilder<List<Double>, TimedRealFunction> { private final double innerLayerRatio; private final int nOfInnerLayers; private final MultiLayerPerceptron.ActivationFunction activationFunction; private final double pruningTime; private final double rate; private final PruningMultiLayerPerceptron.Context context; private final PruningMultiLayerPerceptron.Criterion criterion; public PruningMLP(double innerLayerRatio, int nOfInnerLayers, MultiLayerPerceptron.ActivationFunction activationFunction, double pruningTime, double rate, PruningMultiLayerPerceptron.Context context, PruningMultiLayerPerceptron.Criterion criterion) { this.innerLayerRatio = innerLayerRatio; this.nOfInnerLayers = nOfInnerLayers; this.activationFunction = activationFunction; this.pruningTime = pruningTime; this.rate = rate; this.context = context; this.criterion = criterion; } private int[] innerNeurons(int nOfInputs, int nOfOutputs) { int[] innerNeurons = new int[nOfInnerLayers]; int centerSize = (int) Math.max(2, Math.round(nOfInputs * innerLayerRatio)); if (nOfInnerLayers > 1) { for (int i = 0; i < nOfInnerLayers / 2; i++) { innerNeurons[i] = nOfInputs + (centerSize - nOfInputs) / (nOfInnerLayers / 2 + 1) * (i + 1); } for (int i = nOfInnerLayers / 2; i < nOfInnerLayers; i++) { innerNeurons[i] = centerSize + (nOfOutputs - centerSize) / (nOfInnerLayers / 2 + 1) * (i - nOfInnerLayers / 2); } } else if (nOfInnerLayers > 0) { innerNeurons[0] = centerSize; } return innerNeurons; } @Override public Function<List<Double>, TimedRealFunction> buildFor(TimedRealFunction function) { return values -> { int nOfInputs = function.getInputDimension(); int nOfOutputs = function.getOutputDimension(); int[] innerNeurons = innerNeurons(nOfInputs, nOfOutputs); int nOfWeights = MultiLayerPerceptron.countWeights(nOfInputs, innerNeurons, nOfOutputs); if (nOfWeights != values.size()) { throw new IllegalArgumentException(String.format( "Wrong number of values for weights: %d expected, %d found", nOfWeights, values.size() )); } return new PruningMultiLayerPerceptron( activationFunction, nOfInputs, innerNeurons, nOfOutputs, values.stream().mapToDouble(d -> d).toArray(), pruningTime, context, criterion, rate ); }; } @Override public List<Double> exampleFor(TimedRealFunction function) { return Collections.nCopies( MultiLayerPerceptron.countWeights( MultiLayerPerceptron.countNeurons( function.getInputDimension(), innerNeurons(function.getInputDimension(), function.getOutputDimension()), function.getOutputDimension()) ), 0d ); } }
3,451
36.11828
252
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/phenotype/QuantizedMSN.java
package it.units.erallab.evolution.builder.phenotype; import it.units.erallab.evolution.builder.PrototypedFunctionBuilder; import it.units.erallab.hmsrobots.core.controllers.MultiLayerPerceptron; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedMultilayerSpikingNetwork; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedMultivariateSpikingFunction; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedSpikingFunction; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; /** * @author eric */ public class QuantizedMSN implements PrototypedFunctionBuilder<List<Double>, QuantizedMultivariateSpikingFunction> { private final double innerLayerRatio; private final int nOfInnerLayers; private final BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder; public QuantizedMSN(double innerLayerRatio, int nOfInnerLayers, BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder) { this.innerLayerRatio = innerLayerRatio; this.nOfInnerLayers = nOfInnerLayers; this.neuronBuilder = neuronBuilder; } private int[] innerNeurons(int nOfInputs, int nOfOutputs) { int[] innerNeurons = new int[nOfInnerLayers]; int centerSize = (int) Math.max(2, Math.round(nOfInputs * innerLayerRatio)); if (nOfInnerLayers > 1) { for (int i = 0; i < nOfInnerLayers / 2; i++) { innerNeurons[i] = nOfInputs + (centerSize - nOfInputs) / (nOfInnerLayers / 2 + 1) * (i + 1); } for (int i = nOfInnerLayers / 2; i < nOfInnerLayers; i++) { innerNeurons[i] = centerSize + (nOfOutputs - centerSize) / (nOfInnerLayers / 2 + 1) * (i - nOfInnerLayers / 2); } } else if (nOfInnerLayers > 0) { innerNeurons[0] = centerSize; } return innerNeurons; } @Override public Function<List<Double>, QuantizedMultivariateSpikingFunction> buildFor(QuantizedMultivariateSpikingFunction function) { return values -> { int nOfInputs = function.getInputDimension(); int nOfOutputs = function.getOutputDimension(); int[] innerNeurons = innerNeurons(nOfInputs, nOfOutputs); int nOfWeights = QuantizedMultilayerSpikingNetwork.countWeights(nOfInputs, innerNeurons, nOfOutputs); if (nOfWeights != values.size()) { throw new IllegalArgumentException(String.format( "Wrong number of values for weights: %d expected, %d found", nOfWeights, values.size() )); } return new QuantizedMultilayerSpikingNetwork( nOfInputs, innerNeurons, nOfOutputs, values.stream().mapToDouble(d -> d).toArray(), neuronBuilder ); }; } @Override public List<Double> exampleFor(QuantizedMultivariateSpikingFunction function) { return Collections.nCopies( QuantizedMultilayerSpikingNetwork.countWeights( MultiLayerPerceptron.countNeurons( function.getInputDimension(), innerNeurons(function.getInputDimension(), function.getOutputDimension()), function.getOutputDimension()) ), 0d ); } }
3,221
37.357143
137
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/phenotype/QuantizedMSNWithConverters.java
package it.units.erallab.evolution.builder.phenotype; import it.units.erallab.evolution.builder.PrototypedFunctionBuilder; import it.units.erallab.hmsrobots.core.controllers.MultiLayerPerceptron; import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedMultilayerSpikingNetwork; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedMultilayerSpikingNetworkWithConverters; import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedSpikingFunction; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedValueToSpikeTrainConverter; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; /** * @author eric */ public class QuantizedMSNWithConverters implements PrototypedFunctionBuilder<List<Double>, TimedRealFunction> { private final double innerLayerRatio; private final int nOfInnerLayers; private final BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder; private final QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter; private final QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter; public QuantizedMSNWithConverters(double innerLayerRatio, int nOfInnerLayers, BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder, QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter, QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter) { this.innerLayerRatio = innerLayerRatio; this.nOfInnerLayers = nOfInnerLayers; this.neuronBuilder = neuronBuilder; this.valueToSpikeTrainConverter = valueToSpikeTrainConverter; this.spikeTrainToValueConverter = spikeTrainToValueConverter; } private int[] innerNeurons(int nOfInputs, int nOfOutputs) { int[] innerNeurons = new int[nOfInnerLayers]; int centerSize = (int) Math.max(2, Math.round(nOfInputs * innerLayerRatio)); if (nOfInnerLayers > 1) { for (int i = 0; i < nOfInnerLayers / 2; i++) { innerNeurons[i] = nOfInputs + (centerSize - nOfInputs) / (nOfInnerLayers / 2 + 1) * (i + 1); } for (int i = nOfInnerLayers / 2; i < nOfInnerLayers; i++) { innerNeurons[i] = centerSize + (nOfOutputs - centerSize) / (nOfInnerLayers / 2 + 1) * (i - nOfInnerLayers / 2); } } else if (nOfInnerLayers > 0) { innerNeurons[0] = centerSize; } return innerNeurons; } @Override public Function<List<Double>, TimedRealFunction> buildFor(TimedRealFunction function) { return values -> { int nOfInputs = function.getInputDimension(); int nOfOutputs = function.getOutputDimension(); int[] innerNeurons = innerNeurons(nOfInputs, nOfOutputs); int nOfWeights = QuantizedMultilayerSpikingNetwork.countWeights(nOfInputs, innerNeurons, nOfOutputs); if (nOfWeights != values.size()) { throw new IllegalArgumentException(String.format( "Wrong number of values for weights: %d expected, %d found", nOfWeights, values.size() )); } QuantizedMultilayerSpikingNetwork quantizedMultilayerSpikingNetwork = new QuantizedMultilayerSpikingNetwork(nOfInputs, innerNeurons, nOfOutputs, values.stream().mapToDouble(d -> d).toArray(), neuronBuilder, spikeTrainToValueConverter ); return new QuantizedMultilayerSpikingNetworkWithConverters<>( quantizedMultilayerSpikingNetwork, valueToSpikeTrainConverter, spikeTrainToValueConverter ); }; } @Override public List<Double> exampleFor(TimedRealFunction function) { return Collections.nCopies( QuantizedMultilayerSpikingNetwork.countWeights( MultiLayerPerceptron.countNeurons( function.getInputDimension(), innerNeurons(function.getInputDimension(), function.getOutputDimension()), function.getOutputDimension()) ), 0d ); } }
4,184
43.052632
279
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/utils/Utils.java
/* * Copyright 2020 Eric Medvet <eric.medvet@gmail.com> (as eric) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it.units.erallab.evolution.utils; import it.units.erallab.evolution.LocomotionEvolution; import it.units.erallab.hmsrobots.behavior.BehaviorUtils; import it.units.erallab.hmsrobots.core.objects.Robot; import it.units.erallab.hmsrobots.core.snapshots.VoxelPoly; import it.units.erallab.hmsrobots.tasks.locomotion.Locomotion; import it.units.erallab.hmsrobots.tasks.locomotion.Outcome; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.RobotUtils; import it.units.erallab.hmsrobots.util.SerializationUtils; import it.units.erallab.hmsrobots.viewers.GridFileWriter; import it.units.erallab.hmsrobots.viewers.VideoUtils; import it.units.erallab.hmsrobots.viewers.drawers.Drawer; import it.units.malelab.jgea.core.Individual; import it.units.malelab.jgea.core.evolver.Event; import it.units.malelab.jgea.core.listener.Accumulator; import it.units.malelab.jgea.core.listener.NamedFunction; import it.units.malelab.jgea.core.listener.NamedFunctions; import it.units.malelab.jgea.core.listener.TableBuilder; import it.units.malelab.jgea.core.util.*; import org.dyn4j.dynamics.Settings; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.*; import java.util.function.Function; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.IntStream; import static it.units.malelab.jgea.core.listener.NamedFunctions.*; /** * @author eric */ public class Utils { private static final Logger L = Logger.getLogger(Utils.class.getName()); private Utils() { } public static List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> keysFunctions() { return List.of( eventAttribute("experiment.name"), eventAttribute("seed", "%2d"), eventAttribute("terrain"), eventAttribute("shape"), eventAttribute("sensor.config"), eventAttribute("mapper"), eventAttribute("transformation"), eventAttribute("evolver"), eventAttribute("fitness.metrics") ); } public static List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> basicFunctions() { NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?> elapsedSeconds = elapsedSeconds(); return List.of( iterations(), births(), fitnessEvaluations(), elapsedSeconds.reformat("%6.0f") ); } public static List<NamedFunction<Individual<?, ? extends Robot<?>, ? extends Outcome>, ?>> serializationFunction(boolean flag, NamedFunction<Individual<?, ?, ?>, ?> function) { if (!flag) { return List.of(); } return List.of(f("serialized", r -> SerializationUtils.serialize(r, SerializationUtils.Mode.GZIPPED_JSON)).of(function)); } public static List<NamedFunction<Individual<?, ? extends Robot<?>, ? extends Outcome>, ?>> individualFunctions(Function<Outcome, Double> fitnessFunction) { NamedFunction<Individual<?, ? extends Robot<?>, ? extends Outcome>, ?> size = size().of(genotype()); return List.of( f("w", "%2d", (Function<Grid<?>, Number>) Grid::getW) .of(f("shape", (Function<Robot<?>, Grid<?>>) Robot::getVoxels)) .of(solution()), f("h", "%2d", (Function<Grid<?>, Number>) Grid::getH) .of(f("shape", (Function<Robot<?>, Grid<?>>) Robot::getVoxels)) .of(solution()), f("num.voxel", "%2d", (Function<Grid<?>, Number>) g -> g.count(Objects::nonNull)) .of(f("shape", (Function<Robot<?>, Grid<?>>) Robot::getVoxels)) .of(solution()), size.reformat("%5d"), genotypeBirthIteration(), f("fitness", "%5.1f", fitnessFunction).of(fitness()), f("abs.weights.sum", "%5.1f", Outcome::getInitialSumOfAbsoluteWeights).of(fitness()), f("avg.abs.weights.sum", "%5.1f", Outcome::getAverageSumOfAbsoluteWeights).of(fitness()) ); } public static List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> populationFunctions(Function<Outcome, Double> fitnessFunction) { NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?> min = min(Double::compare).of(each(f("fitness", fitnessFunction).of(fitness()))).of(all()); NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?> median = median(Double::compare).of(each(f("fitness", fitnessFunction).of(fitness()))).of(all()); return List.of( size().of(all()), size().of(firsts()), size().of(lasts()), uniqueness().of(each(genotype())).of(all()), uniqueness().of(each(solution())).of(all()), uniqueness().of(each(fitness())).of(all()), min.reformat("%+4.1f"), median.reformat("%5.1f") ); } public static List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> computationTimeFunctions() { Function<Outcome, Double> computationTimeFunction = Outcome::getComputationTime; NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?> min = min(Double::compare).of(each(f("computation.time", computationTimeFunction).of(fitness()))).of(all()); NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?> max = max(Double::compare).of(each(f("computation.time", computationTimeFunction).of(fitness()))).of(all()); return List.of( min.reformat("%4.1f"), max.reformat("%5.1f") ); } public static List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> visualFunctions(Function<Outcome, Double> fitnessFunction) { return List.of( hist(8) .of(each(f("fitness", fitnessFunction).of(fitness()))) .of(all()), hist(8) .of(each(f("num.voxels", (Function<Grid<?>, Number>) g -> g.count(Objects::nonNull)) .of(f("shape", (Function<Robot<?>, Grid<?>>) Robot::getVoxels)) .of(solution()))) .of(all()), f("minimap", "%4s", (Function<Grid<?>, String>) g -> TextPlotter.binaryMap( g.toArray(Objects::nonNull), (int) Math.min(Math.ceil((float) g.getW() / (float) g.getH() * 2f), 4))) .of(f("shape", (Function<Robot<?>, Grid<?>>) Robot::getVoxels)) .of(solution()).of(best()), f("average.posture.minimap", "%2s", (Function<Outcome, String>) o -> TextPlotter.binaryMap(o.getAveragePosture(8).toArray(b -> b), 2)) .of(fitness()).of(best()) ); } public static List<NamedFunction<Outcome, ?>> basicOutcomeFunctions() { return List.of( f("computation.time", "%4.2f", Outcome::getComputationTime), f("distance", "%5.1f", Outcome::getDistance), f("velocity", "%5.1f", Outcome::getVelocity), f("corrected.efficiency", "%5.2f", Outcome::getCorrectedEfficiency), f("area.ratio.power", "%5.1f", Outcome::getAreaRatioPower), f("control.power", "%5.1f", Outcome::getControlPower) ); } public static List<NamedFunction<Outcome, ?>> detailedOutcomeFunctions(double spectrumMinFreq, double spectrumMaxFreq, int spectrumSize) { return Misc.concat(List.of( NamedFunction.then(cachedF( "center.x.spectrum", (Outcome o) -> new ArrayList<>(o.getCenterXVelocitySpectrum(spectrumMinFreq, spectrumMaxFreq, spectrumSize).values()) ), IntStream.range(0, spectrumSize).mapToObj(NamedFunctions::nth).collect(Collectors.toList()) ), NamedFunction.then(cachedF( "center.y.spectrum", (Outcome o) -> new ArrayList<>(o.getCenterYVelocitySpectrum(spectrumMinFreq, spectrumMaxFreq, spectrumSize).values()) ), IntStream.range(0, spectrumSize).mapToObj(NamedFunctions::nth).collect(Collectors.toList()) ), NamedFunction.then(cachedF( "center.angle.spectrum", (Outcome o) -> new ArrayList<>(o.getCenterAngleSpectrum(spectrumMinFreq, spectrumMaxFreq, spectrumSize).values()) ), IntStream.range(0, spectrumSize).mapToObj(NamedFunctions::nth).collect(Collectors.toList()) ), NamedFunction.then(cachedF( "footprints.spectra", (Outcome o) -> o.getFootprintsSpectra(4, spectrumMinFreq, spectrumMaxFreq, spectrumSize).stream() .map(SortedMap::values) .flatMap(Collection::stream) .collect(Collectors.toList()) ), IntStream.range(0, 4 * spectrumSize).mapToObj(NamedFunctions::nth).collect(Collectors.toList()) ) )); } public static List<NamedFunction<Outcome, ?>> visualOutcomeFunctions(double spectrumMinFreq, double spectrumMaxFreq) { return Misc.concat(List.of( List.of( cachedF("center.x.spectrum", "%4.4s", o -> TextPlotter.barplot( new ArrayList<>(o.getCenterXVelocitySpectrum(spectrumMinFreq, spectrumMaxFreq, 4).values()) )), cachedF("center.y.spectrum", "%4.4s", o -> TextPlotter.barplot( new ArrayList<>(o.getCenterYVelocitySpectrum(spectrumMinFreq, spectrumMaxFreq, 4).values()) )), cachedF("center.angle.spectrum", "%4.4s", o -> TextPlotter.barplot( new ArrayList<>(o.getCenterAngleSpectrum(spectrumMinFreq, spectrumMaxFreq, 4).values()) )) ), NamedFunction.then(cachedF("footprints", o -> o.getFootprintsSpectra(3, spectrumMinFreq, spectrumMaxFreq, 4)), List.of( cachedF("left.spectrum", "%4.4s", l -> TextPlotter.barplot(new ArrayList<>(l.get(0).values()))), cachedF("center.spectrum", "%4.4s", l -> TextPlotter.barplot(new ArrayList<>(l.get(1).values()))), cachedF("right.spectrum", "%4.4s", l -> TextPlotter.barplot(new ArrayList<>(l.get(2).values()))) ) ) )); } public static Accumulator.Factory<Event<?, ? extends Robot<?>, ? extends Outcome>, String> lastEventToString(Function<Outcome, Double> fitnessFunction) { final List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> functions = Misc.concat(List.of( keysFunctions(), basicFunctions(), populationFunctions(fitnessFunction), NamedFunction.then(best(), individualFunctions(fitnessFunction)), NamedFunction.then(as(Outcome.class).of(fitness()).of(best()), basicOutcomeFunctions()) )); return Accumulator.Factory.<Event<?, ? extends Robot<?>, ? extends Outcome>>last().then( e -> functions.stream() .map(f -> f.getName() + ": " + f.applyAndFormat(e)) .collect(Collectors.joining("\n")) ); } public static Accumulator.Factory<Event<?, ? extends Robot<?>, ? extends Outcome>, BufferedImage> fitnessPlot(Function<Outcome, Double> fitnessFunction) { return new TableBuilder<Event<?, ? extends Robot<?>, ? extends Outcome>, Number>(List.of( iterations(), f("fitness", fitnessFunction).of(fitness()).of(best()), min(Double::compare).of(each(f("fitness", fitnessFunction).of(fitness()))).of(all()), median(Double::compare).of(each(f("fitness", fitnessFunction).of(fitness()))).of(all()) )).then(ImagePlotters.xyLines(600, 400)); } public static Accumulator.Factory<Event<?, ? extends Robot<?>, ? extends Outcome>, BufferedImage> centerPositionPlot() { return Accumulator.Factory.<Event<?, ? extends Robot<?>, ? extends Outcome>>last().then( event -> { Outcome o = Misc.first(event.getOrderedPopulation().firsts()).getFitness(); Table<Number> table = new ArrayTable<>(List.of("x", "y", "terrain.y")); o.getObservations().values().forEach(obs -> { VoxelPoly poly = BehaviorUtils.getCentralElement(obs.getVoxelPolies()); table.addRow(List.of( poly.center().x, poly.center().y, obs.getTerrainHeight() )); }); return table; } ) .then(ImagePlotters.xyLines(600, 400)); } public static Accumulator.Factory<Event<?, ? extends Robot<?>, ? extends Outcome>, File> bestVideo(double transientTime, double episodeTime, Settings settings, Pair<Pair<Integer, Integer>, Function<String, Drawer>> drawerSupplier) { int widthMultiplier = drawerSupplier.first().first(); int heightMultiplier = drawerSupplier.first().second(); return Accumulator.Factory.<Event<?, ? extends Robot<?>, ? extends Outcome>>last().then( event -> { Random random = new Random(0); SortedMap<Long, String> terrainSequence = LocomotionEvolution.getSequence((String) event.getAttributes().get("terrain")); SortedMap<Long, String> transformationSequence = LocomotionEvolution.getSequence((String) event.getAttributes().get("transformation")); String terrainName = terrainSequence.get(terrainSequence.lastKey()); String transformationName = transformationSequence.get(transformationSequence.lastKey()); Robot<?> robot = SerializationUtils.clone(Misc.first(event.getOrderedPopulation().firsts()).getSolution()); robot = RobotUtils.buildRobotTransformation(transformationName, random).apply(robot); Locomotion locomotion = new Locomotion( episodeTime, Locomotion.createTerrain(terrainName.replace("-rnd", "-" + random.nextInt(10000))), settings ); File file; try { file = File.createTempFile("robot-video", ".mp4"); GridFileWriter.save(locomotion, robot, widthMultiplier * 300, heightMultiplier * 200, transientTime, 25, VideoUtils.EncoderFacility.JCODEC, file, drawerSupplier.second()); file.deleteOnExit(); } catch (IOException ioException) { L.warning(String.format("Cannot save video of best: %s", ioException)); return null; } return file; } ); } public static Function<Event<?, ? extends Robot<?>, ? extends Outcome>, Collection<LocomotionEvolution.ValidationOutcome>> validation( List<String> validationTerrainNames, List<String> validationTransformationNames, List<Integer> seeds, double episodeTime ) { return event -> { Robot<?> robot = SerializationUtils.clone(Misc.first(event.getOrderedPopulation().firsts()).getSolution()); List<LocomotionEvolution.ValidationOutcome> validationOutcomes = new ArrayList<>(); for (String validationTerrainName : validationTerrainNames) { for (String validationTransformationName : validationTransformationNames) { for (int seed : seeds) { Random random = new Random(seed); robot = SerializationUtils.clone(robot, SerializationUtils.Mode.GZIPPED_JSON); robot = RobotUtils.buildRobotTransformation(validationTransformationName, random).apply(robot); Function<Robot<?>, Outcome> validationLocomotion = LocomotionEvolution.buildLocomotionTask( validationTerrainName, episodeTime, random, false ); Outcome outcome = validationLocomotion.apply(robot); validationOutcomes.add(new LocomotionEvolution.ValidationOutcome( event, Map.ofEntries( Map.entry("validation.terrain", validationTerrainName), Map.entry("validation.transformation", validationTransformationName), Map.entry("validation.seed", seed) ), outcome )); } } } return validationOutcomes; }; } }
16,401
47.961194
234
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/Starter.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots; import it.units.erallab.hmsrobots.core.controllers.DistributedSensing; import it.units.erallab.hmsrobots.core.controllers.MultiLayerPerceptron; import it.units.erallab.hmsrobots.core.objects.Robot; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.tasks.locomotion.Locomotion; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.RobotUtils; import it.units.erallab.hmsrobots.util.SerializationUtils; import it.units.erallab.hmsrobots.viewers.GridOnlineViewer; import it.units.erallab.hmsrobots.viewers.drawers.Drawers; import org.apache.commons.lang3.tuple.Pair; import org.dyn4j.dynamics.Settings; import java.util.Random; import java.util.stream.IntStream; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class Starter { public static void main(String[] args) { randomNonUniformDirectionalMLP(); } private static void randomNonUniformDirectionalMLP() { // body creation Grid<? extends SensingVoxel> bipedBody = RobotUtils.buildSensorizingFunction("uniform-t+a+vxy-0.01").apply(RobotUtils.buildShape("biped-4x3")); Grid<? extends SensingVoxel> wormBody = RobotUtils.buildSensorizingFunction("uniform-t+a+vxy-0.01").apply(RobotUtils.buildShape("worm-5x1")); Grid<? extends SensingVoxel> combBody = RobotUtils.buildSensorizingFunction("uniform-t+a+vxy-0.01").apply(RobotUtils.buildShape("comb-7x2")); // controller creation DistributedSensing bipedDistributedSensing = new DistributedSensing(bipedBody, 1); DistributedSensing wormDistributedSensing = new DistributedSensing(wormBody, 1); DistributedSensing combDistributedSensing = new DistributedSensing(combBody, 1); fillWithRandomMLPs(bipedBody, bipedDistributedSensing); fillWithRandomMLPs(wormBody, wormDistributedSensing); fillWithRandomMLPs(combBody, combDistributedSensing); // robot creation Robot<SensingVoxel> biped = new Robot<>(bipedDistributedSensing, SerializationUtils.clone(bipedBody)); Robot<SensingVoxel> worm = new Robot<>(wormDistributedSensing, SerializationUtils.clone(wormBody)); Robot<SensingVoxel> comb = new Robot<>(combDistributedSensing, SerializationUtils.clone(combBody)); // locomotion task Locomotion locomotion = new Locomotion( 30, Locomotion.createTerrain("downhill-30"), new Settings() ); Grid<Pair<String, Robot<?>>> namedSolutionGrid = Grid.create(3, 1); namedSolutionGrid.set(0, 0, Pair.of("biped", biped)); namedSolutionGrid.set(1, 0, Pair.of("worm", worm)); namedSolutionGrid.set(2, 0, Pair.of("comb", comb)); GridOnlineViewer.run(locomotion, namedSolutionGrid, Drawers::basicWithMiniWorld); } private static void fillWithRandomMLPs(Grid<? extends SensingVoxel> body, DistributedSensing distributedSensing) { Random random = new Random(); for (Grid.Entry<? extends SensingVoxel> entry : body) { MultiLayerPerceptron mlp = new MultiLayerPerceptron( MultiLayerPerceptron.ActivationFunction.TANH, distributedSensing.nOfInputs(entry.getX(), entry.getY()), new int[]{2}, distributedSensing.nOfOutputs(entry.getX(), entry.getY()) ); double[] ws = mlp.getParams(); IntStream.range(0, ws.length).forEach(i -> ws[i] = random.nextDouble() * 2d - 1d); mlp.setParams(ws); distributedSensing.getFunctions().set(entry.getX(), entry.getY(), mlp); } } }
4,242
43.663158
147
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/Actionable.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core; public interface Actionable { void act(final double t); void reset(); }
874
34
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/objects/ControllableVoxel.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.sensors.Touch; import it.units.erallab.hmsrobots.core.snapshots.VoxelPoly; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.joint.DistanceJoint; import org.dyn4j.geometry.Vector2; import java.util.EnumSet; public class ControllableVoxel extends Voxel { public enum ForceMethod { DISTANCE, FORCE } public static final double MAX_FORCE = 100d; public static final ForceMethod FORCE_METHOD = ForceMethod.DISTANCE; @JsonProperty private final double maxForce; //not used in distance forceMethod @JsonProperty private final ForceMethod forceMethod; private transient double controlEnergy; private transient double lastAppliedForce; @JsonCreator public ControllableVoxel( @JsonProperty("sideLength") double sideLength, @JsonProperty("massSideLengthRatio") double massSideLengthRatio, @JsonProperty("springF") double springF, @JsonProperty("springD") double springD, @JsonProperty("massLinearDamping") double massLinearDamping, @JsonProperty("massAngularDamping") double massAngularDamping, @JsonProperty("friction") double friction, @JsonProperty("restitution") double restitution, @JsonProperty("mass") double mass, @JsonProperty("limitContractionFlag") boolean limitContractionFlag, @JsonProperty("massCollisionFlag") boolean massCollisionFlag, @JsonProperty("areaRatioMaxDelta") double areaRatioMaxDelta, @JsonProperty("springScaffoldings") EnumSet<SpringScaffolding> springScaffoldings, @JsonProperty("maxForce") double maxForce, @JsonProperty("forceMethod") ForceMethod forceMethod ) { super(sideLength, massSideLengthRatio, springF, springD, massLinearDamping, massAngularDamping, friction, restitution, mass, limitContractionFlag, massCollisionFlag, areaRatioMaxDelta, springScaffoldings); this.maxForce = maxForce; this.forceMethod = forceMethod; } public ControllableVoxel(double maxForce, ForceMethod forceMethod) { this.maxForce = maxForce; this.forceMethod = forceMethod; } public ControllableVoxel() { this(MAX_FORCE, FORCE_METHOD); } public void applyForce(double f) { if (Math.abs(f) > 1d) { f = Math.signum(f); } lastAppliedForce = f; if (forceMethod.equals(ForceMethod.FORCE)) { double xc = 0d; double yc = 0d; for (Body body : vertexBodies) { xc = xc + body.getWorldCenter().x; yc = yc + body.getWorldCenter().y; } xc = xc / (double) vertexBodies.length; yc = yc / (double) vertexBodies.length; for (Body body : vertexBodies) { Vector2 force = (new Vector2(xc, yc)).subtract(body.getWorldCenter()).getNormalized().multiply(f * maxForce); body.applyForce(force); } } else if (forceMethod.equals(ForceMethod.DISTANCE)) { for (DistanceJoint joint : springJoints) { SpringRange range = (SpringRange) joint.getUserData(); if (f >= 0) { // shrink joint.setDistance(range.rest - (range.rest - range.min) * f); } else if (f < 0) { // expand joint.setDistance(range.rest + (range.max - range.rest) * -f); } } } } public double getLastAppliedForce() { return lastAppliedForce; } public double getControlEnergy() { return controlEnergy; } @Override public VoxelPoly getVoxelPoly() { return new VoxelPoly( getVertices(), getAngle(), getLinearVelocity(), Touch.isTouchingGround(this), getAreaRatio(), getAreaRatioEnergy(), getLastAppliedForce(), getControlEnergy() ); } @Override public void reset() { super.reset(); applyForce(0d); controlEnergy = 0d; lastAppliedForce = 0d; } @Override public void act(double t) { super.act(t); //compute energy controlEnergy = controlEnergy + lastAppliedForce * lastAppliedForce; } @Override public String toString() { return "ControllableVoxel{" + "maxForce=" + maxForce + ", forceMethod=" + forceMethod + ", controlEnergy=" + controlEnergy + '}'; } }
5,071
31.935065
209
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/objects/Ground.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.objects; import it.units.erallab.hmsrobots.core.geometry.Point2; import it.units.erallab.hmsrobots.core.geometry.Poly; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.core.snapshots.Snapshottable; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.World; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Polygon; import org.dyn4j.geometry.Vector2; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class Ground implements WorldObject, Snapshottable { private static final double MIN_Y_THICKNESS = 50d; private final double[] xs; private final double[] ys; private final List<Body> bodies; private final List<Vector2> polygon; public Ground(double[] xs, double[] ys) { this.xs = xs; this.ys = ys; if (xs.length != ys.length) { throw new IllegalArgumentException("xs[] and ys[] must have the same length"); } if (xs.length < 2) { throw new IllegalArgumentException("There must be at least 2 points"); } double[] sortedXs = Arrays.copyOf(xs, xs.length); Arrays.sort(sortedXs); if (!Arrays.equals(xs, sortedXs)) { throw new IllegalArgumentException("x coordinates must be sorted"); } //init collections bodies = new ArrayList<>(xs.length - 1); polygon = new ArrayList<>(xs.length + 2); //find min y double baseY = Arrays.stream(ys).min().getAsDouble() - MIN_Y_THICKNESS; polygon.add(new Vector2(0, baseY)); //build bodies and polygon for (int i = 1; i < xs.length; i++) { Polygon bodyPoly = new Polygon( new Vector2(0, ys[i - 1]), new Vector2(0, baseY), new Vector2(xs[i] - xs[i - 1], baseY), new Vector2(xs[i] - xs[i - 1], ys[i]) ); Body body = new Body(1); body.addFixture(bodyPoly); body.setMass(MassType.INFINITE); body.translate(xs[i - 1], 0); body.setUserData(Ground.class); //body.translate(-xs[0], -minY); bodies.add(body); polygon.add(new Vector2(xs[i - 1], ys[i - 1])); } polygon.add(new Vector2(xs[xs.length - 1], ys[xs.length - 1])); polygon.add(new Vector2(xs[xs.length - 1], baseY)); } @Override public Snapshot getSnapshot() { Point2[] vertices = new Point2[polygon.size()]; for (int i = 0; i < vertices.length; i++) { vertices[i] = Point2.of(polygon.get(i)); } return new Snapshot(Poly.of(vertices), getClass()); } @Override public void addTo(World world) { for (Body body : bodies) { world.addBody(body); } } public List<Body> getBodies() { return bodies; } public double yAt(double x) { double y = Double.NEGATIVE_INFINITY; for (int i = 1; i < xs.length; i++) { if ((xs[i - 1] <= x) && (x <= xs[i])) { return (x - xs[i - 1]) * (ys[i] - ys[i - 1]) / (xs[i] - xs[i - 1]) + ys[i - 1]; } } return Double.NaN; } }
3,793
31.42735
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/objects/Voxel.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import it.units.erallab.hmsrobots.core.Actionable; import it.units.erallab.hmsrobots.core.geometry.BoundingBox; import it.units.erallab.hmsrobots.core.geometry.Point2; import it.units.erallab.hmsrobots.core.geometry.Poly; import it.units.erallab.hmsrobots.core.geometry.Vector; import it.units.erallab.hmsrobots.core.sensors.Touch; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.core.snapshots.Snapshottable; import it.units.erallab.hmsrobots.core.snapshots.VoxelPoly; import org.dyn4j.collision.Filter; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.World; import org.dyn4j.dynamics.joint.DistanceJoint; import org.dyn4j.dynamics.joint.Joint; import org.dyn4j.dynamics.joint.RopeJoint; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Rectangle; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Vector2; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; /** * @author Eric Medvet <eric.medvet@gmail.com> */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class") public class Voxel implements Actionable, Serializable, Snapshottable, WorldObject { public enum SpringScaffolding { SIDE_EXTERNAL, SIDE_INTERNAL, SIDE_CROSS, CENTRAL_CROSS } protected static class SpringRange { public final double min; public final double rest; public final double max; public SpringRange(double min, double rest, double max) { if ((min > rest) || (max < rest) || (min < 0)) { throw new IllegalArgumentException(String.format("Wrong spring range [%f, %f, %f]", min, rest, max)); } this.min = min; this.rest = rest; this.max = max; } @Override public int hashCode() { int hash = 5; hash = 53 * hash + (int) (Double.doubleToLongBits(this.min) ^ (Double.doubleToLongBits(this.min) >>> 32)); hash = 53 * hash + (int) (Double.doubleToLongBits(this.rest) ^ (Double.doubleToLongBits(this.rest) >>> 32)); hash = 53 * hash + (int) (Double.doubleToLongBits(this.max) ^ (Double.doubleToLongBits(this.max) >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SpringRange other = (SpringRange) obj; if (Double.doubleToLongBits(this.min) != Double.doubleToLongBits(other.min)) { return false; } if (Double.doubleToLongBits(this.rest) != Double.doubleToLongBits(other.rest)) { return false; } return Double.doubleToLongBits(this.max) == Double.doubleToLongBits(other.max); } } public static class ParentFilter implements Filter { private final Object parent; public ParentFilter(Object parent) { this.parent = parent; } @Override public boolean isAllowed(Filter f) { if (!(f instanceof ParentFilter)) { return true; } return parent != ((ParentFilter) f).parent; } } public static class RobotFilter implements Filter { @Override public boolean isAllowed(Filter filter) { return true; } } public static final double SIDE_LENGTH = 3d; public static final double MASS_SIDE_LENGTH_RATIO = .40d; public static final double SPRING_F = 8d; public static final double SPRING_D = 0.3d; public static final double MASS_LINEAR_DAMPING = 0.1d; public static final double MASS_ANGULAR_DAMPING = 0.1d; public static final double FRICTION = 10d; public static final double RESTITUTION = 0.1d; public static final double MASS = 1d; public static final boolean LIMIT_CONTRACTION_FLAG = true; public static final boolean MASS_COLLISION_FLAG = false; public static final double AREA_RATIO_MAX_DELTA = 0.225d; public static final EnumSet<SpringScaffolding> SPRING_SCAFFOLDINGS = EnumSet.allOf(SpringScaffolding.class); @JsonProperty private final double sideLength; @JsonProperty private final double massSideLengthRatio; @JsonProperty protected final double springF; @JsonProperty private final double springD; @JsonProperty private final double massLinearDamping; @JsonProperty private final double massAngularDamping; @JsonProperty private final double friction; @JsonProperty private final double restitution; @JsonProperty private final double mass; @JsonProperty private final boolean limitContractionFlag; @JsonProperty private final boolean massCollisionFlag; @JsonProperty private final double areaRatioMaxDelta; @JsonProperty private final EnumSet<SpringScaffolding> springScaffoldings; protected transient Body[] vertexBodies; protected transient DistanceJoint[] springJoints; protected transient RopeJoint[] ropeJoints; private transient World world; private transient double areaRatioEnergy; @JsonCreator public Voxel( @JsonProperty("sideLength") double sideLength, @JsonProperty("massSideLengthRatio") double massSideLengthRatio, @JsonProperty("springF") double springF, @JsonProperty("springD") double springD, @JsonProperty("massLinearDamping") double massLinearDamping, @JsonProperty("massAngularDamping") double massAngularDamping, @JsonProperty("friction") double friction, @JsonProperty("restitution") double restitution, @JsonProperty("mass") double mass, @JsonProperty("limitContractionFlag") boolean limitContractionFlag, @JsonProperty("massCollisionFlag") boolean massCollisionFlag, @JsonProperty("areaRatioMaxDelta") double areaRatioMaxDelta, @JsonProperty("springScaffoldings") EnumSet<SpringScaffolding> springScaffoldings ) { this.sideLength = sideLength; this.massSideLengthRatio = massSideLengthRatio; this.springF = springF; this.springD = springD; this.massLinearDamping = massLinearDamping; this.massAngularDamping = massAngularDamping; this.friction = friction; this.restitution = restitution; this.mass = mass; this.limitContractionFlag = limitContractionFlag; this.massCollisionFlag = massCollisionFlag; this.areaRatioMaxDelta = areaRatioMaxDelta; this.springScaffoldings = springScaffoldings; assemble(); } public Voxel() { this(SIDE_LENGTH, MASS_SIDE_LENGTH_RATIO, SPRING_F, SPRING_D, MASS_LINEAR_DAMPING, MASS_ANGULAR_DAMPING, FRICTION, RESTITUTION, MASS, LIMIT_CONTRACTION_FLAG, MASS_COLLISION_FLAG, AREA_RATIO_MAX_DELTA, SPRING_SCAFFOLDINGS); } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); assemble(); } private void assemble() { //compute densities double massSideLength = sideLength * massSideLengthRatio; double density = mass * massSideLength / massSideLength / 4; //build bodies vertexBodies = new Body[4]; vertexBodies[0] = new Body(1); //NW vertexBodies[1] = new Body(1); //NE vertexBodies[2] = new Body(1); //SE vertexBodies[3] = new Body(1); //SW vertexBodies[0].addFixture(new Rectangle(massSideLength, massSideLength), density, friction, restitution); vertexBodies[1].addFixture(new Rectangle(massSideLength, massSideLength), density, friction, restitution); vertexBodies[2].addFixture(new Rectangle(massSideLength, massSideLength), density, friction, restitution); vertexBodies[3].addFixture(new Rectangle(massSideLength, massSideLength), density, friction, restitution); vertexBodies[0].translate(-(sideLength / 2d - massSideLength / 2d), +(sideLength / 2d - massSideLength / 2d)); vertexBodies[1].translate(+(sideLength / 2d - massSideLength / 2d), +(sideLength / 2d - massSideLength / 2d)); vertexBodies[2].translate(+(sideLength / 2d - massSideLength / 2d), -(sideLength / 2d - massSideLength / 2d)); vertexBodies[3].translate(-(sideLength / 2d - massSideLength / 2d), -(sideLength / 2d - massSideLength / 2d)); for (Body body : vertexBodies) { body.setMass(MassType.NORMAL); body.setLinearDamping(massLinearDamping); body.setAngularDamping(massAngularDamping); } //build rope joints List<RopeJoint> localRopeJoints = new ArrayList<>(); if (limitContractionFlag) { localRopeJoints.add(new RopeJoint(vertexBodies[0], vertexBodies[1], vertexBodies[0].getWorldCenter(), vertexBodies[1].getWorldCenter())); localRopeJoints.add(new RopeJoint(vertexBodies[1], vertexBodies[2], vertexBodies[1].getWorldCenter(), vertexBodies[2].getWorldCenter())); localRopeJoints.add(new RopeJoint(vertexBodies[2], vertexBodies[3], vertexBodies[2].getWorldCenter(), vertexBodies[3].getWorldCenter())); localRopeJoints.add(new RopeJoint(vertexBodies[3], vertexBodies[0], vertexBodies[3].getWorldCenter(), vertexBodies[0].getWorldCenter())); for (RopeJoint ropeJoint : localRopeJoints) { ropeJoint.setLowerLimit(massSideLength); ropeJoint.setLowerLimitEnabled(true); ropeJoint.setUpperLimitEnabled(false); } } ropeJoints = localRopeJoints.toArray(new RopeJoint[0]); //build distance joints List<DistanceJoint> allSpringJoints = new ArrayList<>(); double minSideLength = Math.sqrt(sideLength * sideLength * (1d - areaRatioMaxDelta)); double maxSideLength = Math.sqrt(sideLength * sideLength * (1d + areaRatioMaxDelta)); SpringRange sideParallelRange = new SpringRange(minSideLength - 2d * massSideLength, sideLength - 2d * massSideLength, maxSideLength - 2d * massSideLength); SpringRange sideCrossRange = new SpringRange(Math.sqrt(massSideLength * massSideLength + sideParallelRange.min * sideParallelRange.min), Math.sqrt(massSideLength * massSideLength + sideParallelRange.rest * sideParallelRange.rest), Math.sqrt(massSideLength * massSideLength + sideParallelRange.max * sideParallelRange.max)); SpringRange centralCrossRange = new SpringRange((minSideLength - massSideLength) * Math.sqrt(2d), (sideLength - massSideLength) * Math.sqrt(2d), (maxSideLength - massSideLength) * Math.sqrt(2d)); if (springScaffoldings.contains(SpringScaffolding.SIDE_INTERNAL)) { List<DistanceJoint> localSpringJoints = new ArrayList<>(); localSpringJoints.add(new DistanceJoint(vertexBodies[0], vertexBodies[1], vertexBodies[0].getWorldCenter().copy().add(+massSideLength / 2d, -massSideLength / 2d), vertexBodies[1].getWorldCenter().copy().add(-massSideLength / 2d, -massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[1], vertexBodies[2], vertexBodies[1].getWorldCenter().copy().add(-massSideLength / 2d, -massSideLength / 2d), vertexBodies[2].getWorldCenter().copy().add(-massSideLength / 2d, +massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[2], vertexBodies[3], vertexBodies[2].getWorldCenter().copy().add(-massSideLength / 2d, +massSideLength / 2d), vertexBodies[3].getWorldCenter().copy().add(+massSideLength / 2d, +massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[3], vertexBodies[0], vertexBodies[3].getWorldCenter().copy().add(+massSideLength / 2d, +massSideLength / 2d), vertexBodies[0].getWorldCenter().copy().add(+massSideLength / 2d, -massSideLength / 2d) )); for (DistanceJoint joint : localSpringJoints) { joint.setUserData(sideParallelRange); } allSpringJoints.addAll(localSpringJoints); } if (springScaffoldings.contains(SpringScaffolding.SIDE_EXTERNAL)) { List<DistanceJoint> localSpringJoints = new ArrayList<>(); localSpringJoints.add(new DistanceJoint(vertexBodies[0], vertexBodies[1], vertexBodies[0].getWorldCenter().copy().add(+massSideLength / 2d, +massSideLength / 2d), vertexBodies[1].getWorldCenter().copy().add(-massSideLength / 2d, +massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[1], vertexBodies[2], vertexBodies[1].getWorldCenter().copy().add(+massSideLength / 2d, -massSideLength / 2d), vertexBodies[2].getWorldCenter().copy().add(+massSideLength / 2d, +massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[2], vertexBodies[3], vertexBodies[2].getWorldCenter().copy().add(-massSideLength / 2d, -massSideLength / 2d), vertexBodies[3].getWorldCenter().copy().add(+massSideLength / 2d, -massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[3], vertexBodies[0], vertexBodies[3].getWorldCenter().copy().add(-massSideLength / 2d, +massSideLength / 2d), vertexBodies[0].getWorldCenter().copy().add(-massSideLength / 2d, -massSideLength / 2d) )); for (DistanceJoint joint : localSpringJoints) { joint.setUserData(sideParallelRange); } allSpringJoints.addAll(localSpringJoints); } if (springScaffoldings.contains(SpringScaffolding.SIDE_CROSS)) { List<DistanceJoint> localSpringJoints = new ArrayList<>(); localSpringJoints.add(new DistanceJoint(vertexBodies[0], vertexBodies[1], vertexBodies[0].getWorldCenter().copy().add(+massSideLength / 2d, +massSideLength / 2d), vertexBodies[1].getWorldCenter().copy().add(-massSideLength / 2d, -massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[0], vertexBodies[1], vertexBodies[0].getWorldCenter().copy().add(+massSideLength / 2d, -massSideLength / 2d), vertexBodies[1].getWorldCenter().copy().add(-massSideLength / 2d, +massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[1], vertexBodies[2], vertexBodies[1].getWorldCenter().copy().add(+massSideLength / 2d, -massSideLength / 2d), vertexBodies[2].getWorldCenter().copy().add(-massSideLength / 2d, +massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[1], vertexBodies[2], vertexBodies[1].getWorldCenter().copy().add(-massSideLength / 2d, -massSideLength / 2d), vertexBodies[2].getWorldCenter().copy().add(+massSideLength / 2d, +massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[2], vertexBodies[3], vertexBodies[2].getWorldCenter().copy().add(-massSideLength / 2d, +massSideLength / 2d), vertexBodies[3].getWorldCenter().copy().add(+massSideLength / 2d, -massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[2], vertexBodies[3], vertexBodies[2].getWorldCenter().copy().add(-massSideLength / 2d, -massSideLength / 2d), vertexBodies[3].getWorldCenter().copy().add(+massSideLength / 2d, +massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[3], vertexBodies[0], vertexBodies[3].getWorldCenter().copy().add(-massSideLength / 2d, +massSideLength / 2d), vertexBodies[0].getWorldCenter().copy().add(+massSideLength / 2d, -massSideLength / 2d) )); localSpringJoints.add(new DistanceJoint(vertexBodies[3], vertexBodies[0], vertexBodies[3].getWorldCenter().copy().add(+massSideLength / 2d, +massSideLength / 2d), vertexBodies[0].getWorldCenter().copy().add(-massSideLength / 2d, -massSideLength / 2d) )); for (DistanceJoint joint : localSpringJoints) { joint.setUserData(sideCrossRange); } allSpringJoints.addAll(localSpringJoints); } if (springScaffoldings.contains(SpringScaffolding.CENTRAL_CROSS)) { List<DistanceJoint> localSpringJoints = new ArrayList<>(); localSpringJoints.add(new DistanceJoint(vertexBodies[0], vertexBodies[2], vertexBodies[0].getWorldCenter(), vertexBodies[2].getWorldCenter() )); localSpringJoints.add(new DistanceJoint(vertexBodies[1], vertexBodies[3], vertexBodies[1].getWorldCenter(), vertexBodies[3].getWorldCenter() )); for (DistanceJoint joint : localSpringJoints) { joint.setUserData(centralCrossRange); } allSpringJoints.addAll(localSpringJoints); } //setup spring joints for (DistanceJoint joint : allSpringJoints) { joint.setDistance(((SpringRange) joint.getUserData()).rest); joint.setFrequency(springF); joint.setDampingRatio(springD); } springJoints = allSpringJoints.toArray(new DistanceJoint[0]); } public void setOwner(Robot<?> robot) { Filter filter; if (massCollisionFlag) { filter = new ParentFilter(robot); } else { filter = new RobotFilter(); } for (Body vertexBody : vertexBodies) { vertexBody.setUserData(robot); vertexBody.getFixture(0).setFilter(filter); } } @Override public Snapshot getSnapshot() { Snapshot snapshot = new Snapshot(getVoxelPoly(), getClass()); fillSnapshot(snapshot); return snapshot; } public VoxelPoly getVoxelPoly() { return new VoxelPoly( getVertices(), getAngle(), getLinearVelocity(), Touch.isTouchingGround(this), getAreaRatio(), getAreaRatioEnergy() ); } protected List<Point2> getVertices() { return List.of( Point2.of(getIndexedVertex(0, 3)), Point2.of(getIndexedVertex(1, 2)), Point2.of(getIndexedVertex(2, 1)), Point2.of(getIndexedVertex(3, 0)) ); } protected void fillSnapshot(Snapshot snapshot) { //add parts for (Body body : vertexBodies) { snapshot.getChildren().add(new Snapshot( rectangleToPoly(body), getClass() )); } //add joints for (DistanceJoint joint : springJoints) { snapshot.getChildren().add(new Snapshot( Vector.of( Point2.of(joint.getAnchor1()), Point2.of(joint.getAnchor2()) ), getClass() )); } } public BoundingBox boundingBox() { double minX = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; for (int i = 0; i < 4; i++) { Vector2 point = getIndexedVertex(i, 3 - i); minX = Math.min(minX, point.x); maxX = Math.max(maxX, point.x); minY = Math.min(minY, point.y); maxY = Math.max(maxY, point.y); } return BoundingBox.of( Point2.of(minX, minY), Point2.of(maxX, maxY) ); } private Vector2 getIndexedVertex(int i, int j) { Transform t = vertexBodies[i].getTransform(); Rectangle rectangle = (Rectangle) vertexBodies[i].getFixture(0).getShape(); Vector2 tV = rectangle.getVertices()[j].copy(); t.transform(tV); return tV; } private Poly rectangleToPoly(Body body) { Point2[] vertices = new Point2[4]; Transform t = body.getTransform(); Rectangle rectangle = (Rectangle) body.getFixture(0).getShape(); for (int i = 0; i < 4; i++) { Vector2 tV = rectangle.getVertices()[i].copy(); t.transform(tV); vertices[i] = Point2.of(tV); } return Poly.of(vertices); } @Override public void addTo(World world) { if (this.world != null) { for (Body body : vertexBodies) { this.world.removeBody(body); } for (Joint joint : springJoints) { this.world.removeJoint(joint); } for (Joint joint : ropeJoints) { this.world.removeJoint(joint); } } this.world = world; for (Body body : vertexBodies) { world.addBody(body); } for (Joint joint : springJoints) { world.addJoint(joint); } for (Joint joint : ropeJoints) { world.addJoint(joint); } } public Body[] getVertexBodies() { return vertexBodies; } public Point2 getLinearVelocity() { double x = 0d; double y = 0d; for (Body vertex : vertexBodies) { x = x + vertex.getLinearVelocity().x; y = y + vertex.getLinearVelocity().y; } return Point2.of(x / (double) vertexBodies.length, y / (double) vertexBodies.length); } public double getAreaRatio() { Poly poly = Poly.of( Point2.of(getIndexedVertex(0, 3)), Point2.of(getIndexedVertex(1, 2)), Point2.of(getIndexedVertex(2, 1)), Point2.of(getIndexedVertex(3, 0)) ); return poly.area() / sideLength / sideLength; } public Vector2 getCenter() { double xc = 0d; double yc = 0d; for (Body vertex : vertexBodies) { xc = xc + vertex.getWorldCenter().x; yc = yc + vertex.getWorldCenter().y; } return new Vector2(xc / (double) vertexBodies.length, yc / (double) vertexBodies.length); } public double getAngle() { Vector2 upSide = vertexBodies[1].getWorldCenter().copy().subtract(vertexBodies[0].getWorldCenter()); Vector2 downSide = vertexBodies[2].getWorldCenter().copy().subtract(vertexBodies[3].getWorldCenter()); return (upSide.getDirection() + downSide.getDirection()) / 2d; } public void translate(Vector2 v) { for (Body body : vertexBodies) { body.translate(v); } } public double getSideLength() { return sideLength; } public World getWorld() { return world; } @Override public void reset() { assemble(); areaRatioEnergy = 0d; } @Override public void act(double t) { double areaRatio = getAreaRatio(); areaRatioEnergy = areaRatioEnergy + areaRatio * areaRatio; } public double getAreaRatioEnergy() { return areaRatioEnergy; } @Override public String toString() { return "Voxel{" + "sideLength=" + sideLength + ", massSideLengthRatio=" + massSideLengthRatio + ", springF=" + springF + ", springD=" + springD + ", massLinearDamping=" + massLinearDamping + ", massAngularDamping=" + massAngularDamping + ", friction=" + friction + ", restitution=" + restitution + ", mass=" + mass + ", limitContractionFlag=" + limitContractionFlag + ", massCollisionFlag=" + massCollisionFlag + ", areaRatioMaxDelta=" + areaRatioMaxDelta + ", springScaffoldings=" + springScaffoldings + ", areaRatioEnergy=" + areaRatioEnergy + '}'; } }
23,382
38.767007
327
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/objects/Box.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as eric) * * 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/>. */ package it.units.erallab.hmsrobots.core.objects; import it.units.erallab.hmsrobots.core.geometry.Point2; import it.units.erallab.hmsrobots.core.geometry.Poly; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.core.snapshots.Snapshottable; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.World; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Rectangle; import org.dyn4j.geometry.Vector2; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class Box implements WorldObject, Snapshottable { private final static double FRICTION = 1d; private final static double RESTITUTION = 0.5d; private final Body body; public Box(double w, double h, double angle, double mass) { body = new Body(1); body.addFixture(new Rectangle(w, h), mass / w / h, FRICTION, RESTITUTION); body.setMass(MassType.NORMAL); body.rotate(angle); } public void translate(Vector2 v) { body.translate(new Vector2(v.x, v.y)); } @Override public Snapshot getSnapshot() { Rectangle rectangle = (Rectangle) body.getFixture(0).getShape(); return new Snapshot( Poly.of( Point2.of(rectangle.getVertices()[0]), Point2.of(rectangle.getVertices()[1]), Point2.of(rectangle.getVertices()[2]), Point2.of(rectangle.getVertices()[3]) ), getClass() ); } @Override public void addTo(World world) { world.addBody(body); } }
2,218
30.7
78
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/objects/BreakableVoxel.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.sensors.Sensor; import it.units.erallab.hmsrobots.core.sensors.Touch; import it.units.erallab.hmsrobots.core.snapshots.VoxelPoly; import it.units.erallab.hmsrobots.util.Domain; import org.apache.commons.lang3.ArrayUtils; import org.dyn4j.dynamics.joint.DistanceJoint; import java.util.*; public class BreakableVoxel extends SensingVoxel { public enum ComponentType { ACTUATOR, SENSORS, STRUCTURE } public enum MalfunctionType { NONE, ZERO, FROZEN, RANDOM } public enum MalfunctionTrigger { CONTROL, AREA, TIME } @JsonProperty private final Map<ComponentType, Set<MalfunctionType>> malfunctions; @JsonProperty private final Map<MalfunctionTrigger, Double> triggerThresholds; @JsonProperty private final double restoreTime; @JsonProperty private final long randomSeed; private final EnumMap<MalfunctionTrigger, Double> triggerCounters; private final EnumMap<ComponentType, MalfunctionType> state; private transient double lastT; private transient double lastBreakT; private transient double lastControlEnergy; private transient double lastAreaRatioEnergy; private transient double[] sensorReadings; private transient Random random; @JsonCreator public BreakableVoxel( @JsonProperty("sideLength") double sideLength, @JsonProperty("massSideLengthRatio") double massSideLengthRatio, @JsonProperty("springF") double springF, @JsonProperty("springD") double springD, @JsonProperty("massLinearDamping") double massLinearDamping, @JsonProperty("massAngularDamping") double massAngularDamping, @JsonProperty("friction") double friction, @JsonProperty("restitution") double restitution, @JsonProperty("mass") double mass, @JsonProperty("limitContractionFlag") boolean limitContractionFlag, @JsonProperty("massCollisionFlag") boolean massCollisionFlag, @JsonProperty("areaRatioMaxDelta") double areaRatioMaxDelta, @JsonProperty("springScaffoldings") EnumSet<SpringScaffolding> springScaffoldings, @JsonProperty("maxForce") double maxForce, @JsonProperty("forceMethod") ForceMethod forceMethod, @JsonProperty("sensors") List<Sensor> sensors, @JsonProperty("randomSeed") long randomSeed, @JsonProperty("malfunctions") Map<ComponentType, Set<MalfunctionType>> malfunctions, @JsonProperty("triggerThresholds") Map<MalfunctionTrigger, Double> triggerThresholds, @JsonProperty("restoreTime") double restoreTime ) { super(sideLength, massSideLengthRatio, springF, springD, massLinearDamping, massAngularDamping, friction, restitution, mass, limitContractionFlag, massCollisionFlag, areaRatioMaxDelta, springScaffoldings, maxForce, forceMethod, sensors); this.randomSeed = randomSeed; this.malfunctions = malfunctions; this.triggerThresholds = triggerThresholds; this.restoreTime = restoreTime; triggerCounters = new EnumMap<>(MalfunctionTrigger.class); state = new EnumMap<>(ComponentType.class); reset(); } public BreakableVoxel(double maxForce, ForceMethod forceMethod, List<Sensor> sensors, long randomSeed, Map<ComponentType, Set<MalfunctionType>> malfunctions, Map<MalfunctionTrigger, Double> triggerThresholds, double restoreTime) { super(maxForce, forceMethod, sensors); this.randomSeed = randomSeed; this.malfunctions = malfunctions; this.triggerThresholds = triggerThresholds; this.restoreTime = restoreTime; triggerCounters = new EnumMap<>(MalfunctionTrigger.class); state = new EnumMap<>(ComponentType.class); reset(); } public BreakableVoxel(List<Sensor> sensors, long randomSeed, Map<ComponentType, Set<MalfunctionType>> malfunctions, Map<MalfunctionTrigger, Double> triggerThresholds, double restoreTime) { super(sensors); this.randomSeed = randomSeed; this.malfunctions = malfunctions; this.triggerThresholds = triggerThresholds; this.restoreTime = restoreTime; triggerCounters = new EnumMap<>(MalfunctionTrigger.class); state = new EnumMap<>(ComponentType.class); Arrays.stream(ComponentType.values()).sequential().forEach(component -> state.put(component, MalfunctionType.NONE)); reset(); } @Override public void applyForce(double f) { double innerF = f; if (state.get(ComponentType.ACTUATOR).equals(MalfunctionType.ZERO)) { f = 0; } else if (state.get(ComponentType.ACTUATOR).equals(MalfunctionType.FROZEN)) { f = getLastAppliedForce(); } else if (state.get(ComponentType.ACTUATOR).equals(MalfunctionType.RANDOM)) { f = random.nextDouble() * 2d - 1d; } super.applyForce(f); } private void updateStructureMalfunctionType() { if (state.get(ComponentType.STRUCTURE).equals(MalfunctionType.NONE)) { for (DistanceJoint springJoint : springJoints) { springJoint.setFrequency(springF); } } else if (state.get(ComponentType.STRUCTURE).equals(MalfunctionType.FROZEN)) { for (DistanceJoint springJoint : springJoints) { springJoint.setFrequency(0d); springJoint.setDampingRatio(0d); } } else { throw new IllegalArgumentException("Unsupported structure malfunction type."); } } public boolean isBroken() { return !state.get(ComponentType.ACTUATOR).equals(MalfunctionType.NONE) || !state.get(ComponentType.SENSORS).equals(MalfunctionType.NONE) || !state.get(ComponentType.STRUCTURE).equals(MalfunctionType.NONE); } private double[] random(Domain[] domains) { double[] values = new double[domains.length]; for (int i = 0; i < domains.length; i++) { values[i] = random.nextDouble() * (domains[i].getMax() - domains[i].getMin()) + domains[i].getMin(); } return values; } @Override public VoxelPoly getVoxelPoly() { return new VoxelPoly( getVertices(), getAngle(), getLinearVelocity(), Touch.isTouchingGround(this), getAreaRatio(), getAreaRatioEnergy(), getLastAppliedForce(), getControlEnergy(), new EnumMap<>(state) ); } @Override public void reset() { super.reset(); lastT = 0d; lastBreakT = 0d; lastControlEnergy = 0d; lastAreaRatioEnergy = 0d; random = new Random(randomSeed); sensorReadings = null; Arrays.stream(MalfunctionTrigger.values()).sequential().forEach(trigger -> triggerCounters.put(trigger, 0d)); Arrays.stream(ComponentType.values()).sequential().forEach(component -> state.put(component, MalfunctionType.NONE)); updateStructureMalfunctionType(); } @Override public double[] getSensorReadings() { return switch (state.get(ComponentType.SENSORS)) { case NONE, FROZEN -> sensorReadings; case ZERO -> new double[sensorReadings.length]; case RANDOM -> getSensors().stream() .map(s -> random(s.getDomains())) .reduce(ArrayUtils::addAll) .orElse(new double[sensorReadings.length]); }; } @Override public void act(double t) { super.act(t); if (state.get(ComponentType.SENSORS).equals(MalfunctionType.NONE) || sensorReadings == null) { sensorReadings = super.getSensorReadings(); } //update counters triggerCounters.put(MalfunctionTrigger.TIME, triggerCounters.get(MalfunctionTrigger.TIME) + t - lastT); triggerCounters.put(MalfunctionTrigger.CONTROL, triggerCounters.get(MalfunctionTrigger.CONTROL) + (getControlEnergy() - lastControlEnergy)); triggerCounters.put(MalfunctionTrigger.AREA, triggerCounters.get(MalfunctionTrigger.AREA) + (getAreaRatioEnergy() - lastAreaRatioEnergy)); lastT = t; lastControlEnergy = getControlEnergy(); lastAreaRatioEnergy = getAreaRatioEnergy(); boolean breaking = false; //check if malfunction is applicable for (Map.Entry<MalfunctionTrigger, Double> triggerThreshold : triggerThresholds.entrySet()) { if (random.nextDouble() < 1d - Math.tanh(triggerThreshold.getValue() / triggerCounters.get(triggerThreshold.getKey()))) { //reset counters Arrays.stream(MalfunctionTrigger.values()).sequential().forEach(trigger -> triggerCounters.put(trigger, 0d)); //choose component and malfunction ComponentType[] componentTypes = malfunctions.keySet().toArray(ComponentType[]::new); if (componentTypes.length > 0) { breaking = true; ComponentType componentType = componentTypes[random.nextInt(componentTypes.length)]; MalfunctionType[] malfunctionTypes = malfunctions.get(componentType).toArray(MalfunctionType[]::new); MalfunctionType malfunctionType = malfunctionTypes[random.nextInt(malfunctionTypes.length)]; state.put(componentType, malfunctionType); updateStructureMalfunctionType(); } } } if (breaking) { lastBreakT = t; } //possibly restore if (t - lastBreakT > restoreTime) { state.put(ComponentType.ACTUATOR, MalfunctionType.NONE); state.put(ComponentType.SENSORS, MalfunctionType.NONE); state.put(ComponentType.STRUCTURE, MalfunctionType.NONE); } } @Override public String toString() { return "BreakableVoxel{" + "malfunctions=" + malfunctions + ", triggerThresholds=" + triggerThresholds + ", restoreTime=" + restoreTime + '}'; } }
10,263
39.56917
241
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/objects/WorldObject.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.objects; import org.dyn4j.dynamics.World; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public interface WorldObject { void addTo(World world); }
955
31.965517
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/objects/Robot.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.Actionable; import it.units.erallab.hmsrobots.core.controllers.Controller; import it.units.erallab.hmsrobots.core.geometry.BoundingBox; import it.units.erallab.hmsrobots.core.snapshots.RobotShape; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.core.snapshots.Snapshottable; import it.units.erallab.hmsrobots.core.snapshots.VoxelPoly; import it.units.erallab.hmsrobots.util.Grid; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.World; import org.dyn4j.dynamics.joint.Joint; import org.dyn4j.dynamics.joint.WeldJoint; import org.dyn4j.geometry.Vector2; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class Robot<V extends ControllableVoxel> implements Actionable, Serializable, WorldObject, Snapshottable { @JsonProperty private final Controller<V> controller; @JsonProperty private final Grid<? extends V> voxels; private transient List<Joint> joints; @JsonCreator public Robot( @JsonProperty("controller") Controller<V> controller, @JsonProperty("voxels") Grid<? extends V> voxels ) { this.controller = controller; this.voxels = voxels; reset(); } @Serial private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); reset(); } private void assemble() { joints = new ArrayList<>(); //translate voxels for (int gx = 0; gx < voxels.getW(); gx++) { for (int gy = 0; gy < voxels.getH(); gy++) { Voxel voxel = voxels.get(gx, gy); if (voxel != null) { voxel.setOwner(this); voxel.translate(new Vector2( (double) gx * voxel.getSideLength(), (double) gy * voxel.getSideLength() )); //check for adjacent voxels if ((gx > 0) && (voxels.get(gx - 1, gy) != null)) { Voxel adjacent = voxels.get(gx - 1, gy); joints.add(join(voxel.getVertexBodies()[0], adjacent.getVertexBodies()[1])); joints.add(join(voxel.getVertexBodies()[3], adjacent.getVertexBodies()[2])); } if ((gy > 0) && (voxels.get(gx, gy - 1) != null)) { Voxel adjacent = voxels.get(gx, gy - 1); joints.add(join(voxel.getVertexBodies()[3], adjacent.getVertexBodies()[0])); joints.add(join(voxel.getVertexBodies()[2], adjacent.getVertexBodies()[1])); } } } } } private static Joint join(Body body1, Body body2) { return new WeldJoint(body1, body2, new Vector2( (body1.getWorldCenter().x + body1.getWorldCenter().x) / 2d, (body1.getWorldCenter().y + body1.getWorldCenter().y) / 2d )); } @Override public Snapshot getSnapshot() { Grid<Snapshot> voxelSnapshots = Grid.create(voxels, v -> v == null ? null : v.getSnapshot()); Snapshot snapshot = new Snapshot( new RobotShape( Grid.create(voxelSnapshots, s -> s == null ? null : ((VoxelPoly) s.getContent())), boundingBox() ), getClass() ); if (controller instanceof Snapshottable) { snapshot.getChildren().add(((Snapshottable) controller).getSnapshot()); } snapshot.getChildren().addAll(voxelSnapshots.values().stream().filter(Objects::nonNull).collect(Collectors.toList())); return snapshot; } @Override public void addTo(World world) { for (Voxel voxel : voxels.values()) { if (voxel != null) { voxel.addTo(world); } } for (Joint joint : joints) { world.addJoint(joint); } } @Override public void act(final double t) { voxels.values().stream().filter(Objects::nonNull).forEach(v -> v.act(t)); controller.control(t, voxels); } @Override public void reset() { voxels.values().stream().filter(Objects::nonNull).forEach(ControllableVoxel::reset); assemble(); controller.reset(); } public Vector2 getCenter() { double xc = 0d; double yc = 0d; double n = 0; for (Voxel voxel : voxels.values()) { if (voxel != null) { final Vector2 center = voxel.getCenter(); xc = xc + center.x; yc = yc + center.y; n = n + 1; } } return new Vector2(xc / n, yc / n); } public void translate(Vector2 v) { for (Voxel voxel : voxels.values()) { if (voxel != null) { voxel.translate(v); } } } public BoundingBox boundingBox() { return voxels.values().stream() .filter(Objects::nonNull) .map(Voxel::boundingBox) .reduce(BoundingBox::largest) .get(); } public Controller<V> getController() { return controller; } public Grid<? extends V> getVoxels() { return voxels; } @Override public String toString() { return "Robot{" + "controller=" + controller + ", voxels=" + voxels + '}'; } }
6,055
29.897959
122
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/objects/SensingVoxel.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.sensors.Sensor; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import org.apache.commons.lang3.ArrayUtils; import java.util.EnumSet; import java.util.List; public class SensingVoxel extends ControllableVoxel { @JsonProperty private final List<Sensor> sensors; @JsonCreator public SensingVoxel( @JsonProperty("sideLength") double sideLength, @JsonProperty("massSideLengthRatio") double massSideLengthRatio, @JsonProperty("springF") double springF, @JsonProperty("springD") double springD, @JsonProperty("massLinearDamping") double massLinearDamping, @JsonProperty("massAngularDamping") double massAngularDamping, @JsonProperty("friction") double friction, @JsonProperty("restitution") double restitution, @JsonProperty("mass") double mass, @JsonProperty("limitContractionFlag") boolean limitContractionFlag, @JsonProperty("massCollisionFlag") boolean massCollisionFlag, @JsonProperty("areaRatioMaxDelta") double areaRatioMaxDelta, @JsonProperty("springScaffoldings") EnumSet<SpringScaffolding> springScaffoldings, @JsonProperty("maxForce") double maxForce, @JsonProperty("forceMethod") ForceMethod forceMethod, @JsonProperty("sensors") List<Sensor> sensors ) { super(sideLength, massSideLengthRatio, springF, springD, massLinearDamping, massAngularDamping, friction, restitution, mass, limitContractionFlag, massCollisionFlag, areaRatioMaxDelta, springScaffoldings, maxForce, forceMethod); this.sensors = sensors; } public SensingVoxel(double maxForce, ForceMethod forceMethod, List<Sensor> sensors) { super(maxForce, forceMethod); this.sensors = sensors; } public SensingVoxel(List<Sensor> sensors) { this.sensors = sensors; } @Override public void act(double t) { super.act(t); sensors.forEach(s -> s.act(t)); } @Override public void reset() { super.reset(); sensors.forEach(s -> { s.setVoxel(this); s.reset(); }); } public double[] getSensorReadings() { return sensors.stream() .map(Sensor::getReadings) .reduce(ArrayUtils::addAll) .orElse(new double[sensors.stream().mapToInt(s -> s.getDomains().length).sum()]); } public List<Sensor> getSensors() { return sensors; } @Override protected void fillSnapshot(Snapshot snapshot) { super.fillSnapshot(snapshot); //add sensors for (Sensor sensor : sensors) { snapshot.getChildren().add(sensor.getSnapshot()); } } @Override public String toString() { return "SensingVoxel{" + "sensors=" + sensors + '}'; } }
3,602
32.672897
232
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/geometry/BoundingBox.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.geometry; import java.io.Serializable; public class BoundingBox implements Shape, Serializable { public final Point2 min; public final Point2 max; public static BoundingBox of(double minX, double minY, double maxX, double maxY) { return of( Point2.of(minX, minY), Point2.of(maxX, maxY) ); } public static BoundingBox of(Point2... points) { if (points.length == 0) { throw new IllegalArgumentException("Cannot build on 0 points"); } double minX = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; for (Point2 point : points) { minX = Math.min(minX, point.x); maxX = Math.max(maxX, point.x); minY = Math.min(minY, point.y); maxY = Math.max(maxY, point.y); } return new BoundingBox( Point2.of(minX, minY), Point2.of(maxX, maxY) ); } private BoundingBox(Point2 min, Point2 max) { this.min = min; this.max = max; } @Override public String toString() { return "BoundingBox{" + "min=" + min + ", max=" + max + '}'; } public static BoundingBox largest(BoundingBox bb1, BoundingBox bb2) { return BoundingBox.of(bb1.min, bb1.max, bb2.min, bb2.max); } @Override public Point2 center() { return Point2.of((min.x + max.x) / 2d, (min.y + max.x) / 2d); } @Override public BoundingBox boundingBox() { return this; } public double width() { return max.x - min.x; } public double height() { return max.y - min.y; } }
2,413
26.431818
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/geometry/Poly.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.geometry; import java.util.List; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class Poly implements Shape { private final Point2[] vertexes; public Poly(List<Point2> vertexes) { this.vertexes = new Point2[vertexes.size()]; for (int i = 0; i < vertexes.size(); i++) { this.vertexes[i] = vertexes.get(i); } } private Poly(Point2... vertexes) { this.vertexes = vertexes; } public static Poly of(Point2... vertexes) { return new Poly(vertexes); } @Override public BoundingBox boundingBox() { return BoundingBox.of(vertexes); } public Point2[] getVertexes() { return vertexes; } public double area() { double a = 0d; int l = vertexes.length; for (int i = 0; i < l; i++) { a = a + vertexes[i].x * (vertexes[(l + i + 1) % l].y - vertexes[(l + i - 1) % l].y); } a = 0.5d * Math.abs(a); return a; } @Override public Point2 center() { return Point2.average(vertexes); } }
1,724
24.367647
90
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/geometry/Shape.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.geometry; import java.io.Serializable; public interface Shape extends Serializable { BoundingBox boundingBox(); Point2 center(); }
870
32.5
74
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/geometry/Point2.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.geometry; import org.dyn4j.geometry.Vector2; /** * @author eric */ public class Point2 implements Shape { public final double x; public final double y; private Point2(double x, double y) { this.x = x; this.y = y; } public static Point2 of(double x, double y) { return new Point2(x, y); } public static Point2 of(Vector2 v) { return new Point2(v.x, v.y); } public static Point2 average(Point2... points) { double cx = 0; double cy = 0; double n = 0; for (Point2 point : points) { cx = cx + point.x; cy = cy + point.y; n = n + 1; } return Point2.of(cx / n, cy / n); } @Override public BoundingBox boundingBox() { return BoundingBox.of(this); } @Override public Point2 center() { return this; } @Override public String toString() { return String.format("(%5.3f, %5.3f)", x, y); } }
1,632
22.328571
74
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/geometry/Vector.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.geometry; public class Vector implements Shape { private final Point2 start; private final Point2 end; private Vector(Point2 start, Point2 end) { this.start = start; this.end = end; } public static Vector of(Point2 start, Point2 end) { return new Vector(start, end); } @Override public BoundingBox boundingBox() { return BoundingBox.of(start, end); } @Override public Point2 center() { return Point2.average(start, end); } public Point2 getStart() { return start; } public Point2 getEnd() { return end; } }
1,307
24.647059
74
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/TimeFunctions.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.objects.ControllableVoxel; import it.units.erallab.hmsrobots.core.snapshots.ScopedReadings; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.core.snapshots.Snapshottable; import it.units.erallab.hmsrobots.core.snapshots.StackedScopedReadings; import it.units.erallab.hmsrobots.util.Domain; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.SerializableFunction; import java.util.Objects; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class TimeFunctions extends AbstractController<ControllableVoxel> implements Snapshottable { @JsonProperty private final Grid<SerializableFunction<Double, Double>> functions; private double[] outputs; @JsonCreator public TimeFunctions( @JsonProperty("functions") Grid<SerializableFunction<Double, Double>> functions ) { this.functions = functions; } @Override public Grid<Double> computeControlSignals(double t, Grid<? extends ControllableVoxel> voxels) { outputs = new double[(int) voxels.values().stream().filter(Objects::nonNull).count()]; Grid<Double> controlSignals = Grid.create(voxels.getW(), voxels.getH()); int c = 0; for (Grid.Entry<? extends ControllableVoxel> entry : voxels) { SerializableFunction<Double, Double> function = functions.get(entry.getX(), entry.getY()); if ((entry.getValue() != null) && (function != null)) { double v = function.apply(t); controlSignals.set(entry.getX(), entry.getY(), v); outputs[c] = v; c = c + 1; } } return controlSignals; } @Override public void reset() { } public Grid<SerializableFunction<Double, Double>> getFunctions() { return functions; } @Override public Snapshot getSnapshot() { return new Snapshot( new StackedScopedReadings(new ScopedReadings(outputs, Domain.of(-1d, 1d, outputs.length))), getClass() ); } @Override public String toString() { return "TimeFunctions{" + "functions=" + functions + '}'; } }
3,031
33.067416
99
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/DistributedSensingNonDirectional.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.util.Grid; /** * @author eric */ public class DistributedSensingNonDirectional extends DistributedSensing { public static int nOfOutputs(SensingVoxel voxel, int signals) { return 1 + signals; } @JsonCreator public DistributedSensingNonDirectional( @JsonProperty("signals") int signals, @JsonProperty("nOfInputGrid") Grid<Integer> nOfInputGrid, @JsonProperty("nOfOutputGrid") Grid<Integer> nOfOutputGrid, @JsonProperty("functions") Grid<TimedRealFunction> functions ) { super(signals, nOfInputGrid, nOfOutputGrid, functions); } public DistributedSensingNonDirectional(Grid<? extends SensingVoxel> voxels, int stateSize) { this( stateSize, Grid.create(voxels, v -> (v == null) ? 0 : nOfInputs(v, stateSize)), Grid.create(voxels, v -> (v == null) ? 0 : nOfOutputs(v, stateSize)), Grid.create( voxels.getW(), voxels.getH(), (x, y) -> voxels.get(x, y) == null ? null : new FunctionWrapper(RealFunction.build( (double[] in) -> new double[1 + stateSize], nOfInputs(voxels.get(x, y), stateSize), nOfOutputs(voxels.get(x, y), stateSize)) ) ) ); } @Override protected double[] getLastSignals(int x, int y) { double[] values = new double[signals * Dir.values().length]; if (signals <= 0) { return values; } int c = 0; for (Dir dir : Dir.values()) { int adjacentX = x + dir.dx; int adjacentY = y + dir.dy; double[] lastSignals = lastSignalsGrid.get(adjacentX, adjacentY); if (lastSignals != null) { System.arraycopy(lastSignals, 0, values, c, signals); } c = c + signals; } return values; } @Override public String toString() { return super.toString().replace("DistributedSensing", "DistributedSensingNonDirectional"); } }
2,914
34.120482
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/PruningMultiLayerPerceptron.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.math3.util.Pair; import java.util.*; import java.util.stream.Collectors; public class PruningMultiLayerPerceptron extends MultiLayerPerceptron implements TimedRealFunction, Resettable { public enum Context {NETWORK, LAYER, NEURON} public enum Criterion { WEIGHT, SIGNAL_MEAN, ABS_SIGNAL_MEAN, SIGNAL_VARIANCE, RANDOM } @JsonProperty private final double pruningTime; @JsonProperty private final Context context; @JsonProperty private final Criterion criterion; @JsonProperty private final double rate; private boolean pruned; private long counter; private double[][][] prunedWeights; private double[][][] means; private double[][][] absMeans; private double[][][] meanDiffSquareSums; //https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Weighted_incremental_algorithm public PruningMultiLayerPerceptron( @JsonProperty("activationFunction") ActivationFunction activationFunction, @JsonProperty("weights") double[][][] weights, @JsonProperty("neurons") int[] neurons, @JsonProperty("nOfCalls") double pruningTime, @JsonProperty("context") Context context, @JsonProperty("criterion") Criterion criterion, @JsonProperty("rate") double rate ) { super(activationFunction, weights, neurons); this.pruningTime = pruningTime; this.context = context; this.criterion = criterion; this.rate = rate; reset(); } public PruningMultiLayerPerceptron(ActivationFunction activationFunction, int nOfInput, int[] innerNeurons, int nOfOutput, double[] weights, double pruningTime, Context context, Criterion criterion, double rate) { super(activationFunction, nOfInput, innerNeurons, nOfOutput, weights); this.pruningTime = pruningTime; this.context = context; this.criterion = criterion; this.rate = rate; reset(); } public PruningMultiLayerPerceptron(ActivationFunction activationFunction, int nOfInput, int[] innerNeurons, int nOfOutput, double pruningTime, Context context, Criterion criterion, double rate) { super(activationFunction, nOfInput, innerNeurons, nOfOutput); this.pruningTime = pruningTime; this.context = context; this.criterion = criterion; this.rate = rate; reset(); } @Override public void setParams(double[] params) { super.setParams(params); reset(); } @Override public void reset() { if (rate < 0 || rate > 1) { throw new IllegalArgumentException(String.format("Pruning rate should be defined in [0,1]: %f found", rate)); } pruned = false; counter = 0; means = new double[weights.length][][]; absMeans = new double[weights.length][][]; meanDiffSquareSums = new double[weights.length][][]; prunedWeights = new double[weights.length][][]; for (int i = 1; i < neurons.length; i++) { means[i - 1] = new double[weights[i - 1].length][]; absMeans[i - 1] = new double[weights[i - 1].length][]; meanDiffSquareSums[i - 1] = new double[weights[i - 1].length][]; prunedWeights[i - 1] = new double[weights[i - 1].length][]; for (int j = 0; j < weights[i - 1].length; j++) { means[i - 1][j] = new double[weights[i - 1][j].length]; absMeans[i - 1][j] = new double[weights[i - 1][j].length]; meanDiffSquareSums[i - 1][j] = new double[weights[i - 1][j].length]; prunedWeights[i - 1][j] = new double[weights[i - 1][j].length]; for (int k = 0; k < weights[i - 1][j].length; k++) { means[i - 1][j][k] = weights[i - 1][j][k]; absMeans[i - 1][j][k] = Math.abs(weights[i - 1][j][k]); prunedWeights[i - 1][j][k] = weights[i - 1][j][k]; } } } } private void prune() { pruned = true; List<Pair<int[], Double>> pairs = new ArrayList<>(); Random random = new Random((long) (10000 * weights[0][0][0])); // TODO to improve, should be passed to constructor for (int i = 1; i < neurons.length; i++) { for (int j = 0; j < neurons[i]; j++) { for (int k = 0; k < neurons[i - 1] + 1; k++) { pairs.add(Pair.create( new int[]{i, j, k}, switch (criterion) { case WEIGHT -> Math.abs(prunedWeights[i - 1][j][k]); case SIGNAL_MEAN -> means[i - 1][j][k]; case ABS_SIGNAL_MEAN -> absMeans[i - 1][j][k]; case SIGNAL_VARIANCE -> meanDiffSquareSums[i - 1][j][k]; case RANDOM -> random.nextDouble(); } )); } } } if (context.equals(Context.NETWORK)) { prune(pairs); } else if (context.equals(Context.LAYER)) { for (int i = 1; i < neurons.length; i++) { final int localI = i; prune(pairs.stream().filter(p -> p.getKey()[0] == localI).collect(Collectors.toList())); } } else if (context.equals(Context.NEURON)) { for (int i = 1; i < neurons.length; i++) { for (int j = 0; j < neurons[i]; j++) { final int localI = i; final int localJ = j; prune(pairs.stream().filter(p -> p.getKey()[0] == localI && p.getKey()[1] == localJ).collect(Collectors.toList())); } } } } private void prune(List<Pair<int[], Double>> localPairs) { localPairs.sort(Comparator.comparing(Pair::getValue)); localPairs.subList(0, (int) Math.round(localPairs.size() * rate)).forEach(p -> prune(p.getKey())); } private void prune(int[] is) { int i = is[0]; int j = is[1]; int k = is[2]; prunedWeights[i - 1][j][k] = 0d; if (criterion.equals(Criterion.SIGNAL_VARIANCE) && k != 0) { prunedWeights[i - 1][j][0] = prunedWeights[i - 1][j][0] + prunedWeights[i - 1][j][k]; } } @Override public double[] apply(double t, double[] input) { if (t >= pruningTime) { prune(); } if (input.length != neurons[0]) { throw new IllegalArgumentException(String.format("Expected input length is %d: found %d", neurons[0], input.length)); } activationValues[0] = Arrays.stream(input).map(activationFunction::apply).toArray(); for (int i = 1; i < neurons.length; i++) { activationValues[i] = new double[neurons[i]]; for (int j = 0; j < neurons[i]; j++) { double sum = prunedWeights[i - 1][j][0]; //set the bias for (int k = 1; k < neurons[i - 1] + 1; k++) { double signal = activationValues[i - 1][k - 1] * prunedWeights[i - 1][j][k]; sum = sum + signal; double delta = signal - means[i - 1][j][k]; means[i - 1][j][k] = means[i - 1][j][k] + delta / ((double) counter + 1d); absMeans[i - 1][j][k] = absMeans[i - 1][j][k] + (Math.abs(signal) - absMeans[i - 1][j][k]) / ((double) counter + 1d); meanDiffSquareSums[i - 1][j][k] = meanDiffSquareSums[i - 1][j][k] + delta * (signal - means[i - 1][j][k]); } activationValues[i][j] = activationFunction.apply(sum); } } counter = counter + 1; return activationValues[neurons.length - 1]; } @Override public double[][][] getWeights() { return prunedWeights; } }
8,004
36.759434
215
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/AbstractController.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import it.units.erallab.hmsrobots.core.objects.ControllableVoxel; import it.units.erallab.hmsrobots.util.Grid; public abstract class AbstractController<V extends ControllableVoxel> implements Controller<V> { @Override public void control(double t, Grid<? extends V> voxels) { Grid<Double> controlSignals = computeControlSignals(t, voxels); voxels.forEach(e -> { if (e.getValue() != null) { e.getValue().applyForce(controlSignals.get(e.getX(), e.getY())); } }); } public abstract Grid<Double> computeControlSignals(double t, Grid<? extends V> voxels); public AbstractController<V> step(double stepT) { return new StepController<>(this, stepT); } public AbstractController<V> smoothed(double controlSignalSpeed) { return new SmoothedController<>(this, controlSignalSpeed); } }
1,646
34.804348
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/MultiLayerPerceptron.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.snapshots.MLPState; import it.units.erallab.hmsrobots.core.snapshots.Snapshottable; import it.units.erallab.hmsrobots.util.Domain; import it.units.erallab.hmsrobots.util.Parametrized; import java.io.Serializable; import java.util.Arrays; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; /** * @author eric */ public class MultiLayerPerceptron implements Serializable, RealFunction, Parametrized, Snapshottable, StatefulNN { public enum ActivationFunction implements Function<Double, Double> { RELU(x -> (x < 0) ? 0d : x, Domain.of(0d, Double.POSITIVE_INFINITY)), SIGMOID(x -> 1d / (1d + Math.exp(-x)), Domain.of(0d, 1d)), SIN(Math::sin, Domain.of(-1d, 1d)), TANH(Math::tanh, Domain.of(-1d, 1d)), SIGN(Math::signum, Domain.of(-1d, 1d)), IDENTITY(x -> x, Domain.of(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)); private final Function<Double, Double> f; private final Domain domain; ActivationFunction(Function<Double, Double> f, Domain domain) { this.f = f; this.domain = domain; } public Function<Double, Double> getF() { return f; } public Domain getDomain() { return domain; } public Double apply(Double x) { return f.apply(x); } } @JsonProperty protected final ActivationFunction activationFunction; @JsonProperty protected final double[][][] weights; @JsonProperty protected final int[] neurons; protected final double[][] activationValues; @JsonCreator public MultiLayerPerceptron( @JsonProperty("activationFunction") ActivationFunction activationFunction, @JsonProperty("weights") double[][][] weights, @JsonProperty("neurons") int[] neurons ) { this.activationFunction = activationFunction; this.weights = weights; this.neurons = neurons; activationValues = new double[neurons.length][]; if (flat(weights, neurons).length != countWeights(neurons)) { throw new IllegalArgumentException(String.format( "Wrong number of weights: %d expected, %d found", countWeights(neurons), flat(weights, neurons).length )); } } public MultiLayerPerceptron(ActivationFunction activationFunction, int nOfInput, int[] innerNeurons, int nOfOutput, double[] weights) { this( activationFunction, unflat(weights, countNeurons(nOfInput, innerNeurons, nOfOutput)), countNeurons(nOfInput, innerNeurons, nOfOutput) ); } public MultiLayerPerceptron(ActivationFunction activationFunction, int nOfInput, int[] innerNeurons, int nOfOutput) { this( activationFunction, nOfInput, innerNeurons, nOfOutput, new double[countWeights(countNeurons(nOfInput, innerNeurons, nOfOutput))] ); } public static int[] countNeurons(int nOfInput, int[] innerNeurons, int nOfOutput) { final int[] neurons; neurons = new int[2 + innerNeurons.length]; System.arraycopy(innerNeurons, 0, neurons, 1, innerNeurons.length); neurons[0] = nOfInput; neurons[neurons.length - 1] = nOfOutput; return neurons; } public static double[][][] unflat(double[] flatWeights, int[] neurons) { double[][][] unflatWeights = new double[neurons.length - 1][][]; int c = 0; for (int i = 1; i < neurons.length; i++) { unflatWeights[i - 1] = new double[neurons[i]][neurons[i - 1] + 1]; for (int j = 0; j < neurons[i]; j++) { for (int k = 0; k < neurons[i - 1] + 1; k++) { unflatWeights[i - 1][j][k] = flatWeights[c]; c = c + 1; } } } return unflatWeights; } public static double[] flat(double[][][] unflatWeights, int[] neurons) { double[] flatWeights = new double[countWeights(neurons)]; int c = 0; for (int i = 1; i < neurons.length; i++) { for (int j = 0; j < neurons[i]; j++) { for (int k = 0; k < neurons[i - 1] + 1; k++) { flatWeights[c] = unflatWeights[i - 1][j][k]; c = c + 1; } } } return flatWeights; } public static int countWeights(int[] neurons) { int c = 0; for (int i = 1; i < neurons.length; i++) { c = c + neurons[i] * (neurons[i - 1] + 1); } return c; } public static int countWeights(int nOfInput, int[] innerNeurons, int nOfOutput) { return countWeights(countNeurons(nOfInput, innerNeurons, nOfOutput)); } @Override public double[] apply(double[] input) { if (input.length != neurons[0]) { throw new IllegalArgumentException(String.format("Expected input length is %d: found %d", neurons[0], input.length)); } activationValues[0] = Arrays.stream(input).map(activationFunction.f::apply).toArray(); for (int i = 1; i < neurons.length; i++) { activationValues[i] = new double[neurons[i]]; for (int j = 0; j < neurons[i]; j++) { double sum = weights[i - 1][j][0]; //set the bias for (int k = 1; k < neurons[i - 1] + 1; k++) { sum = sum + activationValues[i - 1][k - 1] * weights[i - 1][j][k]; } activationValues[i][j] = activationFunction.apply(sum); } } return activationValues[neurons.length - 1]; } @Override public int getInputDimension() { return neurons[0]; } @Override public int getOutputDimension() { return neurons[neurons.length - 1]; } public double[][][] getWeights() { return weights; } public int[] getNeurons() { return neurons; } public double[][] getActivationValues() { return activationValues; } @Override public double[] getParams() { return MultiLayerPerceptron.flat(weights, neurons); } @Override public MLPState getState() { return new MLPState(getActivationValues(), getWeights(), activationFunction.getDomain()); } @Override public void setParams(double[] params) { double[][][] newWeights = MultiLayerPerceptron.unflat(params, neurons); for (int l = 0; l < newWeights.length; l++) { for (int s = 0; s < newWeights[l].length; s++) { System.arraycopy(newWeights[l][s], 0, weights[l][s], 0, newWeights[l][s].length); } } } @Override public int hashCode() { int hash = 5; hash = 67 * hash + Objects.hashCode(this.activationFunction); hash = 67 * hash + Arrays.deepHashCode(this.weights); hash = 67 * hash + Arrays.hashCode(this.neurons); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final MultiLayerPerceptron other = (MultiLayerPerceptron) obj; if (this.activationFunction != other.activationFunction) { return false; } if (!Arrays.deepEquals(this.weights, other.weights)) { return false; } return Arrays.equals(this.neurons, other.neurons); } @Override public String toString() { return "MLP." + activationFunction.toString().toLowerCase() + "[" + Arrays.stream(neurons).mapToObj(Integer::toString).collect(Collectors.joining(",")) + "]"; } public String weightsString() { StringBuilder sb = new StringBuilder(); for (int i = 1; i < neurons.length; i++) { for (int j = 0; j < neurons[i]; j++) { sb.append("->(").append(i).append(",").append(j).append("):"); for (int k = 0; k < neurons[i - 1] + 1; k++) { sb.append(String.format(" %+5.3f", weights[i - 1][j][k])); } sb.append("\n"); } } return sb.toString(); } }
8,576
30.189091
137
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/TimedRealFunction.java
package it.units.erallab.hmsrobots.core.controllers; import java.io.Serializable; /** * @author eric on 2021/03/09 for 2dhmsr */ public interface TimedRealFunction extends Serializable { double[] apply(double t, double[] input); int getInputDimension(); int getOutputDimension(); }
294
18.666667
57
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/DistributedSensing.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.util.Grid; import org.apache.commons.lang3.ArrayUtils; import java.util.Objects; /** * @author eric */ public class DistributedSensing extends AbstractController<SensingVoxel> { protected enum Dir { N(0, -1, 0), E(1, 0, 1), S(0, 1, 2), W(-1, 0, 3); final int dx; final int dy; private final int index; Dir(int dx, int dy, int index) { this.dx = dx; this.dy = dy; this.index = index; } private static Dir adjacent(Dir dir) { return switch (dir) { case N -> Dir.S; case E -> Dir.W; case S -> Dir.N; case W -> Dir.E; }; } } protected static class FunctionWrapper implements TimedRealFunction { @JsonProperty private final TimedRealFunction inner; @JsonCreator public FunctionWrapper(@JsonProperty("inner") TimedRealFunction inner) { this.inner = inner; } @Override public double[] apply(double t, double[] in) { return inner.apply(t, in); } @Override public int getInputDimension() { return inner.getInputDimension(); } @Override public int getOutputDimension() { return inner.getOutputDimension(); } } @JsonProperty protected final int signals; @JsonProperty private final Grid<Integer> nOfInputGrid; @JsonProperty private final Grid<Integer> nOfOutputGrid; @JsonProperty private final Grid<TimedRealFunction> functions; protected final Grid<double[]> lastSignalsGrid; private final Grid<double[]> currentSignalsGrid; public static int nOfInputs(SensingVoxel voxel, int signals) { return signals * Dir.values().length + voxel.getSensors().stream().mapToInt(s -> s.getDomains().length).sum(); } public static int nOfOutputs(SensingVoxel voxel, int signals) { return 1 + signals * Dir.values().length; } @JsonCreator public DistributedSensing( @JsonProperty("signals") int signals, @JsonProperty("nOfInputGrid") Grid<Integer> nOfInputGrid, @JsonProperty("nOfOutputGrid") Grid<Integer> nOfOutputGrid, @JsonProperty("functions") Grid<TimedRealFunction> functions ) { this.signals = signals; this.nOfInputGrid = nOfInputGrid; this.nOfOutputGrid = nOfOutputGrid; this.functions = functions; lastSignalsGrid = Grid.create(functions, f -> new double[signals * Dir.values().length]); currentSignalsGrid = Grid.create(functions, f -> new double[signals * Dir.values().length]); reset(); } public DistributedSensing(Grid<? extends SensingVoxel> voxels, int signals) { this( signals, Grid.create(voxels, v -> (v == null) ? 0 : nOfInputs(v, signals)), Grid.create(voxels, v -> (v == null) ? 0 : nOfOutputs(v, signals)), Grid.create( voxels.getW(), voxels.getH(), (x, y) -> voxels.get(x, y) == null ? null : new FunctionWrapper(RealFunction.build( (double[] in) -> new double[1 + signals * Dir.values().length], nOfInputs(voxels.get(x, y), signals), nOfOutputs(voxels.get(x, y), signals)) ) ) ); } public Grid<TimedRealFunction> getFunctions() { return functions; } @Override public void reset() { for (int x = 0; x < lastSignalsGrid.getW(); x++) { for (int y = 0; y < lastSignalsGrid.getH(); y++) { lastSignalsGrid.set(x, y, new double[signals * Dir.values().length]); } } for (int x = 0; x < currentSignalsGrid.getW(); x++) { for (int y = 0; y < currentSignalsGrid.getH(); y++) { currentSignalsGrid.set(x, y, new double[signals * Dir.values().length]); } } functions.values().stream().filter(Objects::nonNull).forEach(f -> { if (f instanceof Resettable) { ((Resettable) f).reset(); } }); } @Override public Grid<Double> computeControlSignals(double t, Grid<? extends SensingVoxel> voxels) { Grid<Double> controlSignals = Grid.create(voxels); for (Grid.Entry<? extends SensingVoxel> entry : voxels) { if (entry.getValue() == null) { continue; } //get inputs double[] signals = getLastSignals(entry.getX(), entry.getY()); double[] inputs = ArrayUtils.addAll(entry.getValue().getSensorReadings(), signals); //compute outputs TimedRealFunction function = functions.get(entry.getX(), entry.getY()); double[] outputs = function != null ? function.apply(t, inputs) : new double[nOfOutputs(entry.getX(), entry.getY())]; //save outputs controlSignals.set(entry.getX(), entry.getY(), outputs[0]); System.arraycopy(outputs, 1, currentSignalsGrid.get(entry.getX(), entry.getY()), 0, outputs.length - 1); } for (Grid.Entry<? extends SensingVoxel> entry : voxels) { if (entry.getValue() == null) { continue; } int x = entry.getX(); int y = entry.getY(); System.arraycopy(currentSignalsGrid.get(x, y), 0, lastSignalsGrid.get(x, y), 0, currentSignalsGrid.get(x, y).length); } return controlSignals; } public int nOfInputs(int x, int y) { return nOfInputGrid.get(x, y); } public int nOfOutputs(int x, int y) { return nOfOutputGrid.get(x, y); } protected double[] getLastSignals(int x, int y) { double[] values = new double[signals * Dir.values().length]; if (signals <= 0) { return values; } int c = 0; for (Dir dir : Dir.values()) { int adjacentX = x + dir.dx; int adjacentY = y + dir.dy; double[] lastSignals = lastSignalsGrid.get(adjacentX, adjacentY); if (lastSignals != null) { int index = Dir.adjacent(dir).index; System.arraycopy(lastSignals, index * signals, values, c, signals); } c = c + signals; } return values; } @Override public String toString() { return "DistributedSensing{" + "signals=" + signals + ", functions=" + functions + '}'; } }
6,979
30.300448
123
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/PhaseSin.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as eric) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.SerializableFunction; import java.util.Objects; /** * @author eric */ public class PhaseSin extends TimeFunctions { @JsonProperty private final double frequency; @JsonProperty private final double amplitude; @JsonProperty private final Grid<Double> phases; @JsonCreator public PhaseSin( @JsonProperty("frequency") double frequency, @JsonProperty("amplitude") double amplitude, @JsonProperty("phases") Grid<Double> phases ) { super(getFunctions(frequency, amplitude, phases)); this.phases = phases; this.frequency = frequency; this.amplitude = amplitude; } private static Grid<SerializableFunction<Double, Double>> getFunctions(final double frequency, final double amplitude, final Grid<Double> phases) { Grid<SerializableFunction<Double, Double>> functions = Grid.create(phases); for (Grid.Entry<Double> entry : phases) { if (entry.getValue() != null) { functions.set(entry.getX(), entry.getY(), t -> Math.sin(2d * Math.PI * frequency * t + entry.getValue()) * amplitude); } } return functions; } @Override public int hashCode() { int hash = 7; hash = 83 * hash + Objects.hashCode(this.phases); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PhaseSin other = (PhaseSin) obj; return Objects.equals(this.phases, other.phases); } public Grid<Double> getPhases() { return phases; } @Override public String toString() { return "PhaseSin{" + "frequency=" + frequency + ", amplitude=" + amplitude + ", phases=" + phases + '}'; } }
2,768
28.147368
149
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/StepController.java
/* * Copyright (C) 2021 Giorgia Nadizar <giorgia.nadizar@gmail.com> (as Giorgia Nadizar) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.objects.ControllableVoxel; import it.units.erallab.hmsrobots.util.Grid; public class StepController<V extends ControllableVoxel> extends AbstractController<V> { @JsonProperty private final AbstractController<V> innerController; @JsonProperty private final double stepT; double lastT = Double.NEGATIVE_INFINITY; Grid<Double> lastControlSignals = null; @JsonCreator public StepController( @JsonProperty("innerController") AbstractController<V> innerController, @JsonProperty("stepT") double stepT) { this.innerController = innerController; this.stepT = stepT; } @Override public Grid<Double> computeControlSignals(double t, Grid<? extends V> voxels) { Grid<Double> controlSignals = innerController.computeControlSignals(t, voxels); if (t - lastT >= stepT || lastControlSignals == null) { lastControlSignals = Grid.create(controlSignals, v -> v); lastT = t; } return lastControlSignals; } @Override public void reset() { innerController.reset(); lastT = Double.NEGATIVE_INFINITY; } }
2,017
32.633333
88
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/SmoothedController.java
/* * Copyright (C) 2021 Giorgia Nadizar <giorgia.nadizar@gmail.com> (as Giorgia Nadizar) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.objects.ControllableVoxel; import it.units.erallab.hmsrobots.util.Grid; public class SmoothedController<V extends ControllableVoxel> extends AbstractController<V> { @JsonProperty private final AbstractController<V> innerController; @JsonProperty private final double controlSignalSpeed; double lastT = Double.NEGATIVE_INFINITY; Grid<Double> currentControlSignals = null; @JsonCreator public SmoothedController(@JsonProperty("innerController") AbstractController<V> innerController, @JsonProperty("stepT") double controlSignalSpeed) { this.innerController = innerController; this.controlSignalSpeed = controlSignalSpeed; } @Override public Grid<Double> computeControlSignals(double t, Grid<? extends V> voxels) { Grid<Double> targetControlSignals = innerController.computeControlSignals(t, voxels); if (currentControlSignals == null) { currentControlSignals = Grid.create(targetControlSignals, v -> 0d); lastT = t; } double dT = t - lastT; double dControlSignal = dT * controlSignalSpeed; lastT = t; return Grid.create(targetControlSignals.getW(), targetControlSignals.getH(), (x, y) -> { Double targetControlSignal = targetControlSignals.get(x, y); double currentControlSignal = currentControlSignals.get(x, y); if (targetControlSignal == null) { return 0d; } if (Math.abs(targetControlSignal - currentControlSignal) <= dControlSignal) { currentControlSignals.set(x, y, targetControlSignal); } else if (targetControlSignal > currentControlSignal) { currentControlSignals.set(x, y, currentControlSignals.get(x, y) + dControlSignal); } else { currentControlSignals.set(x, y, currentControlSignals.get(x, y) - dControlSignal); } return currentControlSignals.get(x, y); }); } @Override public void reset() { innerController.reset(); currentControlSignals = null; } }
2,889
37.533333
151
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/StatefulNN.java
/* * Copyright (C) 2021 Giorgia Nadizar <giorgia.nadizar@gmail.com> (as Giorgia Nadizar) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import it.units.erallab.hmsrobots.core.snapshots.MLPState; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.core.snapshots.Snapshottable; public interface StatefulNN extends Snapshottable { MLPState getState(); @Override default Snapshot getSnapshot() { return new Snapshot(getState(), getClass()); } }
1,159
34.151515
86
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/CentralizedSensing.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.core.sensors.Sensor; import it.units.erallab.hmsrobots.core.snapshots.ScopedReadings; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.core.snapshots.Snapshottable; import it.units.erallab.hmsrobots.core.snapshots.StackedScopedReadings; import it.units.erallab.hmsrobots.util.Domain; import it.units.erallab.hmsrobots.util.Grid; import org.apache.commons.lang3.ArrayUtils; import java.util.Collection; import java.util.Objects; /** * @author eric */ public class CentralizedSensing extends AbstractController<SensingVoxel> implements Snapshottable { @JsonProperty private final int nOfInputs; @JsonProperty private final int nOfOutputs; @JsonProperty @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class") private TimedRealFunction function; private double[] inputs; private double[] outputs; private Domain[] inputDomains; private final Domain[] outputDomains; public CentralizedSensing( @JsonProperty("nOfInputs") int nOfInputs, @JsonProperty("nOfOutputs") int nOfOutputs, @JsonProperty("function") TimedRealFunction function ) { this.nOfInputs = nOfInputs; this.nOfOutputs = nOfOutputs; outputDomains = Domain.of(-1d, 1d, nOfOutputs); setFunction(function); } public CentralizedSensing(Grid<? extends SensingVoxel> voxels) { this(voxels, RealFunction.build(in -> new double[nOfOutputs(voxels)], nOfInputs(voxels), nOfOutputs(voxels))); } public CentralizedSensing(Grid<? extends SensingVoxel> voxels, TimedRealFunction function) { this(nOfInputs(voxels), nOfOutputs(voxels), function); } public static int nOfInputs(Grid<? extends SensingVoxel> voxels) { return voxels.values().stream() .filter(Objects::nonNull) .mapToInt(v -> v.getSensors().stream() .mapToInt(s -> s.getDomains().length) .sum()) .sum(); } public static int nOfOutputs(Grid<? extends SensingVoxel> voxels) { return (int) voxels.values().stream() .filter(Objects::nonNull) .count(); } public int nOfInputs() { return nOfInputs; } public int nOfOutputs() { return nOfOutputs; } public TimedRealFunction getFunction() { return function; } public void setFunction(TimedRealFunction function) { if (function.getInputDimension() != nOfInputs || function.getOutputDimension() != nOfOutputs) { throw new IllegalArgumentException(String.format( "Wrong dimension of input or output in provided function: R^%d->R^%d expected, R^%d->R^%d found", nOfInputs, nOfOutputs, function.getInputDimension(), function.getOutputDimension() )); } this.function = function; } @Override public Grid<Double> computeControlSignals(double t, Grid<? extends SensingVoxel> voxels) { //collect inputs inputs = voxels.values().stream() .filter(Objects::nonNull) .map(SensingVoxel::getSensorReadings) .reduce(ArrayUtils::addAll) .orElse(new double[nOfInputs]); inputDomains = voxels.values().stream() .filter(Objects::nonNull) .map(SensingVoxel::getSensors) .flatMap(Collection::stream) .map(Sensor::getDomains) .reduce(ArrayUtils::addAll) .orElse(Domain.of(-1d, 1d, nOfInputs)); //compute outputs outputs = function != null ? function.apply(t, inputs) : new double[nOfOutputs]; //apply inputs Grid<Double> controlSignals = Grid.create(voxels.getW(), voxels.getH()); int c = 0; for (Grid.Entry<? extends SensingVoxel> entry : voxels) { if (entry.getValue() != null) { if (c < outputs.length) { controlSignals.set(entry.getX(), entry.getY(), outputs[c]); c = c + 1; } } } return controlSignals; } @Override public void reset() { if (function instanceof Resettable) { ((Resettable) function).reset(); } } @Override public String toString() { return "CentralizedSensing{" + "function=" + function + '}'; } @Override public Snapshot getSnapshot() { Snapshot snapshot = new Snapshot( new StackedScopedReadings( new ScopedReadings(inputs, inputDomains), new ScopedReadings(outputs, outputDomains) ), getClass() ); if (function instanceof Snapshottable) { snapshot.getChildren().add(((Snapshottable) function).getSnapshot()); } return snapshot; } }
5,508
31.216374
114
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/RealFunction.java
package it.units.erallab.hmsrobots.core.controllers; import it.units.erallab.hmsrobots.util.SerializableFunction; /** * @author eric on 2021/03/09 for 2dhmsr */ public interface RealFunction extends TimedRealFunction { double[] apply(double[] input); @Override default double[] apply(double t, double[] input) { return apply(input); } static RealFunction build(SerializableFunction<double[], double[]> function, int inputDimension, int outputDimension) { return new RealFunction() { @Override public double[] apply(double[] input) { return function.apply(input); } @Override public int getInputDimension() { return inputDimension; } @Override public int getOutputDimension() { return outputDimension; } }; } }
821
21.833333
121
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/SelfOrganizing.java
/* * Copyright (C) 2021 Federico Pigozzi <pigozzife@gmail.com> (as Federico Pigozzi <pigozzife@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.*; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.util.Grid; import org.apache.commons.math3.util.Pair; import java.io.Serializable; import java.util.*; import java.util.stream.Collectors; /** * @author federico */ public class SelfOrganizing implements Controller<SensingVoxel> { public static class Edge implements Serializable { @JsonProperty private final int source; @JsonProperty private final int target; @JsonProperty private double weight; @JsonProperty private double bias; @JsonCreator public Edge(@JsonProperty("source") int s, @JsonProperty("target") int t, @JsonProperty("weight") double w, @JsonProperty("bias") double b) { source = s; target = t; weight = w; bias = b; } public double[] getParams() { return new double[]{weight, bias}; } public void setParams(List<Double> params) { weight = params.get(0); bias = params.get(1); } public int getSource() { return source; } public int getTarget() { return target; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Edge edge = (Edge) o; return source == edge.source && target == edge.target; } @Override public int hashCode() { return Objects.hash(source, target); } @Override public String toString() { return "Edge{" + String.join(",", String.valueOf(source), String.valueOf(target)) + "}"; } } @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) @JsonSubTypes({ @JsonSubTypes.Type(value = ActuatorNeuron.class, name = "actuator"), @JsonSubTypes.Type(value = SensingNeuron.class, name = "sensing"), @JsonSubTypes.Type(value = HiddenNeuron.class, name = "hidden") }) public abstract static class Neuron implements Serializable { @JsonProperty protected final int index; @JsonProperty protected final int x; @JsonProperty protected final int y; @JsonProperty protected final MultiLayerPerceptron.ActivationFunction function; @JsonProperty protected final List<Edge> ingoingEdges; protected transient double message; protected transient double cache; @JsonCreator public Neuron(@JsonProperty("index") int idx, @JsonProperty("x") int coord1, @JsonProperty("y") int coord2, @JsonProperty("function") MultiLayerPerceptron.ActivationFunction a) { index = idx; x = coord1; y = coord2; function = a; ingoingEdges = new ArrayList<>(); resetState(); } public abstract void forward(Grid<? extends SensingVoxel> voxels, SelfOrganizing controller); public abstract boolean isActuator(); public abstract boolean isSensing(); public boolean isHidden() { return !(isSensing() || isActuator()); } protected double propagate(Edge e, SelfOrganizing controller) { double[] params = e.getParams(); return controller.getNeuronsMap().get(e.getSource()).send() * params[0] + params[1]; } public void advance() { cache = message; } public double send() { return cache; } public boolean hasInNeighbour(int other) { return ingoingEdges.stream().mapToInt(Edge::getSource).anyMatch(i -> i == other); } public MultiLayerPerceptron.ActivationFunction getActivation() { return function; } public void addIngoingEdge(Edge e) { ingoingEdges.add(e); } public int getIndex() { return index; } public List<Edge> getIngoingEdges() { return ingoingEdges; } public int getX() { return x; } public int getY() { return y; } public void resetState() { message = 0.0; cache = 0.0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Neuron neuron = (Neuron) o; return index == neuron.index; } @Override public int hashCode() { return Objects.hash(index); } @Override public String toString() { return "Neuron." + function.toString().toLowerCase() + "{" + String.join(",", String.valueOf(index), String.valueOf(x), String.valueOf(y), "[" + String.join(",", ingoingEdges.stream().map(Edge::toString).toArray(String[]::new)) + "]") + "}"; } } public static class ActuatorNeuron extends Neuron { @JsonCreator public ActuatorNeuron(@JsonProperty("index") int idx, @JsonProperty("x") int coord1, @JsonProperty("y") int coord2) { super(idx, coord1, coord2, MultiLayerPerceptron.ActivationFunction.TANH); } @Override public void forward(Grid<? extends SensingVoxel> voxels, SelfOrganizing controller) { SensingVoxel voxel = voxels.get(x, y); message = function.apply(ingoingEdges.stream().mapToDouble(e -> propagate(e, controller)).sum()); voxel.applyForce(message); } @Override public boolean isActuator() { return true; } @Override public boolean isSensing() { return false; } @Override public String toString() { return super.toString().replace("Neuron", "Neuron.Actuator."); } } public static class SensingNeuron extends Neuron { @JsonProperty private final int numSensor; @JsonCreator public SensingNeuron(@JsonProperty("index") int idx, @JsonProperty("x") int coord1, @JsonProperty("y") int coord2, @JsonProperty("numSensor") int s) { super(idx, coord1, coord2, MultiLayerPerceptron.ActivationFunction.TANH); numSensor = s; } public int getNumSensor() { return numSensor; } @Override public void forward(Grid<? extends SensingVoxel> voxels, SelfOrganizing controller) { SensingVoxel voxel = voxels.get(x, y); message = function.apply(voxel.getSensors().stream().flatMapToDouble(x -> Arrays.stream(x.getReadings())) .toArray()[numSensor]); } @Override public boolean isSensing() { return true; } @Override public boolean isActuator() { return false; } @Override public String toString() { return super.toString().replace("Neuron", "Neuron.Sensing."); } } public static class HiddenNeuron extends Neuron { @JsonCreator public HiddenNeuron(@JsonProperty("index") int idx, @JsonProperty("x") int coord1, @JsonProperty("y") int coord2, @JsonProperty("function") MultiLayerPerceptron.ActivationFunction a) { super(idx, coord1, coord2, a); } @Override public void forward(Grid<? extends SensingVoxel> voxels, SelfOrganizing controller) { message = function.apply(ingoingEdges.stream().mapToDouble(e -> propagate(e, controller)).sum()); } @Override public boolean isActuator() { return false; } @Override public boolean isSensing() { return false; } @Override public String toString() { return super.toString().replace("Neuron", "Neuron.Hidden."); } } @JsonProperty private final Map<Integer, Neuron> neurons; @JsonCreator public SelfOrganizing(@JsonProperty("neurons") Map<Integer, Neuron> neurons) { this.neurons = new HashMap<>(); for (Neuron entry : neurons.values()) { copyNeuron(entry); } } public SelfOrganizing(SelfOrganizing other) { this(other.getNeuronsMap()); } public Map<Integer, Neuron> getNeuronsMap() { return neurons; } public List<Neuron> getNeurons() { return neurons.values().stream().collect(Collectors.toUnmodifiableList()); } public List<Edge> getEdges() { return neurons.values().stream().flatMap(n -> n.getIngoingEdges().stream()).collect(Collectors.toUnmodifiableList()); } public void copyNeuron(Neuron neuron) { int idx = neuron.getIndex(); Neuron newComer; if (neuron instanceof SensingNeuron) { newComer = new SensingNeuron(idx, neuron.getX(), neuron.getY(), ((SensingNeuron) neuron).getNumSensor()); } else if (neuron instanceof ActuatorNeuron) { newComer = new ActuatorNeuron(idx, neuron.getX(), neuron.getY()); } else if (neuron instanceof HiddenNeuron) { newComer = new HiddenNeuron(idx, neuron.getX(), neuron.getY(), neuron.getActivation()); if (neurons.containsKey(idx)) { throw new IllegalArgumentException(String.format("Inserting already-present neuron: %d", idx)); } } else { throw new RuntimeException(String.format("Unknown Neuron type: %s", neuron.getClass())); } neurons.put(idx, newComer); for (Edge edge : neuron.getIngoingEdges()) { addEdge(edge.getSource(), edge.getTarget(), edge.getParams()[0], edge.getParams()[1]); } } public Neuron addHiddenNeuron(MultiLayerPerceptron.ActivationFunction a, int x, int y) { int idx = getFirstAvailableIndex(); Neuron newNeuron = new HiddenNeuron(idx, x, y, a); neurons.put(idx, newNeuron); return newNeuron; } public Neuron addActuatorNeuron(int x, int y) { int idx = getFirstAvailableIndex(); Neuron newNeuron = new ActuatorNeuron(idx, x, y); neurons.put(idx, newNeuron); return newNeuron; } public Neuron addSensingNeuron(int x, int y, int s) { int idx = getFirstAvailableIndex(); Neuron newNeuron = new SensingNeuron(idx, x, y, s); neurons.put(idx, newNeuron); return newNeuron; } private int getFirstAvailableIndex() { for (int i = 0; i < this.neurons.size(); ++i) { if (!neurons.containsKey(i)) { return i; } } return neurons.size(); } public void removeNeuron(Neuron neuron) { for (Edge edge : getEdges()) { if (edge.getSource() == neuron.getIndex() || edge.getTarget() == neuron.getIndex()) { removeEdge(edge); } } neurons.remove(neuron.getIndex()); } public void addEdge(int source, int dest, double weight, double bias) { if (neurons.get(dest).hasInNeighbour(source)) { throw new RuntimeException(String.format("Adding already-present edge: [%d,%d]", source, dest)); } Edge edge = new Edge(source, dest, weight, bias); neurons.get(dest).addIngoingEdge(edge); } public void removeEdge(Edge edge) { removeEdge(edge.getSource(), edge.getTarget()); } public void removeEdge(int source, int target) { neurons.get(target).getIngoingEdges().removeIf(e -> e.getSource() == source); } public List<Edge> getOutgoingEdges(Neuron neuron) { return getOutgoingEdges(neuron.getIndex()); } public List<Edge> getOutgoingEdges(int idx) { List<Edge> out = new ArrayList<>(); for (Edge edge : getEdges()) { if (edge.getSource() == idx) { out.add(edge); } } return out; } public Pair[] getValidAndDistinctCoordinates() { return getNeurons().stream().map(n -> new Pair<>(n.getX(), n.getY())).distinct().toArray(Pair[]::new); } @Override public void control(double t, Grid<? extends SensingVoxel> voxels) { getNeurons().forEach(n -> n.forward(voxels, this)); getNeurons().forEach(Neuron::advance); } @Override public void reset() { getNeurons().forEach(Neuron::resetState); } @Override public String toString() { return "SelfOrganizing{" + neurons.values().stream().map(Neuron::toString).collect(Collectors.joining("-")) + "}"; } }
12,672
27.099778
121
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/Controller.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import com.fasterxml.jackson.annotation.JsonTypeInfo; import it.units.erallab.hmsrobots.core.objects.ControllableVoxel; import it.units.erallab.hmsrobots.util.Grid; import java.io.Serializable; /** * @author eric */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class") public interface Controller<V extends ControllableVoxel> extends Resettable, Serializable { void control(double t, Grid<? extends V> voxels); static <K extends ControllableVoxel> Controller<K> empty() { return new Controller<>() { @Override public void control(double t, Grid<? extends K> voxels) { } @Override public void reset() { } }; } }
1,490
31.413043
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/Resettable.java
package it.units.erallab.hmsrobots.core.controllers; /** * @author eric on 2021/02/15 for 2dhmsr */ public interface Resettable { void reset(); }
151
15.888889
52
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/PosesController.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.controllers; import it.units.erallab.hmsrobots.core.objects.ControllableVoxel; import it.units.erallab.hmsrobots.util.Grid; import java.util.List; import java.util.Set; /** * @author "Eric Medvet" on 2021/12/03 for 2dhmsr */ public class PosesController extends AbstractController<ControllableVoxel> { private final double stepT; private final List<Set<Grid.Key>> poses; public PosesController(double stepT, List<Set<Grid.Key>> poses) { this.stepT = stepT; this.poses = poses; } @Override public Grid<Double> computeControlSignals(double t, Grid<? extends ControllableVoxel> voxels) { int poseIndex = (int) Math.round(t / stepT) % poses.size(); Grid<Double> values = Grid.create(voxels, v -> -1d); for (Grid.Key key : poses.get(poseIndex)) { if (key.getX() >= 0 && key.getX() < values.getW() && key.getY() >= 0 && key.getY() < values.getH()) { values.set(key.getX(), key.getY(), 1d); } } return values; } @Override public void reset() { } }
1,814
31.410714
107
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedMultilayerSpikingNetwork.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import it.units.erallab.hmsrobots.core.controllers.MultiLayerPerceptron; import it.units.erallab.hmsrobots.core.controllers.StatefulNN; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedMovingAverageSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.core.snapshots.SNNState; import it.units.erallab.hmsrobots.util.Parametrized; import it.units.erallab.hmsrobots.util.SerializationUtils; import java.util.*; import java.util.function.BiFunction; import java.util.stream.IntStream; import java.util.stream.Stream; @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class") public class QuantizedMultilayerSpikingNetwork implements QuantizedMultivariateSpikingFunction, Parametrized, StatefulNN { @JsonProperty protected final QuantizedSpikingFunction[][] neurons; // layer + position in the layer @JsonProperty protected final double[][][] weights; // layer + start neuron + end neuron protected double previousApplicationTime = 0d; protected double timeWindowSize; protected boolean spikesTracker = false; protected final List<Double>[][] spikes; protected final int[][][] currentSpikes; protected boolean weightsTracker = false; protected final Map<Double, double[]> weightsInTime; @JsonProperty private final QuantizedSpikeTrainToValueConverter[][] snapshotConverters; @SuppressWarnings("unchecked") @JsonCreator public QuantizedMultilayerSpikingNetwork( @JsonProperty("neurons") QuantizedSpikingFunction[][] neurons, @JsonProperty("weights") double[][][] weights, @JsonProperty("snapshotConverters") QuantizedSpikeTrainToValueConverter[][] snapshotConverters) { this.neurons = neurons; this.weights = weights; this.snapshotConverters = snapshotConverters; if (flat(weights, neurons).length != countWeights(neurons)) { throw new IllegalArgumentException(String.format( "Wrong number of weights: %d expected, %d found", countWeights(neurons), flat(weights, neurons).length )); } spikes = new List[neurons.length][]; currentSpikes = new int[neurons.length][][]; for (int i = 0; i < neurons.length; i++) { currentSpikes[i] = new int[neurons[i].length][]; spikes[i] = new List[neurons[i].length]; for (int j = 0; j < spikes[i].length; j++) { spikes[i][j] = new ArrayList<>(); } } weightsInTime = new HashMap<>(); weightsInTime.put(previousApplicationTime, flat(weights, neurons)); innerReset(); } public QuantizedMultilayerSpikingNetwork(QuantizedSpikingFunction[][] neurons, double[][][] weights) { this(neurons, weights, createSnapshotConverters(neurons, new QuantizedMovingAverageSpikeTrainToValueConverter())); } public QuantizedMultilayerSpikingNetwork(QuantizedSpikingFunction[][] neurons, double[] weights, QuantizedSpikeTrainToValueConverter converter) { this(neurons, unflat(weights, neurons), createSnapshotConverters(neurons, converter)); } public QuantizedMultilayerSpikingNetwork(int nOfInput, int[] innerNeurons, int nOfOutput, double[] weights, BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder, QuantizedSpikeTrainToValueConverter converter) { this(createNeurons(MultiLayerPerceptron.countNeurons(nOfInput, innerNeurons, nOfOutput), neuronBuilder), weights, converter); } public QuantizedMultilayerSpikingNetwork(int nOfInput, int[] innerNeurons, int nOfOutput, BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder, QuantizedSpikeTrainToValueConverter converter) { this(createNeurons(MultiLayerPerceptron.countNeurons(nOfInput, innerNeurons, nOfOutput), neuronBuilder), new double[countWeights(createNeurons(MultiLayerPerceptron.countNeurons(nOfInput, innerNeurons, nOfOutput), neuronBuilder))], converter); } public QuantizedMultilayerSpikingNetwork(QuantizedSpikingFunction[][] neurons, double[] weights) { this(neurons, unflat(weights, neurons)); } public QuantizedMultilayerSpikingNetwork(int nOfInput, int[] innerNeurons, int nOfOutput, double[] weights, BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder) { this(createNeurons(MultiLayerPerceptron.countNeurons(nOfInput, innerNeurons, nOfOutput), neuronBuilder), weights); } public QuantizedMultilayerSpikingNetwork(int nOfInput, int[] innerNeurons, int nOfOutput, BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder) { this(createNeurons(MultiLayerPerceptron.countNeurons(nOfInput, innerNeurons, nOfOutput), neuronBuilder), new double[countWeights(createNeurons(MultiLayerPerceptron.countNeurons(nOfInput, innerNeurons, nOfOutput), neuronBuilder))]); } protected static QuantizedSpikeTrainToValueConverter[][] createSnapshotConverters(QuantizedSpikingFunction[][] neurons, QuantizedSpikeTrainToValueConverter converter) { QuantizedSpikeTrainToValueConverter[][] converters = new QuantizedSpikeTrainToValueConverter[neurons.length][]; IntStream.range(0, converters.length).forEach(layer -> { converters[layer] = new QuantizedSpikeTrainToValueConverter[neurons[layer].length]; IntStream.range(0, neurons[layer].length).forEach(neuron -> { converters[layer][neuron] = SerializationUtils.clone(converter); converters[layer][neuron].reset(); } ); }); return converters; } protected static QuantizedSpikingFunction[][] createNeurons(int[] neuronsPerLayer, QuantizedSpikingFunction quantizedSpikingFunction) { QuantizedSpikingFunction[][] quantizedSpikingFunctions = new QuantizedSpikingFunction[neuronsPerLayer.length][]; for (int i = 0; i < neuronsPerLayer.length; i++) { quantizedSpikingFunctions[i] = new QuantizedSpikingFunction[neuronsPerLayer[i]]; for (int j = 0; j < quantizedSpikingFunctions[i].length; j++) { quantizedSpikingFunctions[i][j] = SerializationUtils.clone(quantizedSpikingFunction, SerializationUtils.Mode.JAVA); quantizedSpikingFunctions[i][j].reset(); } } return quantizedSpikingFunctions; } protected static QuantizedSpikingFunction[][] createNeurons(int[] neuronsPerLayer, BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder) { QuantizedSpikingFunction[][] quantizedSpikingFunctions = new QuantizedSpikingFunction[neuronsPerLayer.length][]; for (int i = 0; i < neuronsPerLayer.length; i++) { quantizedSpikingFunctions[i] = new QuantizedSpikingFunction[neuronsPerLayer[i]]; for (int j = 0; j < quantizedSpikingFunctions[i].length; j++) { quantizedSpikingFunctions[i][j] = neuronBuilder.apply(i, j); } } return quantizedSpikingFunctions; } @Override public int[][] apply(double t, int[][] inputs) { timeWindowSize = t - previousApplicationTime; if (inputs.length != neurons[0].length) { throw new IllegalArgumentException(String.format("Expected input length is %d: found %d", neurons[0].length, inputs.length)); } // destination neuron, array of incoming weights double[][] incomingWeights = new double[inputs.length][inputs.length]; for (int i = 0; i < incomingWeights.length; i++) { incomingWeights[i][i] = 1; if (neurons[0][i] instanceof QuantizedIzhikevicNeuron) { incomingWeights[i][i] = 100; } } // iterating over layers for (int layerIndex = 0; layerIndex < neurons.length; layerIndex++) { QuantizedSpikingFunction[] layer = neurons[layerIndex]; for (int neuronIndex = 0; neuronIndex < layer.length; neuronIndex++) { double[] weightedInputSpikeTrain = createWeightedSpikeTrain(layerIndex == 0 ? inputs : currentSpikes[layerIndex - 1], incomingWeights[neuronIndex]); layer[neuronIndex].setSumOfIncomingWeights(Arrays.stream(incomingWeights[neuronIndex]).sum()); // for homeostasis currentSpikes[layerIndex][neuronIndex] = layer[neuronIndex].compute(weightedInputSpikeTrain, t); if (spikesTracker) { int arrayLength = currentSpikes[layerIndex][neuronIndex].length; int finalLayerIndex = layerIndex; int finalNeuronIndex = neuronIndex; Arrays.stream(currentSpikes[layerIndex][neuronIndex]).forEach(x -> spikes[finalLayerIndex][finalNeuronIndex].add(x / arrayLength * timeWindowSize + previousApplicationTime)); } } if (layerIndex == neurons.length - 1) { break; } incomingWeights = new double[neurons[layerIndex + 1].length][neurons[layerIndex].length]; for (int i = 0; i < incomingWeights.length; i++) { for (int j = 0; j < incomingWeights[0].length; j++) { incomingWeights[i][j] = weights[layerIndex][j][i]; } } } previousApplicationTime = t; return currentSpikes[currentSpikes.length - 1]; } protected double[] createWeightedSpikeTrain(int[][] inputs, double[] weights) { double[] weightedSpikeTrain = new double[inputs[0].length]; for (int time = 0; time < weightedSpikeTrain.length; time++) { for (int neuron = 0; neuron < inputs.length; neuron++) { weightedSpikeTrain[time] += weights[neuron] * inputs[neuron][time]; } } return weightedSpikeTrain; } public static int countWeights(QuantizedSpikingFunction[][] neurons) { int c = 0; for (int i = 1; i < neurons.length; i++) { c += neurons[i].length * neurons[i - 1].length; } return c; } public static int countWeights(int[] neurons) { int c = 0; for (int i = 1; i < neurons.length; i++) { c += neurons[i] * neurons[i - 1]; } return c; } public static int countWeights(int nOfInput, int[] innerNeurons, int nOfOutput) { return countWeights(MultiLayerPerceptron.countNeurons(nOfInput, innerNeurons, nOfOutput)); } // for each layer, for each neuron, list incoming weights in order public static double[] flat(double[][][] unflatWeights, QuantizedSpikingFunction[][] neurons) { double[] flatWeights = new double[countWeights(neurons)]; int c = 0; for (int i = 1; i < neurons.length; i++) { for (int j = 0; j < neurons[i].length; j++) { for (int k = 0; k < neurons[i - 1].length; k++) { flatWeights[c] = unflatWeights[i - 1][k][j]; c++; } } } return flatWeights; } public static double[][][] unflat(double[] flatWeights, QuantizedSpikingFunction[][] neurons) { double[][][] unflatWeights = new double[neurons.length - 1][][]; int c = 0; for (int i = 1; i < neurons.length; i++) { unflatWeights[i - 1] = new double[neurons[i - 1].length][neurons[i].length]; for (int j = 0; j < neurons[i].length; j++) { for (int k = 0; k < neurons[i - 1].length; k++) { unflatWeights[i - 1][k][j] = flatWeights[c]; c++; } } } return unflatWeights; } public QuantizedSpikingFunction[][] getNeurons() { return neurons; } public double[][][] getWeights() { return weights; } @Override public double[] getParams() { return flat(weights, neurons); } @Override public void setParams(double[] params) { double[][][] newWeights = unflat(params, neurons); for (int l = 0; l < newWeights.length; l++) { for (int s = 0; s < newWeights[l].length; s++) { System.arraycopy(newWeights[l][s], 0, weights[l][s], 0, newWeights[l][s].length); } } reset(); } @Override public int getInputDimension() { return neurons[0].length; } @Override public int getOutputDimension() { return neurons[neurons.length - 1].length; } public void setPlotMode(boolean plotMode) { Stream.of(neurons) .flatMap(Stream::of) .forEach(x -> x.setPlotMode(true)); } public void setSpikesTracker(boolean spikesTracker) { this.spikesTracker = spikesTracker; } public void setWeightsTracker(boolean weightsTracker) { this.weightsTracker = weightsTracker; } public List<Double>[][] getSpikes() { return spikes; } public Map<Double, double[]> getWeightsInTime() { return weightsInTime; } @Override public SNNState getState() { return new SNNState(getCurrentSpikes(), getWeights(), snapshotConverters, timeWindowSize); } public int[][][] getCurrentSpikes() { return currentSpikes; } @Override public void reset() { innerReset(); } private void innerReset() { previousApplicationTime = 0d; for (int i = 0; i < neurons.length; i++) { for (int j = 0; j < neurons[i].length; j++) { neurons[i][j].reset(); spikes[i][j].clear(); snapshotConverters[i][j].reset(); } } } }
12,993
40.120253
246
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedLIFNeuronWithHomeostasis.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.SortedMap; import java.util.TreeMap; public class QuantizedLIFNeuronWithHomeostasis extends QuantizedLIFNeuron { @JsonProperty private final double startingTheta; @JsonProperty private final double startingThresholdPotential; private double theta; private static final double THETA_INCREMENT_RATE = 0.2; private static final double THETA_DECAY_RATE = 0.01; private final SortedMap<Double, Double> thresholdValues; @JsonCreator public QuantizedLIFNeuronWithHomeostasis( @JsonProperty("restingPotential") double restingPotential, @JsonProperty("thresholdPotential") double thresholdPotential, @JsonProperty("lambdaDecay") double lambdaDecay, @JsonProperty("theta") double theta, @JsonProperty("plotMode") boolean plotMode ) { super(restingPotential, thresholdPotential, lambdaDecay, plotMode); startingTheta = theta; startingThresholdPotential = thresholdPotential; this.theta = startingTheta; thresholdValues = new TreeMap<>(); if (plotMode) { thresholdValues.put(lastInputTime, thresholdPotential); } } public QuantizedLIFNeuronWithHomeostasis(double restingPotential, double thresholdPotential, double lambdaDecay, double theta) { this(restingPotential, thresholdPotential, lambdaDecay, theta, false); } public QuantizedLIFNeuronWithHomeostasis(double restingPotential, double thresholdPotential, double lambdaDecay) { this(restingPotential, thresholdPotential, lambdaDecay, 0d, false); } public QuantizedLIFNeuronWithHomeostasis(boolean plotMode) { this(0, 1.0, 0.01, 0d, plotMode); } public QuantizedLIFNeuronWithHomeostasis() { this(false); } @Override protected void acceptWeightedSpike(double spikeTime, double weightedSpike) { double previousInputTime = lastInputTime; thresholdPotential = Math.min(startingThresholdPotential, sumOfIncomingWeights) + theta; super.acceptWeightedSpike(spikeTime, weightedSpike); if (membranePotential < thresholdPotential) { theta = theta - THETA_DECAY_RATE * (spikeTime - previousInputTime) * TO_MILLIS_MULTIPLIER * theta; } if (plotMode) { thresholdValues.put(previousInputTime, thresholdPotential); } } @Override protected void resetAfterSpike() { theta += THETA_INCREMENT_RATE; super.resetAfterSpike(); } @Override public void reset() { super.reset(); theta = startingTheta; thresholdPotential = startingThresholdPotential; } public SortedMap<Double, Double> getThresholdValues() { return thresholdValues; } }
2,779
31.705882
130
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedLIFNeuron.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class QuantizedLIFNeuron extends QuantizedSpikingNeuron { @JsonProperty private final double lambdaDecay; @JsonCreator public QuantizedLIFNeuron( @JsonProperty("restingPotential") double restingPotential, @JsonProperty("thresholdPotential") double thresholdPotential, @JsonProperty("lambdaDecay") double lambdaDecay, @JsonProperty("plotMode") boolean plotMode ) { super(restingPotential, thresholdPotential, plotMode); this.lambdaDecay = lambdaDecay; } public QuantizedLIFNeuron(double restingPotential, double thresholdPotential, double lambdaDecay){ this(restingPotential,thresholdPotential,lambdaDecay,false); } public QuantizedLIFNeuron(boolean plotMode) { this(0, 1.0, 0.01, plotMode); } public QuantizedLIFNeuron(){ this(false); } @Override protected void acceptWeightedSpike(double spikeTime, double weightedSpike) { double decay = TO_MILLIS_MULTIPLIER * (spikeTime - lastInputTime) * lambdaDecay * membranePotential; membranePotential -= decay; if (plotMode) { membranePotentialValues.put(spikeTime, membranePotential); } membranePotential += weightedSpike; if (plotMode) { membranePotentialValues.put(spikeTime + PLOTTING_TIME_STEP, membranePotential); } lastInputTime = spikeTime; } @Override protected void resetAfterSpike() { membranePotential = restingPotential; if (plotMode) { membranePotentialValues.put(lastInputTime + 2 * PLOTTING_TIME_STEP, membranePotential); } } }
1,730
29.368421
104
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedMultivariateSpikingFunction.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import it.units.erallab.hmsrobots.core.controllers.Resettable; import it.units.erallab.hmsrobots.util.SerializableFunction; import java.io.Serializable; public interface QuantizedMultivariateSpikingFunction extends Resettable, Serializable { int[][] apply(double t, int[][] inputs); int getInputDimension(); int getOutputDimension(); static QuantizedMultivariateSpikingFunction build(SerializableFunction<int[][], int[][]> function, int inputDimension, int outputDimension) { return new QuantizedMultivariateSpikingFunction() { @Override public int[][] apply(double t, int[][] inputs) { return function.apply(inputs); } @Override public int getInputDimension() { return inputDimension; } @Override public int getOutputDimension() { return outputDimension; } @Override public void reset() { } }; } }
986
23.675
143
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedIzhikevicNeuron.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.SortedMap; import java.util.TreeMap; public class QuantizedIzhikevicNeuron extends QuantizedSpikingNeuron { public enum IzhikevicParameters { REGULAR_SPIKING_PARAMS(30, 0.02, 0.2, -65, 8); private final double threshold; private final double a; private final double b; private final double c; private final double d; IzhikevicParameters(double threshold, double a, double b, double c, double d) { this.threshold = threshold; this.a = a; this.b = b; this.c = c; this.d = d; } } private static final double INPUT_MULTIPLIER = 15; private double membraneRecovery; @JsonProperty private final double a; @JsonProperty private final double b; @JsonProperty private final double c; @JsonProperty private final double d; private final SortedMap<Double, Double> membraneRecoveryValues; @JsonCreator public QuantizedIzhikevicNeuron( @JsonProperty("thresholdPotential") double thresholdPotential, @JsonProperty("a") double a, @JsonProperty("b") double b, @JsonProperty("c") double c, @JsonProperty("d") double d, @JsonProperty("plotMode") boolean plotMode ) { super(c, thresholdPotential, plotMode); this.a = a; this.b = b; this.c = c; this.d = d; membraneRecovery = b * membranePotential; membraneRecoveryValues = new TreeMap<>(); if (plotMode) { membraneRecoveryValues.put(lastInputTime, membraneRecovery); } } public QuantizedIzhikevicNeuron(double thresholdPotential, double a, double b, double c, double d) { this(thresholdPotential, a, b, c, d, false); } public QuantizedIzhikevicNeuron(IzhikevicParameters parameters, boolean plotMode) { this(parameters.threshold, parameters.a, parameters.b, parameters.c, parameters.d, plotMode); } public QuantizedIzhikevicNeuron(IzhikevicParameters parameters) { this(parameters, false); } public QuantizedIzhikevicNeuron(boolean plotMode) { this(IzhikevicParameters.REGULAR_SPIKING_PARAMS, plotMode); } public QuantizedIzhikevicNeuron() { this(false); } @Override protected void acceptWeightedSpike(double spikeTime, double weightedSpike) { double I = b + weightedSpike * INPUT_MULTIPLIER; double deltaV = TO_MILLIS_MULTIPLIER * (spikeTime - lastInputTime) * (0.04 * Math.pow(membranePotential, 2) + 5 * membranePotential + 140 - membraneRecovery + I); double deltaU = TO_MILLIS_MULTIPLIER * (spikeTime - lastInputTime) * a * (b * membranePotential - membraneRecovery); membranePotential += deltaV; //if (membranePotential < c) { // membranePotential = c; //} membraneRecovery += deltaU; if (plotMode) { membranePotentialValues.put(spikeTime, membranePotential); membraneRecoveryValues.put(spikeTime, membraneRecovery); } lastInputTime = spikeTime; } @Override protected void resetAfterSpike() { membranePotential = c; membraneRecovery += d; if (plotMode) { membranePotentialValues.put(lastInputTime + PLOTTING_TIME_STEP, membranePotential); membraneRecoveryValues.put(lastInputTime + PLOTTING_TIME_STEP, membraneRecovery); } } @Override public void reset() { super.reset(); membraneRecovery = b * membranePotential; } public SortedMap<Double, Double> getMembraneRecoveryValues() { return membraneRecoveryValues; } }
3,615
28.398374
166
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedDistributedSpikingSensing.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.controllers.AbstractController; import it.units.erallab.hmsrobots.core.controllers.DistributedSensing; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedValueToSpikeTrainConverter; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.SerializationUtils; import org.apache.commons.lang3.ArrayUtils; import java.util.Arrays; import java.util.stream.IntStream; public class QuantizedDistributedSpikingSensing extends AbstractController<SensingVoxel> { protected static final int ARRAY_SIZE = QuantizedValueToSpikeTrainConverter.ARRAY_SIZE; protected enum Dir { N(0, -1, 0), E(1, 0, 1), S(0, 1, 2), W(-1, 0, 3); final int dx; final int dy; private final int index; Dir(int dx, int dy, int index) { this.dx = dx; this.dy = dy; this.index = index; } private static Dir adjacent(Dir dir) { return switch (dir) { case N -> Dir.S; case E -> Dir.W; case S -> Dir.N; case W -> Dir.E; }; } } @JsonProperty protected final int signals; @JsonProperty private final Grid<Integer> nOfInputGrid; @JsonProperty private final Grid<Integer> nOfOutputGrid; @JsonProperty private final Grid<QuantizedMultivariateSpikingFunction> functions; @JsonProperty private final Grid<QuantizedSpikeTrainToValueConverter> outputConverters; @JsonProperty private final Grid<QuantizedValueToSpikeTrainConverter[]> inputConverters; private double previousTime = 0; protected final Grid<int[][]> lastSignalsGrid; private final Grid<int[][]> currentSignalsGrid; @JsonCreator public QuantizedDistributedSpikingSensing( @JsonProperty("signals") int signals, @JsonProperty("nOfInputGrid") Grid<Integer> nOfInputGrid, @JsonProperty("nOfOutputGrid") Grid<Integer> nOfOutputGrid, @JsonProperty("functions") Grid<QuantizedMultivariateSpikingFunction> functions, @JsonProperty("outputConverters") Grid<QuantizedSpikeTrainToValueConverter> outputConverters, @JsonProperty("inputConverters") Grid<QuantizedValueToSpikeTrainConverter[]> inputConverters ) { this.signals = signals; this.nOfInputGrid = nOfInputGrid; this.nOfOutputGrid = nOfOutputGrid; this.functions = functions; this.outputConverters = outputConverters; this.inputConverters = inputConverters; lastSignalsGrid = Grid.create(functions, f -> new int[signals * Dir.values().length][ARRAY_SIZE]); currentSignalsGrid = Grid.create(functions, f -> new int[signals * Dir.values().length][ARRAY_SIZE]); reset(); } public QuantizedDistributedSpikingSensing(Grid<? extends SensingVoxel> voxels, int signals, QuantizedSpikingFunction spikingFunction, QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter, QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter) { this( signals, Grid.create(voxels, v -> (v == null) ? 0 : DistributedSensing.nOfInputs(v, signals)), Grid.create(voxels, v -> (v == null) ? 0 : DistributedSensing.nOfOutputs(v, signals)), Grid.create( voxels, v -> (v == null) ? null : new QuantizedMultilayerSpikingNetwork(DistributedSensing.nOfInputs(v, signals), new int[]{DistributedSensing.nOfInputs(v, signals), DistributedSensing.nOfInputs(v, signals)}, DistributedSensing.nOfOutputs(v, signals), (x, y) -> spikingFunction)), Grid.create(voxels, v -> (v == null) ? null : SerializationUtils.clone(spikeTrainToValueConverter)), Grid.create(voxels, v -> (v == null) ? null : IntStream.range(0, v.getSensors().stream().mapToInt(s -> s.getDomains().length).sum()).mapToObj(i -> SerializationUtils.clone(valueToSpikeTrainConverter)).toArray(QuantizedValueToSpikeTrainConverter[]::new)) ); } public Grid<QuantizedMultivariateSpikingFunction> getFunctions() { return functions; } public void reset() { previousTime = 0; for (int x = 0; x < lastSignalsGrid.getW(); x++) { for (int y = 0; y < lastSignalsGrid.getH(); y++) { lastSignalsGrid.set(x, y, new int[signals * Dir.values().length][ARRAY_SIZE]); currentSignalsGrid.set(x, y, new int[signals * Dir.values().length][ARRAY_SIZE]); if (outputConverters.get(x, y) != null) { outputConverters.get(x, y).reset(); } if (inputConverters.get(x, y) != null) { Arrays.stream(inputConverters.get(x, y)).forEach(QuantizedValueToSpikeTrainConverter::reset); } if (functions.get(x, y) != null) { functions.get(x, y).reset(); } } } } @Override public Grid<Double> computeControlSignals(double t, Grid<? extends SensingVoxel> voxels) { Grid<Double> controlSignals = Grid.create(voxels); for (Grid.Entry<? extends SensingVoxel> entry : voxels) { if (entry.getValue() == null) { continue; } //get inputs int[][] lastSignals = getLastSignals(entry.getX(), entry.getY()); int[][] sensorValues = convertSensorReadings(entry.getValue().getSensorReadings(), inputConverters.get(entry.getX(), entry.getY()), t); int[][] inputs = ArrayUtils.addAll(lastSignals, sensorValues); //compute outputs QuantizedMultivariateSpikingFunction function = functions.get(entry.getX(), entry.getY()); int[][] outputs = function != null ? function.apply(t, inputs) : new int[nOfOutputs(entry.getX(), entry.getY())][ARRAY_SIZE]; //apply outputs double force = outputConverters.get(entry.getX(), entry.getY()).convert(outputs[0], t - previousTime); controlSignals.set(entry.getX(), entry.getY(), force); System.arraycopy(outputs, 1, currentSignalsGrid.get(entry.getX(), entry.getY()), 0, outputs.length - 1); } previousTime = t; for (Grid.Entry<? extends SensingVoxel> entry : voxels) { System.arraycopy(currentSignalsGrid.get(entry.getX(), entry.getY()), 0, lastSignalsGrid.get(entry.getX(), entry.getY()), 0, signals * Dir.values().length); } return controlSignals; } protected int[][] getLastSignals(int x, int y) { int[][] values = new int[signals * Dir.values().length][]; if (signals <= 0) { return values; } int c = 0; for (Dir dir : Dir.values()) { int adjacentX = x + dir.dx; int adjacentY = y + dir.dy; int[][] lastSignals = lastSignalsGrid.get(adjacentX, adjacentY); if (lastSignals != null) { int index = Dir.adjacent(dir).index; System.arraycopy(lastSignals, index * signals, values, c, signals); } c = c + signals; } for (int i = 0; i < values.length; i++) { if (values[i] == null) { values[i] = new int[QuantizedValueToSpikeTrainConverter.ARRAY_SIZE]; } } return values; } private int[][] convertSensorReadings(double[] sensorsReadings, QuantizedValueToSpikeTrainConverter[] valueToSpikeTrainConverters, double t) { int[][] convertedValues = new int[sensorsReadings.length][]; IntStream.range(0, sensorsReadings.length).forEach(i -> convertedValues[i] = valueToSpikeTrainConverters[i].convert(sensorsReadings[i], t - previousTime, t)); return convertedValues; } public int nOfInputs(int x, int y) { return nOfInputGrid.get(x, y); } public int nOfOutputs(int x, int y) { return nOfOutputGrid.get(x, y); } @Override public String toString() { return "DistributedSpikingSensing{" + "signals=" + signals + ", functions=" + functions + '}'; } }
7,935
39.489796
265
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedMultilayerSpikingNetworkWithConverters.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.controllers.Resettable; import it.units.erallab.hmsrobots.core.controllers.StatefulNN; import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedMovingAverageSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedUniformWithMemoryValueToSpikeTrainConverter; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedValueToSpikeTrainConverter; import it.units.erallab.hmsrobots.core.snapshots.MLPState; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.util.Parametrized; import it.units.erallab.hmsrobots.util.SerializationUtils; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.IntStream; public class QuantizedMultilayerSpikingNetworkWithConverters<N extends QuantizedMultilayerSpikingNetwork> implements TimedRealFunction, Parametrized, Resettable, StatefulNN { @JsonProperty private final N multilayerSpikingNetwork; @JsonProperty private final QuantizedValueToSpikeTrainConverter[] quantizedValueToSpikeTrainConverters; @JsonProperty private final QuantizedSpikeTrainToValueConverter[] quantizedSpikeTrainToValueConverters; private double previousApplicationTime = 0d; @JsonCreator public QuantizedMultilayerSpikingNetworkWithConverters( @JsonProperty("multilayerSpikingNetwork") N multilayerSpikingNetwork, @JsonProperty("quantizedValueToSpikeTrainConverters") QuantizedValueToSpikeTrainConverter[] quantizedValueToSpikeTrainConverter, @JsonProperty("quantizedSpikeTrainToValueConverters") QuantizedSpikeTrainToValueConverter[] quantizedSpikeTrainToValueConverter ) { this.multilayerSpikingNetwork = multilayerSpikingNetwork; this.quantizedValueToSpikeTrainConverters = quantizedValueToSpikeTrainConverter; this.quantizedSpikeTrainToValueConverters = quantizedSpikeTrainToValueConverter; reset(); } public QuantizedMultilayerSpikingNetworkWithConverters(N multilayerSpikingNetwork, QuantizedValueToSpikeTrainConverter quantizedValueToSpikeTrainConverter, QuantizedSpikeTrainToValueConverter quantizedSpikeTrainToValueConverter) { this(multilayerSpikingNetwork, createInputConverters(multilayerSpikingNetwork.getInputDimension(), quantizedValueToSpikeTrainConverter), createOutputConverters(multilayerSpikingNetwork.getOutputDimension(), quantizedSpikeTrainToValueConverter)); } public QuantizedMultilayerSpikingNetworkWithConverters(N multilayerSpikingNetwork) { this(multilayerSpikingNetwork, createInputConverters(multilayerSpikingNetwork.getInputDimension(), new QuantizedUniformWithMemoryValueToSpikeTrainConverter()), createOutputConverters(multilayerSpikingNetwork.getOutputDimension(), new QuantizedMovingAverageSpikeTrainToValueConverter())); } @Override public double[] apply(final double t, double[] input) { double deltaT = t - previousApplicationTime; int[][] inputSpikes = new int[input.length][]; IntStream.range(0, input.length).forEach(i -> inputSpikes[i] = quantizedValueToSpikeTrainConverters[i].convert(input[i], deltaT, t)); int[][] outputSpikes = multilayerSpikingNetwork.apply(t, inputSpikes); double[] output = new double[outputSpikes.length]; IntStream.range(0, outputSpikes.length).forEach(i -> output[i] = quantizedSpikeTrainToValueConverters[i].convert(outputSpikes[i], deltaT)); previousApplicationTime = t; return output; } @Override public int getInputDimension() { return multilayerSpikingNetwork.getInputDimension(); } @Override public int getOutputDimension() { return multilayerSpikingNetwork.getOutputDimension(); } public QuantizedMultilayerSpikingNetwork getMultilayerSpikingNetwork() { return multilayerSpikingNetwork; } protected static QuantizedValueToSpikeTrainConverter[] createInputConverters(int nOfInputs, QuantizedValueToSpikeTrainConverter quantizedValueToSpikeTrainConverter) { QuantizedValueToSpikeTrainConverter[] quantizedValueToSpikeTrainConverters = new QuantizedValueToSpikeTrainConverter[nOfInputs]; IntStream.range(0, nOfInputs).forEach(i -> { quantizedValueToSpikeTrainConverters[i] = SerializationUtils.clone(quantizedValueToSpikeTrainConverter); quantizedValueToSpikeTrainConverters[i].reset(); }); return quantizedValueToSpikeTrainConverters; } protected static QuantizedSpikeTrainToValueConverter[] createOutputConverters(int nOfOutputs, QuantizedSpikeTrainToValueConverter quantizedSpikeTrainToValueConverter) { QuantizedSpikeTrainToValueConverter[] quantizedSpikeTrainToValueConverters = new QuantizedSpikeTrainToValueConverter[nOfOutputs]; IntStream.range(0, nOfOutputs).forEach(i -> { quantizedSpikeTrainToValueConverters[i] = SerializationUtils.clone(quantizedSpikeTrainToValueConverter); quantizedSpikeTrainToValueConverters[i].reset(); }); return quantizedSpikeTrainToValueConverters; } @Override public double[] getParams() { return multilayerSpikingNetwork.getParams(); } @Override public void setParams(double[] params) { multilayerSpikingNetwork.setParams(params); reset(); } public void setPlotMode(boolean plotMode) { multilayerSpikingNetwork.setPlotMode(plotMode); } public void setSpikesTracker(boolean spikesTracker) { multilayerSpikingNetwork.setSpikesTracker(spikesTracker); } public List<Double>[][] getSpikes() { return multilayerSpikingNetwork.getSpikes(); } public void setWeightsTracker(boolean weightsTracker) { multilayerSpikingNetwork.setWeightsTracker(weightsTracker); } public Map<Double, double[]> getWeightsInTime() { return multilayerSpikingNetwork.getWeightsInTime(); } @Override public MLPState getState() { return multilayerSpikingNetwork.getState(); } @Override public Snapshot getSnapshot() { return multilayerSpikingNetwork.getSnapshot(); } @Override public void reset() { multilayerSpikingNetwork.reset(); previousApplicationTime = 0d; Arrays.stream(quantizedSpikeTrainToValueConverters).forEach(QuantizedSpikeTrainToValueConverter::reset); Arrays.stream(quantizedValueToSpikeTrainConverters).forEach(QuantizedValueToSpikeTrainConverter::reset); } public N getSNN() { return multilayerSpikingNetwork; } }
6,788
42.242038
232
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedSpikingNeuron.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.SortedMap; import java.util.TreeMap; import java.util.stream.IntStream; public abstract class QuantizedSpikingNeuron implements QuantizedSpikingFunction { protected static final double TO_MILLIS_MULTIPLIER = 1000; @JsonProperty protected final double restingPotential; @JsonProperty protected double thresholdPotential; protected double membranePotential; protected double lastInputTime = 0; private double lastEvaluatedTime = 0; protected double sumOfIncomingWeights = 0; @JsonProperty protected boolean plotMode; protected final SortedMap<Double, Double> membranePotentialValues; protected final SortedMap<Double, Double> inputSpikesValues; protected static final double PLOTTING_TIME_STEP = 0.000000000001; @JsonCreator public QuantizedSpikingNeuron( @JsonProperty("restingPotential") double restingPotential, @JsonProperty("thresholdPotential") double thresholdPotential, @JsonProperty("plotMode") boolean plotMode ) { this.restingPotential = restingPotential; this.thresholdPotential = thresholdPotential; this.plotMode = plotMode; membranePotential = restingPotential; membranePotentialValues = new TreeMap<>(); inputSpikesValues = new TreeMap<>(); if (plotMode) { membranePotentialValues.put(lastInputTime, membranePotential); } } public QuantizedSpikingNeuron(double restingPotential, double thresholdPotential) { this(restingPotential, thresholdPotential, false); } @Override public int[] compute(double[] weightedSpikes, double t) { int[] spikes = new int[weightedSpikes.length]; double timeWindowSize = t - lastEvaluatedTime; if (timeWindowSize == 0) { return spikes; } IntStream.range(0, weightedSpikes.length).forEach(spikeTime -> { double absoluteSpikeTime = spikeTime * timeWindowSize / (double) weightedSpikes.length + lastEvaluatedTime; double weightedSpike = weightedSpikes[spikeTime]; if (plotMode && weightedSpike != 0) { inputSpikesValues.put(absoluteSpikeTime, weightedSpike); } acceptWeightedSpike(absoluteSpikeTime, weightedSpike); if (membranePotential >= thresholdPotential) { spikes[spikeTime] = 1; resetAfterSpike(); } } ); lastEvaluatedTime = t; return spikes; } protected abstract void acceptWeightedSpike(double spikeTime, double weightedSpike); protected abstract void resetAfterSpike(); public SortedMap<Double, Double> getMembranePotentialValues() { return membranePotentialValues; } public SortedMap<Double, Double> getInputSpikesValues() { return inputSpikesValues; } public double getRestingPotential() { return restingPotential; } public double getThresholdPotential() { return thresholdPotential; } public double getMembranePotential() { return membranePotential; } public double getLastEvaluatedTime() { return lastEvaluatedTime; } @Override public void setPlotMode(boolean plotMode) { this.plotMode = plotMode; reset(); } @Override public void setSumOfIncomingWeights(double sumOfIncomingWeights) { this.sumOfIncomingWeights = sumOfIncomingWeights; } @Override public void reset() { membranePotential = restingPotential; lastEvaluatedTime = 0; lastInputTime = 0; } }
3,567
28.487603
117
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedDistributedSpikingSensingNonDirectional.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.controllers.DistributedSensingNonDirectional; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedValueToSpikeTrainConverter; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.SerializationUtils; import java.util.stream.IntStream; public class QuantizedDistributedSpikingSensingNonDirectional extends QuantizedDistributedSpikingSensing { @JsonCreator public QuantizedDistributedSpikingSensingNonDirectional( @JsonProperty("signals") int signals, @JsonProperty("nOfInputGrid") Grid<Integer> nOfInputGrid, @JsonProperty("nOfOutputGrid") Grid<Integer> nOfOutputGrid, @JsonProperty("functions") Grid<QuantizedMultivariateSpikingFunction> functions, @JsonProperty("outputConverters") Grid<QuantizedSpikeTrainToValueConverter> outputConverters, @JsonProperty("inputConverters") Grid<QuantizedValueToSpikeTrainConverter[]> inputConverters ) { super(signals,nOfInputGrid,nOfOutputGrid,functions,outputConverters,inputConverters); } public QuantizedDistributedSpikingSensingNonDirectional(Grid<? extends SensingVoxel> voxels, int stateSize, QuantizedSpikingFunction spikingFunction, QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter, QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter) { this( stateSize, Grid.create(voxels, v -> (v == null) ? 0 : DistributedSensingNonDirectional.nOfInputs(v, stateSize)), Grid.create(voxels, v -> (v == null) ? 0 : DistributedSensingNonDirectional.nOfOutputs(v, stateSize)), Grid.create( voxels, v -> (v == null) ? null : new QuantizedMultilayerSpikingNetwork(DistributedSensingNonDirectional.nOfInputs(v, stateSize), new int[]{DistributedSensingNonDirectional.nOfInputs(v, stateSize), DistributedSensingNonDirectional.nOfInputs(v, stateSize)}, DistributedSensingNonDirectional.nOfOutputs(v, stateSize), (x, y) -> spikingFunction)), Grid.create(voxels, v -> (v == null) ? null : SerializationUtils.clone(spikeTrainToValueConverter)), Grid.create(voxels, v -> (v == null) ? null : IntStream.range(0, v.getSensors().stream().mapToInt(s -> s.getDomains().length).sum()).mapToObj(i -> SerializationUtils.clone(valueToSpikeTrainConverter)).toArray(QuantizedValueToSpikeTrainConverter[]::new)) ); } @Override protected int[][] getLastSignals(int x, int y) { int[][] values = new int[signals * Dir.values().length][]; if (signals <= 0) { return values; } int c = 0; for (Dir dir : Dir.values()) { int adjacentX = x + dir.dx; int adjacentY = y + dir.dy; int[][] lastSignals = lastSignalsGrid.get(adjacentX, adjacentY); if (lastSignals != null) { System.arraycopy(lastSignals, 0, values, c, signals); } c = c + signals; } for (int i = 0; i < values.length; i++) { if (values[i] == null) { values[i] = new int[QuantizedValueToSpikeTrainConverter.ARRAY_SIZE]; } } return values; } @Override public String toString() { return super.toString().replace("DistributedSpikingSensing", "DistributedSpikingSensingNonDirectional"); } }
3,597
48.287671
281
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/QuantizedSpikingFunction.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr; import com.fasterxml.jackson.annotation.JsonTypeInfo; import it.units.erallab.hmsrobots.core.controllers.Resettable; import java.io.Serializable; @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, property="@class") public interface QuantizedSpikingFunction extends Resettable, Serializable { int[] compute(double[] weightedSpikes, double time); void setSumOfIncomingWeights(double sumOfIncomingWeights); void setPlotMode(boolean plotMode); }
514
27.611111
76
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/converters/stv/QuantizedSpikeTrainToValueConverter.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv; import com.fasterxml.jackson.annotation.JsonTypeInfo; import it.units.erallab.hmsrobots.core.controllers.Resettable; import java.io.Serializable; @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, property="@class") public interface QuantizedSpikeTrainToValueConverter extends Serializable, Resettable { double LOWER_BOUND = -1; double UPPER_BOUND = 1; double DEFAULT_FREQUENCY = 50; double convert(int[] spikeTrain, double timeWindowSize); void setFrequency(double frequency); @Override default void reset() { } default double normalizeValue(double value) { value = value * 2 - 1; return Math.max(Math.min(UPPER_BOUND, value), LOWER_BOUND); } }
750
24.896552
87
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/converters/stv/QuantizedAverageFrequencySpikeTrainToValueConverter.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Arrays; public class QuantizedAverageFrequencySpikeTrainToValueConverter implements QuantizedSpikeTrainToValueConverter { @JsonProperty private double frequency; // hertz @JsonCreator public QuantizedAverageFrequencySpikeTrainToValueConverter( @JsonProperty("frequency") double frequency ) { this.frequency = frequency; } public QuantizedAverageFrequencySpikeTrainToValueConverter() { this(DEFAULT_FREQUENCY); } @Override public void setFrequency(double frequency) { this.frequency = frequency; } @Override public double convert(int[] spikeTrain, double timeWindowSize) { return convert(Arrays.stream(spikeTrain).sum(), timeWindowSize); } protected double convert(int numberOfSpikes, double timeWindowSize) { if (timeWindowSize == 0) { return normalizeValue(0); } return normalizeValue(numberOfSpikes / timeWindowSize / frequency); } }
1,123
25.761905
113
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/converters/stv/QuantizedMovingAverageSpikeTrainToValueConverter.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Arrays; import java.util.stream.IntStream; public class QuantizedMovingAverageSpikeTrainToValueConverter extends QuantizedAverageFrequencySpikeTrainToValueConverter { private static final int DEFAULT_NUMBER_OF_WINDOWS = 10; @JsonProperty int numberOfWindows; private final double[] windowSizes; private final int[] spikesPerWindow; private int currentPosition = 0; @JsonCreator public QuantizedMovingAverageSpikeTrainToValueConverter( @JsonProperty("frequency") double frequency, @JsonProperty("numberOfWindows") int numberOfWindows ) { super(frequency); windowSizes = new double[numberOfWindows]; spikesPerWindow = new int[numberOfWindows]; this.numberOfWindows = numberOfWindows; } public QuantizedMovingAverageSpikeTrainToValueConverter(int numberOfWindows) { this(DEFAULT_FREQUENCY, numberOfWindows); } public QuantizedMovingAverageSpikeTrainToValueConverter(double frequency) { this(frequency, DEFAULT_NUMBER_OF_WINDOWS); } public QuantizedMovingAverageSpikeTrainToValueConverter() { this(DEFAULT_FREQUENCY, DEFAULT_NUMBER_OF_WINDOWS); } @Override public double convert(int[] spikeTrain, double timeWindowSize) { windowSizes[currentPosition] = timeWindowSize; spikesPerWindow[currentPosition] = Arrays.stream(spikeTrain).sum(); currentPosition = (currentPosition == (windowSizes.length - 1)) ? 0 : (currentPosition + 1); int totalNumberOfSpikes = 0; double totalWindowSize = 0; for (int i = 0; i < windowSizes.length; i++) { if (windowSizes[i] > 0) { totalWindowSize += windowSizes[i]; totalNumberOfSpikes += spikesPerWindow[i]; } } return convert(totalNumberOfSpikes, totalWindowSize); } @Override public void reset() { IntStream.range(0, windowSizes.length).forEach(i -> { windowSizes[i] = 0; spikesPerWindow[i] = 0; }); currentPosition = 0; } }
2,143
30.072464
123
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/converters/vts/QuantizedUniformWithMemoryValueToSpikeTrainConverter.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class QuantizedUniformWithMemoryValueToSpikeTrainConverter extends QuantizedUniformValueToSpikeTrainConverter { private double lastSpikeTime = 0; @JsonCreator public QuantizedUniformWithMemoryValueToSpikeTrainConverter( @JsonProperty("frequency") double frequency ) { super(frequency); } public QuantizedUniformWithMemoryValueToSpikeTrainConverter() { } @Override public int[] convert(double value, double timeWindowSize, double timeWindowEnd) { value = clipInputValue(value); int[] spikes = new int[ARRAY_SIZE]; if (value == 0) { return spikes; } double timeWindowStart = timeWindowEnd - timeWindowSize; double deltaT = computeDeltaT(value); for (double t = lastSpikeTime; t < timeWindowEnd; t += deltaT) { if (t >= timeWindowStart) { spikes[(int)Math.floor(((t - timeWindowStart) / timeWindowSize) * ARRAY_SIZE)] += 1; lastSpikeTime = t; } } return spikes; } @Override public void reset() { lastSpikeTime = 0; } }
1,228
27.581395
118
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/converters/vts/QuantizedUniformValueToSpikeTrainConverter.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class QuantizedUniformValueToSpikeTrainConverter implements QuantizedValueToSpikeTrainConverter { @JsonProperty protected double frequency; // hertz @JsonProperty protected double minFrequency = MIN_FREQUENCY; @JsonCreator public QuantizedUniformValueToSpikeTrainConverter( @JsonProperty("frequency") double frequency ) { this.frequency = frequency; } public QuantizedUniformValueToSpikeTrainConverter() { this(DEFAULT_FREQUENCY); } @Override public void setFrequency(double frequency) { this.frequency = frequency; } @Override public int[] convert(double value, double timeWindowSize, double timeWindowEnd) { int[] spikes = new int[ARRAY_SIZE]; value = clipInputValue(value); if (value == 0) { return spikes; } double deltaT = computeDeltaT(value); for (double t = deltaT; t < timeWindowSize; t += deltaT) { spikes[(int)Math.floor(t / timeWindowSize * ARRAY_SIZE)] += 1; } return spikes; } protected double computeDeltaT(double value) { double frequencyRange = frequency - minFrequency; double frequency = value * frequencyRange + minFrequency; return 1 / frequency; } }
1,382
26.66
104
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/controllers/snndiscr/converters/vts/QuantizedValueToSpikeTrainConverter.java
package it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts; import com.fasterxml.jackson.annotation.JsonTypeInfo; import it.units.erallab.hmsrobots.core.controllers.Resettable; import java.io.Serializable; @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, property="@class") public interface QuantizedValueToSpikeTrainConverter extends Serializable, Resettable { double LOWER_BOUND = 0; double UPPER_BOUND = 1; double DEFAULT_FREQUENCY = 50; double MIN_FREQUENCY = 5; int ARRAY_SIZE = 16; int[] convert(double value, double timeWindowSize, double timeWindowEnd); void setFrequency(double frequency); @Override default void reset() { } default double clipInputValue(double value) { return Math.max(Math.min(UPPER_BOUND, value), LOWER_BOUND); } }
790
25.366667
87
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Malfunction.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import it.units.erallab.hmsrobots.core.objects.BreakableVoxel; import it.units.erallab.hmsrobots.util.Domain; /** * @author eric */ public class Malfunction extends AbstractSensor { private final static Domain[] DOMAINS = new Domain[]{ Domain.of(0d, 1d) }; public Malfunction() { super(DOMAINS); } @Override public double[] sense(double t) { if (voxel instanceof BreakableVoxel) { if (((BreakableVoxel) voxel).isBroken()) { return new double[]{1d}; } } return new double[]{0d}; } }
1,350
27.744681
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Normalization.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.util.Domain; import java.util.Collections; public class Normalization extends CompositeSensor { @JsonCreator public Normalization( @JsonProperty("sensor") Sensor sensor ) { super( Collections.nCopies(sensor.getDomains().length, Domain.of(0d, 1d)).toArray(Domain[]::new), sensor ); } @Override public double[] sense(double t) { double[] innerValues = sensor.getReadings(); double[] values = new double[innerValues.length]; for (int i = 0; i < values.length; i++) { Domain d = sensor.getDomains()[i]; values[i] = Math.min(Math.max((innerValues[i] - d.getMin()) / (d.getMax() - d.getMin()), 0d), 1d); } return values; } }
1,645
32.591837
104
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/AggregatorSensor.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.util.Domain; import java.util.TreeMap; /** * @author "Eric Medvet" on 2021/08/13 for 2dhmsr */ public abstract class AggregatorSensor extends CompositeSensor { @JsonProperty protected final double interval; protected final TreeMap<Double, double[]> readings; public AggregatorSensor(Domain[] domains, Sensor sensor, double interval) { super(domains, sensor); this.interval = interval; readings = new TreeMap<>(); reset(); } @Override public void reset() { super.reset(); readings.clear(); } @Override protected double[] sense(double t) { double[] currentReadings = sensor.getReadings(); readings.put(t, currentReadings); double t0 = readings.firstKey(); while (t0 < (t - interval)) { readings.remove(t0); t0 = readings.firstKey(); } return aggregate(t); } protected abstract double[] aggregate(double t); @Override public String toString() { return getClass().getSimpleName() + "{" + "sensor=" + sensor + ", interval=" + interval + '}'; } }
1,962
27.449275
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Trend.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.util.Domain; import java.util.Arrays; public class Trend extends AggregatorSensor { @JsonCreator public Trend( @JsonProperty("sensor") Sensor sensor, @JsonProperty("interval") double interval ) { super( Arrays.stream(sensor.getDomains()) .map(d -> Domain.of( -Math.abs(d.getMax() - d.getMin()) / interval, Math.abs(d.getMax() - d.getMin()) / interval )).toArray(Domain[]::new), sensor, interval ); reset(); } @Override protected double[] aggregate(double t) { double localInterval = readings.lastKey() - readings.firstKey(); if (localInterval == 0) { return new double[domains.length]; } double[] firsts = readings.firstEntry().getValue(); double[] lasts = readings.lastEntry().getValue(); double[] changes = new double[firsts.length]; for (int i = 0; i < changes.length; i++) { changes[i] = (lasts[i] - firsts[i]) / (localInterval); } return changes; } }
1,972
31.883333
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Average.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as eric) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class Average extends AggregatorSensor { @JsonCreator public Average( @JsonProperty("sensor") Sensor sensor, @JsonProperty("interval") double interval ) { super(sensor.getDomains(), sensor, interval); reset(); } @Override protected double[] aggregate(double t) { double[] sums = new double[readings.firstEntry().getValue().length]; for (double[] pastReadings : readings.values()) { for (int i = 0; i < sums.length; i++) { sums[i] = sums[i] + pastReadings[i]; } } for (int i = 0; i < sums.length; i++) { sums[i] = sums[i] / (double) readings.size(); } return sums; } }
1,549
31.291667
74
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Angle.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import it.units.erallab.hmsrobots.util.Domain; public class Angle extends AbstractSensor { private final static Domain[] DOMAINS = new Domain[]{ Domain.of(-Math.PI, Math.PI) }; public Angle() { super(DOMAINS); } @Override protected double[] sense(double t) { return new double[]{voxel.getAngle()}; } }
1,138
30.638889
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Crumpling.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import it.units.erallab.hmsrobots.util.Domain; public class Crumpling extends AbstractSensor { private final static double THRESHOLD = 0.2d; private final static Domain[] DOMAINS = new Domain[]{ Domain.of(0d, 1d) }; public Crumpling() { super(DOMAINS); } @Override public double[] sense(double t) { double c = 0d; for (int i = 0; i < voxel.getVertexBodies().length; i++) { for (int j = i + 1; j < voxel.getVertexBodies().length; j++) { double d = voxel.getVertexBodies()[i].getWorldCenter().distance(voxel.getVertexBodies()[j].getWorldCenter()); if (d < voxel.getSideLength() * THRESHOLD) { c = c + 1d; } } } return new double[]{2d * c / (double) (voxel.getVertexBodies().length * (voxel.getVertexBodies().length - 1))}; } }
1,622
33.531915
117
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/AppliedForce.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import it.units.erallab.hmsrobots.core.objects.ControllableVoxel; import it.units.erallab.hmsrobots.util.Domain; public class AppliedForce extends AbstractSensor { private final static Domain[] DOMAINS = new Domain[]{ Domain.of(-1d, 1d) }; public AppliedForce() { super(DOMAINS); } @Override protected double[] sense(double t) { return new double[]{((ControllableVoxel) voxel).getLastAppliedForce()}; } }
1,241
32.567568
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Touch.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import it.units.erallab.hmsrobots.core.objects.Ground; import it.units.erallab.hmsrobots.core.objects.Voxel; import it.units.erallab.hmsrobots.util.Domain; import org.dyn4j.dynamics.Body; import java.util.List; public class Touch extends AbstractSensor { private final static Domain[] DOMAINS = new Domain[]{ Domain.of(0d, 1d) }; public Touch() { super(DOMAINS); } @Override public double[] sense(double t) { return isTouching(voxel) ? new double[]{1d} : new double[]{0d}; } public static boolean isTouching(Voxel voxel) { for (Body vertexBody : voxel.getVertexBodies()) { List<Body> inContactBodies = vertexBody.getInContactBodies(false); for (Body inContactBody : inContactBodies) { Object userData = inContactBody.getUserData(); if (userData == null) { return true; } else if (userData != vertexBody.getUserData()) { return true; } } } return false; } public static boolean isTouchingGround(Voxel voxel) { for (Body vertexBody : voxel.getVertexBodies()) { List<Body> inContactBodies = vertexBody.getInContactBodies(false); for (Body inContactBody : inContactBodies) { if ((inContactBody.getUserData() != null) && (inContactBody.getUserData().equals(Ground.class))) { return true; } } } return false; } }
2,191
31.716418
106
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Constant.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.util.Domain; import java.util.Arrays; /** * @author eric on 2020/12/11 for 2dhmsr */ public class Constant extends AbstractSensor { @JsonProperty private final double[] values; @JsonCreator public Constant(@JsonProperty("values") double... values) { super(computeDomains(values)); this.values = values; } private static Domain[] computeDomains(double... values) { double max = Arrays.stream(values).max().orElse(1d); double min = Arrays.stream(values).min().orElse(0d); max = Math.max(1d, max); min = Math.min(0d, min); Domain[] domains = new Domain[values.length]; for (int i = 0; i < values.length; i++) { domains[i] = Domain.of(min, max); } return domains; } @Override public double[] sense(double t) { return values; } @Override public String toString() { return "Constant{" + "values=" + Arrays.toString(values) + '}'; } }
1,879
28.375
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Lidar.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.objects.Voxel; import it.units.erallab.hmsrobots.core.snapshots.LidarReadings; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.util.Domain; import org.apache.commons.lang3.ArrayUtils; import org.dyn4j.collision.Filter; import org.dyn4j.dynamics.RaycastResult; import org.dyn4j.geometry.Ray; import java.io.Serializable; import java.util.*; import java.util.stream.DoubleStream; public class Lidar extends AbstractSensor { public enum Side { N(Math.PI / 4d, Math.PI * 3d / 4d), E(Math.PI * -1d / 4d, Math.PI / 4d), S(Math.PI * 5d / 4d, Math.PI * 7d / 4d), W(Math.PI * 3d / 4d, Math.PI * 5d / 4d); private final double startAngle; private final double endAngle; Side(double startAngle, double endAngle) { this.startAngle = startAngle; this.endAngle = endAngle; } public double getStartAngle() { return startAngle; } public double getEndAngle() { return endAngle; } } public static class RaycastFilter implements Filter, Serializable { @Override public boolean isAllowed(Filter f) { if (f == null) return true; return !(f instanceof Voxel.ParentFilter) && !(f instanceof Voxel.RobotFilter); } } @JsonProperty private final double rayLength; @JsonProperty private final double[] rayDirections; @JsonCreator public Lidar( @JsonProperty("rayLength") double rayLength, @JsonProperty("rayDirections") double... rayDirections ) { super(Collections.nCopies(rayDirections.length, Domain.of(0, rayLength)).toArray(Domain[]::new)); this.rayLength = rayLength; this.rayDirections = rayDirections; } public Lidar(double rayLength, Map<Side, Integer> raysPerSide) { this( rayLength, Arrays.stream(raysPerSide.entrySet().stream() .map(e -> sampleRangeWithRays(e.getValue(), e.getKey().startAngle, e.getKey().endAngle)) .reduce(new double[]{}, ArrayUtils::addAll)).distinct().toArray() ); } private static double[] sampleRangeWithRays(int numberOfRays, double startAngle, double endAngle) { return numberOfRays == 1 ? new double[]{(endAngle - startAngle) / 2} : DoubleStream.iterate(startAngle, d -> d + (endAngle - startAngle) / (numberOfRays - 1)).limit(numberOfRays).toArray(); } @Override public double[] sense(double t) { List<RaycastResult> results = new ArrayList<>(); return Arrays.stream(rayDirections).map(rayDirection -> { Ray ray = new Ray(voxel.getCenter(), rayDirection + voxel.getAngle()); results.clear(); voxel.getWorld().raycast(ray, rayLength, new RaycastFilter(), true, false, false, results); return results.isEmpty() ? rayLength : results.get(0).getRaycast().getDistance(); }).toArray(); } @Override public Snapshot getSnapshot() { return new Snapshot( new LidarReadings( Arrays.copyOf(readings, readings.length), Arrays.stream(domains).map(d -> Domain.of(d.getMin(), d.getMax())).toArray(Domain[]::new), voxel.getAngle(), Arrays.copyOf(rayDirections, rayDirections.length) ), getClass() ); } @Override public String toString() { return "Lidar{" + "rayLength=" + rayLength + ", rayDirections=" + Arrays.toString(rayDirections) + '}'; } }
4,340
31.155556
126
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Noisy.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Arrays; import java.util.Random; /** * @author eric on 2020/12/18 for 2dhmsr */ public class Noisy extends CompositeSensor { @JsonProperty private final double sigma; @JsonProperty private final long seed; private final double[] sigmas; private final Random random; @JsonCreator public Noisy( @JsonProperty("sensor") Sensor sensor, @JsonProperty("sigma") double sigma, @JsonProperty("seed") long seed ) { super(sensor.getDomains(), sensor); this.sigma = sigma; this.seed = seed; random = new Random(seed); sigmas = Arrays.stream(sensor.getDomains()) .mapToDouble(d -> Math.abs(d.getMax() - d.getMin()) * sigma) .toArray(); reset(); } @Override public double[] sense(double t) { double[] values = sensor.getReadings(); for (int i = 0; i < values.length; i++) { values[i] = values[i] + random.nextGaussian() * sigmas[i]; } return values; } @Override public String toString() { return "Noisy{" + "sensor=" + sensor + ", sigma=" + sigma + '}'; } }
2,023
26.726027
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Sensor.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonTypeInfo; import it.units.erallab.hmsrobots.core.Actionable; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.core.snapshots.Snapshottable; import it.units.erallab.hmsrobots.util.Domain; import java.io.Serializable; @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class") public interface Sensor extends Serializable, Actionable, Snapshottable { Domain[] getDomains(); void setVoxel(SensingVoxel sensingVoxel); double[] getReadings(); }
1,351
35.540541
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/TimeFunction.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.util.Domain; import it.units.erallab.hmsrobots.util.SerializableFunction; public class TimeFunction extends AbstractSensor { @JsonProperty private final SerializableFunction<Double, Double> function; @JsonProperty private final double min; @JsonProperty private final double max; @JsonCreator public TimeFunction( @JsonProperty("function") SerializableFunction<Double, Double> function, @JsonProperty("min") double min, @JsonProperty("max") double max ) { super(new Domain[]{Domain.of(min, max)}); this.min = min; this.max = max; this.function = function; } @Override public double[] sense(double t) { return new double[]{function.apply(t)}; } @Override public String toString() { return "TimeFunction{" + "function=" + function + ", min=" + min + ", max=" + max + '}'; } }
1,830
30.033898
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/ControlPower.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.util.Domain; public class ControlPower extends AbstractSensor { private double lastT; @JsonProperty private final double controlInterval; @JsonCreator public ControlPower( @JsonProperty("controlInterval") double controlInterval ) { super(new Domain[]{ Domain.of(0, 1d / controlInterval) }); this.controlInterval = controlInterval; } @Override public double[] sense(double t) { double power = voxel.getControlEnergy() / (t - lastT); lastT = t; return new double[]{power}; } @Override public void reset() { super.reset(); lastT = 0; } public double getControlInterval() { return controlInterval; } @Override public String toString() { return "ControlPower{" + "controlInterval=" + controlInterval + '}'; } }
1,764
27.015873
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/DynamicNormalization.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.util.Domain; import java.util.Arrays; import java.util.Collections; public class DynamicNormalization extends AggregatorSensor { @JsonCreator public DynamicNormalization( @JsonProperty("sensor") Sensor sensor, @JsonProperty("interval") double interval ) { super( Collections.nCopies(sensor.getDomains().length, Domain.of(0d, 1d)).toArray(Domain[]::new), sensor, interval ); reset(); } @Override protected double[] aggregate(double t) { double[] currentReadings = sensor.getReadings(); double[] mins = new double[currentReadings.length]; double[] maxs = new double[currentReadings.length]; Arrays.fill(mins, Double.POSITIVE_INFINITY); Arrays.fill(maxs, Double.NEGATIVE_INFINITY); for (double[] pastReadings : readings.values()) { for (int i = 0; i < currentReadings.length; i++) { mins[i] = Math.min(mins[i], pastReadings[i]); maxs[i] = Math.max(maxs[i], pastReadings[i]); } } double[] values = new double[currentReadings.length]; for (int i = 0; i < values.length; i++) { values[i] = Math.min(Math.max((currentReadings[i] - mins[i]) / (maxs[i] - mins[i]), 0d), 1d); } return values; } }
2,177
34.129032
99
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/AreaRatio.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import it.units.erallab.hmsrobots.util.Domain; public class AreaRatio extends AbstractSensor { private final static double RATIO_DELTA = 0.5d; private final static Domain[] DOMAINS = new Domain[]{ Domain.of(1d - RATIO_DELTA, 1d + RATIO_DELTA) }; public AreaRatio() { super(DOMAINS); } @Override public double[] sense(double t) { return new double[]{voxel.getAreaRatio()}; } }
1,215
31
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/AbstractSensor.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.core.snapshots.ScopedReadings; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.util.Domain; import java.util.Arrays; /** * @author "Eric Medvet" on 2021/08/13 for 2dhmsr */ public abstract class AbstractSensor implements Sensor { protected final Domain[] domains; protected SensingVoxel voxel; protected double[] readings; public AbstractSensor(Domain[] domains) { this.domains = domains; } @Override public Domain[] getDomains() { return domains; } public SensingVoxel getVoxel() { return voxel; } @Override public void setVoxel(SensingVoxel voxel) { this.voxel = voxel; } @Override public double[] getReadings() { return readings; } @Override public void act(double t) { readings = sense(t); } @Override public void reset() { } @Override public Snapshot getSnapshot() { return new Snapshot( new ScopedReadings( Arrays.copyOf(readings, readings.length), Arrays.stream(domains).map(d -> Domain.of(d.getMin(), d.getMax())).toArray(Domain[]::new) ), getClass() ); } @Override public String toString() { return getClass().getSimpleName(); } protected abstract double[] sense(double t); }
2,187
24.44186
101
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/Velocity.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.geometry.Point2; import it.units.erallab.hmsrobots.util.Domain; import org.dyn4j.geometry.Vector2; import java.util.EnumSet; public class Velocity extends AbstractSensor { public enum Axis {X, Y} @JsonProperty private final boolean rotated; @JsonProperty private final EnumSet<Axis> axes; @JsonProperty private final double maxVelocityNorm; public Velocity(boolean rotated, double maxVelocityNorm, Axis... axes) { this( rotated, maxVelocityNorm, axes.length > 0 ? EnumSet.of(axes[0], axes) : EnumSet.noneOf(Axis.class) ); } @JsonCreator public Velocity( @JsonProperty("rotated") boolean rotated, @JsonProperty("maxVelocityNorm") double maxVelocityNorm, @JsonProperty("axes") EnumSet<Axis> axes ) { super(axes.stream().map(a -> Domain.of(-maxVelocityNorm, maxVelocityNorm)).toArray(Domain[]::new)); this.rotated = rotated; this.maxVelocityNorm = maxVelocityNorm; this.axes = axes; } @Override public double[] sense(double t) { double[] values = new double[domains.length]; int c = 0; Point2 linearVelocity = voxel.getLinearVelocity(); Vector2 velocity = new Vector2(linearVelocity.x, linearVelocity.y); double angle = voxel.getAngle(); if (axes.contains(Axis.X)) { if (!rotated) { values[c] = velocity.x; } else { values[c] = velocity.copy().dot(new Vector2(angle)); } c = c + 1; } if (axes.contains(Axis.Y)) { if (!rotated) { values[c] = velocity.y; } else { values[c] = velocity.copy().dot(new Vector2(angle + Math.PI / 2d)); } } return values; } @Override public String toString() { return "Velocity{" + "rotated=" + rotated + ", axes=" + axes + ", maxVelocityNorm=" + maxVelocityNorm + '}'; } }
2,809
29.879121
103
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/SoftNormalization.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.util.Domain; import java.util.Collections; public class SoftNormalization extends CompositeSensor { @JsonCreator public SoftNormalization( @JsonProperty("sensor") Sensor sensor ) { super( Collections.nCopies(sensor.getDomains().length, Domain.of(0d, 1d)).toArray(Domain[]::new), sensor ); } @Override public double[] sense(double t) { double[] innerValues = sensor.getReadings(); double[] values = new double[innerValues.length]; for (int i = 0; i < values.length; i++) { Domain d = sensor.getDomains()[i]; double v = (innerValues[i] - d.getMin()) / (d.getMax() - d.getMin()); //tanh(((x*2)-1)*2)/2+1/2 values[i] = Math.tanh(((v * 2d) - 1d) * 2d) / 2d + 0.5d; } return values; } }
1,721
31.490566
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/sensors/CompositeSensor.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.sensors; import com.fasterxml.jackson.annotation.JsonProperty; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.util.Domain; /** * @author "Eric Medvet" on 2021/08/13 for 2dhmsr */ public abstract class CompositeSensor extends AbstractSensor { @JsonProperty protected final Sensor sensor; public CompositeSensor( Domain[] domains, Sensor sensor ) { super(domains); this.sensor = sensor; } @Override public void act(double t) { sensor.act(t); readings = sense(t); } @Override public void reset() { super.reset(); sensor.reset(); } @Override public void setVoxel(SensingVoxel voxel) { super.setVoxel(voxel); sensor.setVoxel(voxel); } @Override public Snapshot getSnapshot() { Snapshot snapshot = super.getSnapshot(); snapshot.getChildren().add(sensor.getSnapshot()); return snapshot; } public Sensor getSensor() { return sensor; } @Override public String toString() { return getClass().getSimpleName() + "{" + "sensor=" + sensor + '}'; } }
1,974
24.649351
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/RobotShape.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; import it.units.erallab.hmsrobots.core.geometry.BoundingBox; import it.units.erallab.hmsrobots.core.geometry.Point2; import it.units.erallab.hmsrobots.core.geometry.Shape; import it.units.erallab.hmsrobots.util.Grid; /** * @author "Eric Medvet" on 2021/09/17 for 2dhmsr */ public class RobotShape implements Shape { private final Grid<? extends VoxelPoly> polies; private final BoundingBox boundingBox; public RobotShape(Grid<? extends VoxelPoly> polies, BoundingBox boundingBox) { this.polies = polies; this.boundingBox = boundingBox; } @Override public BoundingBox boundingBox() { return boundingBox; } @Override public Point2 center() { return boundingBox.center(); } public Grid<? extends VoxelPoly> getPolies() { return polies; } }
1,533
29.078431
80
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/SnapshotListener.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public interface SnapshotListener { void listen(double t, Snapshot snapshot); }
945
34.037037
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/SNNState.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter; import it.units.erallab.hmsrobots.util.Domain; import java.util.Arrays; import java.util.stream.IntStream; /** * @author "Eric Medvet" on 2021/09/10 for 2dhmsr */ public class SNNState extends MLPState { private final int[][][] spikes; public SNNState(int[][][] spikes, double[][][] weights, QuantizedSpikeTrainToValueConverter[][] converters, double timeWindowSize) { super(computeFiringRates(spikes, converters,timeWindowSize), weights, Domain.of(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)); this.spikes = copyOf(spikes); } private static double[][] computeFiringRates(int[][][] spikes, QuantizedSpikeTrainToValueConverter[][] converters, double timeWindowSize) { double[][] firingRates = new double[spikes.length][]; IntStream.range(0, spikes.length).forEach(layer -> { firingRates[layer] = new double[spikes[layer].length]; IntStream.range(0, spikes[layer].length).forEach(neuron -> firingRates[layer][neuron] = converters[layer][neuron].convert(spikes[layer][neuron],timeWindowSize) ); }); return firingRates; } public int[][][] getSpikes() { return spikes; } private static double[][] copyOf(double[][] o) { double[][] c = new double[o.length][]; for (int i = 0; i < o.length; i++) { c[i] = Arrays.copyOf(o[i], o[i].length); } return c; } private static int[][] copyOf(int[][] o) { int[][] c = new int[o.length][]; for (int i = 0; i < o.length; i++) { c[i] = Arrays.copyOf(o[i], o[i].length); } return c; } private static double[][][] copyOf(double[][][] o) { double[][][] c = new double[o.length][][]; for (int i = 0; i < o.length; i++) { c[i] = copyOf(o[i]); } return c; } private static int[][][] copyOf(int[][][] o) { int[][][] c = new int[o.length][][]; for (int i = 0; i < o.length; i++) { c[i] = copyOf(o[i]); } return c; } }
2,792
31.476744
141
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/LidarReadings.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; import it.units.erallab.hmsrobots.util.Domain; /** * @author "Eric Medvet" on 2021/08/13 for 2dhmsr */ public class LidarReadings extends ScopedReadings { private final double voxelAngle; private final double[] rayDirections; public LidarReadings(double[] readings, Domain[] domains, double voxelAngle, double[] rayDirections) { super(readings, domains); this.voxelAngle = voxelAngle; this.rayDirections = rayDirections; } public double getVoxelAngle() { return voxelAngle; } public double[] getRayDirections() { return rayDirections; } }
1,388
31.302326
104
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/ScopedReadings.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; import it.units.erallab.hmsrobots.util.Domain; /** * @author "Eric Medvet" on 2021/08/13 for 2dhmsr */ public class ScopedReadings { private final double[] readings; private final Domain[] domains; public ScopedReadings(double[] readings, Domain[] domains) { this.readings = readings; this.domains = domains; } public double[] getReadings() { return readings; } public Domain[] getDomains() { return domains; } }
1,258
28.97619
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/Snapshottable.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; /** * @author eric on 2021/08/12 for 2dhmsr */ public interface Snapshottable { Snapshot getSnapshot(); //TODO maybe later add a filter }
887
33.153846
74
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/MLPState.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; import it.units.erallab.hmsrobots.util.Domain; import java.util.Arrays; /** * @author "Eric Medvet" on 2021/09/10 for 2dhmsr */ public class MLPState { private final double[][] activationValues; private final double[][][] weights; private final Domain activationDomain; public MLPState(double[][] activationValues, double[][][] weights, Domain activationDomain) { this.activationValues = copyOf(activationValues); this.weights = copyOf(weights); this.activationDomain = activationDomain; } public double[][] getActivationValues() { return activationValues; } public double[][][] getWeights() { return weights; } public Domain getActivationDomain() { return activationDomain; } private static double[][] copyOf(double[][] o) { double[][] c = new double[o.length][]; for (int i = 0; i < o.length; i++) { c[i] = Arrays.copyOf(o[i], o[i].length); } return c; } private static double[][][] copyOf(double[][][] o) { double[][][] c = new double[o.length][][]; for (int i = 0; i < o.length; i++) { c[i] = copyOf(o[i]); } return c; } }
1,881
27.089552
95
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/VoxelPoly.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; import it.units.erallab.hmsrobots.core.geometry.Point2; import it.units.erallab.hmsrobots.core.geometry.Poly; import it.units.erallab.hmsrobots.core.objects.BreakableVoxel; import java.util.List; import java.util.Map; /** * @author "Eric Medvet" on 2021/08/13 for 2dhmsr */ public class VoxelPoly extends Poly { private final double angle; private final Point2 linearVelocity; private final boolean isTouchingGround; private final double areaRatio; private final double areaRatioEnergy; private final double lastAppliedForce; private final double controlEnergy; private final Map<BreakableVoxel.ComponentType, BreakableVoxel.MalfunctionType> malfunctions; public VoxelPoly(List<Point2> vertexes, double angle, Point2 linearVelocity, boolean isTouchingGround, double areaRatio, double areaRatioEnergy) { this(vertexes, angle, linearVelocity, isTouchingGround, areaRatio, areaRatioEnergy, 0d, 0d); } public VoxelPoly(List<Point2> vertexes, double angle, Point2 linearVelocity, boolean isTouchingGround, double areaRatio, double areaRatioEnergy, double lastAppliedForce, double controlEnergy) { this(vertexes, angle, linearVelocity, isTouchingGround, areaRatio, areaRatioEnergy, lastAppliedForce, controlEnergy, Map.of()); } public VoxelPoly(List<Point2> vertexes, double angle, Point2 linearVelocity, boolean isTouchingGround, double areaRatio, double areaRatioEnergy, double lastAppliedForce, double controlEnergy, Map<BreakableVoxel.ComponentType, BreakableVoxel.MalfunctionType> malfunctions) { super(vertexes); this.angle = angle; this.linearVelocity = linearVelocity; this.isTouchingGround = isTouchingGround; this.areaRatio = areaRatio; this.areaRatioEnergy = areaRatioEnergy; this.lastAppliedForce = lastAppliedForce; this.controlEnergy = controlEnergy; this.malfunctions = malfunctions; } public double getAngle() { return angle; } public Point2 getLinearVelocity() { return linearVelocity; } public boolean isTouchingGround() { return isTouchingGround; } public double getAreaRatio() { return areaRatio; } public double getAreaRatioEnergy() { return areaRatioEnergy; } public double getLastAppliedForce() { return lastAppliedForce; } public double getControlEnergy() { return controlEnergy; } public Map<BreakableVoxel.ComponentType, BreakableVoxel.MalfunctionType> getMalfunctions() { return malfunctions; } }
3,215
33.580645
275
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/Snapshot.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; import java.util.ArrayList; import java.util.List; /** * @author "Eric Medvet" on 2021/08/12 for 2dhmsr */ public class Snapshot { private final Object content; private final Class<? extends Snapshottable> snapshottableClass; private final List<Snapshot> children; public static Snapshot world(List<Snapshot> snapshots) { Snapshottable snapshottable = () -> world(List.of()); Snapshot snapshot = new Snapshot(new Object(), snapshottable.getClass()); snapshot.getChildren().addAll(snapshots); return snapshot; } public Snapshot(Object content, Class<? extends Snapshottable> snapshottableClass) { this.content = content; this.snapshottableClass = snapshottableClass; this.children = new ArrayList<>(); } public List<Snapshot> getChildren() { return children; } public Object getContent() { return content; } public Class<? extends Snapshottable> getSnapshottableClass() { return snapshottableClass; } }
1,722
29.22807
86
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/core/snapshots/StackedScopedReadings.java
/* * Copyright (c) "Eric Medvet" 2021. * * 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/>. */ package it.units.erallab.hmsrobots.core.snapshots; /** * @author "Eric Medvet" on 2021/09/07 for 2dhmsr */ public class StackedScopedReadings { private final ScopedReadings[] scopedReadings; public StackedScopedReadings(ScopedReadings... scopedReadings) { this.scopedReadings = scopedReadings; } public ScopedReadings[] getScopedReadings() { return scopedReadings; } }
1,085
30.941176
74
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/util/Utils.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.util; import com.google.common.collect.LinkedHashMultiset; import com.google.common.collect.Multiset; import org.apache.commons.lang3.tuple.Pair; import java.util.*; import java.util.function.Predicate; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class Utils { private Utils() { } private static final Logger L = Logger.getLogger(Utils.class.getName()); public static <K> Grid<K> gridLargestConnected(Grid<K> kGrid, Predicate<K> p) { Grid<Integer> iGrid = partitionGrid(kGrid, p); //count elements per partition Multiset<Integer> counts = LinkedHashMultiset.create(); for (Integer i : iGrid.values()) { if (i != null) { counts.add(i); } } //find largest Integer maxIndex = null; int max = 0; for (Integer index : counts.elementSet()) { int count = counts.count(index); if (count > max) { max = count; maxIndex = index; } } //if no largest, return empty if (maxIndex == null) { return Grid.create(kGrid); } //filter map Grid<K> filtered = Grid.create(kGrid); for (Grid.Entry<Integer> iEntry : iGrid) { if (iEntry.getValue() != null && iEntry.getValue().equals(maxIndex)) { filtered.set(iEntry.getX(), iEntry.getY(), kGrid.get(iEntry.getX(), iEntry.getY())); } } return filtered; } public static <K> Grid<K> gridConnected(Grid<K> kGrid, Comparator<K> comparator, int n) { Comparator<Grid.Entry<K>> entryComparator = (e1, e2) -> comparator.compare(e1.getValue(), e2.getValue()); Predicate<Pair<Grid.Entry<?>, Grid.Entry<?>>> adjacencyPredicate = p -> (Math.abs(p.getLeft().getX() - p.getRight().getX()) <= 1 && p.getLeft().getY() == p.getRight().getY()) || (Math.abs(p.getLeft().getY() - p.getRight().getY()) <= 1 && p.getLeft().getX() == p.getRight().getX()); Grid.Entry<K> entryFirst = kGrid.stream() .min(entryComparator) .orElseThrow(() -> new IllegalArgumentException("Grid has no max element")); Set<Grid.Entry<K>> selected = new HashSet<>(n); selected.add(entryFirst); while (selected.size() < n) { Set<Grid.Entry<K>> candidates = kGrid.stream() .filter(e -> e.getValue() != null) .filter(e -> !selected.contains(e)) .filter(e -> selected.stream().anyMatch(f -> adjacencyPredicate.test(Pair.of(e, f)))) .collect(Collectors.toSet()); if (candidates.isEmpty()) { break; } selected.add(candidates.stream().min(entryComparator).orElse(entryFirst)); } Grid<K> outGrid = Grid.create(kGrid.getW(), kGrid.getH()); selected.forEach(e -> outGrid.set(e.getX(), e.getY(), e.getValue())); return outGrid; } private static <K> Grid<Integer> partitionGrid(Grid<K> kGrid, Predicate<K> p) { Grid<Integer> iGrid = Grid.create(kGrid); for (int x = 0; x < kGrid.getW(); x++) { for (int y = 0; y < kGrid.getH(); y++) { if (iGrid.get(x, y) == null) { int index = iGrid.values().stream().filter(Objects::nonNull).mapToInt(i -> i).max().orElse(0); partitionGrid(x, y, index + 1, kGrid, iGrid, p); } } } return iGrid; } private static <K> void partitionGrid(int x, int y, int i, Grid<K> kGrid, Grid<Integer> iGrid, Predicate<K> p) { boolean hereFilled = p.test(kGrid.get(x, y)); //already done if (iGrid.get(x, y) != null) { return; } //filled but not done if (hereFilled) { iGrid.set(x, y, i); //expand east if (x > 0) { partitionGrid(x - 1, y, i, kGrid, iGrid, p); } //expand west if (x < kGrid.getW() - 1) { partitionGrid(x + 1, y, i, kGrid, iGrid, p); } //expand north if (y > 0) { partitionGrid(x, y - 1, i, kGrid, iGrid, p); } //expand south if (y < kGrid.getH() - 1) { partitionGrid(x, y + 1, i, kGrid, iGrid, p); } } } public static <K> Grid<K> cropGrid(Grid<K> inGrid, Predicate<K> p) { //find bounds int minX = inGrid.getW(); int maxX = 0; int minY = inGrid.getH(); int maxY = 0; for (Grid.Entry<K> entry : inGrid) { if (p.test(entry.getValue())) { minX = Math.min(minX, entry.getX()); maxX = Math.max(maxX, entry.getX()); minY = Math.min(minY, entry.getY()); maxY = Math.max(maxY, entry.getY()); } } //build new grid Grid<K> outGrid = Grid.create(maxX - minX + 1, maxY - minY + 1); //fill for (int x = 0; x < outGrid.getW(); x++) { for (int y = 0; y < outGrid.getH(); y++) { outGrid.set(x, y, inGrid.get(x + minX, y + minY)); } } return outGrid; } public static double shapeElongation(Grid<Boolean> posture, int n) { if (posture.values().stream().noneMatch(e -> e)) { throw new IllegalArgumentException("Grid is empty"); } else if (n <= 0) { throw new IllegalArgumentException(String.format("Non-positive number of directions provided: %d", n)); } List<Pair<Integer, Integer>> coordinates = posture.stream() .filter(Grid.Entry::getValue) .map(e -> Pair.of(e.getX(), e.getY())) .collect(Collectors.toList()); List<Double> diameters = new ArrayList<>(); for (int i = 0; i < n; ++i) { double theta = (2 * i * Math.PI) / n; List<Pair<Double, Double>> rotatedCoordinates = coordinates.stream() .map(p -> Pair.of(p.getLeft() * Math.cos(theta) - p.getRight() * Math.sin(theta), p.getLeft() * Math.sin(theta) + p.getRight() * Math.cos(theta))) .collect(Collectors.toList()); double minX = rotatedCoordinates.stream().min(Comparator.comparingDouble(Pair::getLeft)).get().getLeft(); double maxX = rotatedCoordinates.stream().max(Comparator.comparingDouble(Pair::getLeft)).get().getLeft(); double minY = rotatedCoordinates.stream().min(Comparator.comparingDouble(Pair::getRight)).get().getRight(); double maxY = rotatedCoordinates.stream().max(Comparator.comparingDouble(Pair::getRight)).get().getRight(); double sideX = maxX - minX + 1; double sideY = maxY - minY + 1; diameters.add(Math.min(sideX, sideY) / Math.max(sideX, sideY)); } return 1.0 - Collections.min(diameters); } public static double shapeCompactness(Grid<Boolean> posture) { // approximate convex hull Grid<Boolean> convexHull = Grid.create(posture.getW(), posture.getH(), posture::get); boolean none = false; // loop as long as there are false cells have at least five of the eight Moore neighbors as true while (!none) { none = true; for (Grid.Entry<Boolean> entry : convexHull) { if (convexHull.get(entry.getX(), entry.getY())) { continue; } int currentX = entry.getX(); int currentY = entry.getY(); int adjacentCount = 0; // count how many of the Moore neighbors are true for (int i : new int[]{1, -1}) { int neighborX = currentX; int neighborY = currentY + i; if (0 <= neighborY && neighborY < convexHull.getH() && convexHull.get(neighborX, neighborY)) { adjacentCount += 1; } neighborX = currentX + i; neighborY = currentY; if (0 <= neighborX && neighborX < convexHull.getW() && convexHull.get(neighborX, neighborY)) { adjacentCount += 1; } neighborX = currentX + i; neighborY = currentY + i; if (0 <= neighborX && 0 <= neighborY && neighborX < convexHull.getW() && neighborY < convexHull.getH() && convexHull.get(neighborX, neighborY)) { adjacentCount += 1; } neighborX = currentX + i; neighborY = currentY - i; if (0 <= neighborX && 0 <= neighborY && neighborX < convexHull.getW() && neighborY < convexHull.getH() && convexHull.get(neighborX, neighborY)) { adjacentCount += 1; } } // if at least five, fill the cell if (adjacentCount >= 5) { convexHull.set(entry.getX(), entry.getY(), true); none = false; } } } // compute are ratio between convex hull and posture int nVoxels = (int) posture.count(e -> e); int nConvexHull = (int) convexHull.count(e -> e); // -> 0.0 for less compact shapes, -> 1.0 for more compact shapes return (double) nVoxels / nConvexHull; } @SafeVarargs public static <E> List<E> ofNonNull(E... es) { List<E> list = new ArrayList<>(); for (E e : es) { if (e != null) { list.add(e); } } return list; } public static String param(String pattern, String string, String paramName) { Matcher matcher = Pattern.compile(pattern).matcher(string); if (matcher.matches()) { return matcher.group(paramName); } throw new IllegalStateException(String.format("Param %s not found in %s with pattern %s", paramName, string, pattern)); } public static Map<String, String> params(String pattern, String string) { if (!string.matches(pattern)) { return null; } Matcher m = Pattern.compile("\\(\\?<([a-zA-Z][a-zA-Z0-9]*)>").matcher(pattern); List<String> groupNames = new ArrayList<>(); while (m.find()) { groupNames.add(m.group(1)); } Map<String, String> params = new HashMap<>(); for (String groupName : groupNames) { String value = param(pattern, string, groupName); if (value != null) { params.put(groupName, value); } } return params; } }
10,476
36.417857
285
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/util/RobotUtils.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.util; import it.units.erallab.hmsrobots.core.objects.BreakableVoxel; import it.units.erallab.hmsrobots.core.objects.Robot; import it.units.erallab.hmsrobots.core.objects.SensingVoxel; import it.units.erallab.hmsrobots.core.sensors.*; import java.util.*; import java.util.function.Function; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import static it.units.erallab.hmsrobots.util.Utils.params; /** * @author eric on 2020/12/22 for 2dhmsr */ public class RobotUtils { private final static Map<String, Function<GridPosition, Sensor>> PREDEFINED_SENSORS = new TreeMap<>(Map.ofEntries( Map.entry("t", p -> new Average(new Touch(), 0.25)), Map.entry("a", p -> new SoftNormalization(new AreaRatio())), Map.entry("r", p -> new SoftNormalization(new Angle())), Map.entry("vx", p -> new SoftNormalization(new Average(new Velocity(true, 8d, Velocity.Axis.X), 0.5))), Map.entry("vy", p -> new SoftNormalization(new Average(new Velocity(true, 8d, Velocity.Axis.Y), 0.5))), Map.entry("vxy", p -> new SoftNormalization(new Average(new Velocity(true, 8d, Velocity.Axis.X, Velocity.Axis.Y), 0.5))), Map.entry("ax", p -> new SoftNormalization(new Trend(new Velocity(true, 4d, Velocity.Axis.X), 0.5))), Map.entry("ay", p -> new SoftNormalization(new Trend(new Velocity(true, 4d, Velocity.Axis.Y), 0.5))), Map.entry("axy", p -> new SoftNormalization(new Trend(new Velocity(true, 4d, Velocity.Axis.X, Velocity.Axis.Y), 0.5))), Map.entry("px", p -> new Constant((double) p.x / ((double) p.width - 1d))), Map.entry("py", p -> new Constant((double) p.y / ((double) p.height - 1d))), Map.entry("m", p -> new Malfunction()), Map.entry("cpg", p -> new Normalization(new TimeFunction(t -> Math.sin(2 * Math.PI * -1 * t), -1, 1))), Map.entry("l5", p -> new Normalization(new Lidar(10d, Map.of(lidarSide((double) p.x / ((double) p.width - 1d), (double) p.y / ((double) p.height - 1d)), 5)))), Map.entry("l1", p -> new Normalization(new Lidar(10d, Map.of(lidarSide((double) p.x / ((double) p.width - 1d), (double) p.y / ((double) p.height - 1d)), 1)))), Map.entry("lf5", p -> createLidar(p, 5, 1)) )); private static class GridPosition { final int x; final int y; final int width; final int height; public GridPosition(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } } private static Lidar createLidar(GridPosition gridPosition, int numberOfRays, int l) { double voxelSize = 3; double verticalDistance = gridPosition.y + 0.5; double horizontalDistanceFromBodyEnd = gridPosition.x + 0.5; if (gridPosition.x >= gridPosition.width / 2) { horizontalDistanceFromBodyEnd = gridPosition.width - horizontalDistanceFromBodyEnd; } double maxHorizontalDistance = 2 * l * gridPosition.width + horizontalDistanceFromBodyEnd; double minHorizontalDistance = l * gridPosition.width + horizontalDistanceFromBodyEnd; double rayLength = voxelSize * Math.sqrt(maxHorizontalDistance * maxHorizontalDistance + verticalDistance * verticalDistance); double startAngle = 3 * Math.PI / 2 - Math.atan(minHorizontalDistance / verticalDistance); double endAngle = 3 * Math.PI / 2 - Math.atan(maxHorizontalDistance / verticalDistance); if (gridPosition.x >= gridPosition.width / 2) { startAngle = Math.PI - startAngle; endAngle = Math.PI - endAngle; } return new Lidar(rayLength, startAngle, endAngle, numberOfRays); } private static Lidar.Side lidarSide(double x, double y) { if (y > x && y > (1 - x)) { return Lidar.Side.N; } if (y >= x && y <= (1 - x)) { return Lidar.Side.W; } if (y < x && y < (1 - x)) { return Lidar.Side.S; } return Lidar.Side.E; } private RobotUtils() { } public static UnaryOperator<Robot<?>> buildRobotTransformation(String name, Random externalRandom) { String breakable = "breakable-(?<triggerType>time|area)-(?<thresholdMean>\\d+(\\.\\d+)?)/(?<thresholdStDev>\\d+(\\.\\d+)?)-(?<restTimeMean>\\d+(\\.\\d+)?)/(?<restTimeStDev>\\d+(\\.\\d+)?)-(?<seed>\\d+|rnd)"; String broken = "broken-(?<ratio>\\d+(\\.\\d+)?)-(?<seed>\\d+|rnd)"; String identity = "identity"; Map<String, String> params; if ((params = params(identity, name)) != null) { return UnaryOperator.identity(); } if ((params = params(breakable, name)) != null) { String type = params.get("triggerType"); double thresholdMean = Double.parseDouble(params.get("thresholdMean")); double thresholdStDev = Double.parseDouble(params.get("thresholdStDev")); double restoreTimeMean = Double.parseDouble(params.get("restTimeMean")); double restoreTimeStDev = Double.parseDouble(params.get("restTimeStDev")); Random random; if (!params.get("seed").equals("rnd")) { random = new Random(Long.parseLong(params.get("seed"))); } else { random = externalRandom; } return new UnaryOperator<Robot<?>>() { @Override @SuppressWarnings("unchecked") public Robot<?> apply(Robot<?> robot) { return new Robot<>( ((Robot<SensingVoxel>) robot).getController(), Grid.create(SerializationUtils.clone((Grid<SensingVoxel>) robot.getVoxels()), v -> v == null ? null : new BreakableVoxel( v.getSensors(), random.nextInt(), Map.of( BreakableVoxel.ComponentType.ACTUATOR, Set.of(BreakableVoxel.MalfunctionType.FROZEN) ), Map.of( BreakableVoxel.MalfunctionTrigger.valueOf(type.toUpperCase()), random.nextGaussian() * thresholdStDev + thresholdMean ), random.nextGaussian() * restoreTimeStDev + restoreTimeMean )) ); } }; } if ((params = params(broken, name)) != null) { double ratio = Double.parseDouble(params.get("ratio")); Random random; if (!params.get("seed").equals("rnd")) { random = new Random(Long.parseLong(params.get("seed"))); } else { random = externalRandom; } return new UnaryOperator<Robot<?>>() { @Override @SuppressWarnings("unchecked") public Robot<?> apply(Robot<?> robot) { return new Robot<>( ((Robot<SensingVoxel>) robot).getController(), Grid.create(SerializationUtils.clone((Grid<SensingVoxel>) robot.getVoxels()), v -> v == null ? null : random.nextDouble() > ratio ? v : new BreakableVoxel( v.getSensors(), random.nextInt(), Map.of(BreakableVoxel.ComponentType.ACTUATOR, Set.of(BreakableVoxel.MalfunctionType.FROZEN)), Map.of(BreakableVoxel.MalfunctionTrigger.TIME, 0d), Double.POSITIVE_INFINITY )) ); } }; } throw new IllegalArgumentException(String.format("Unknown transformation name: %s", name)); } public static Function<Grid<Boolean>, Grid<? extends SensingVoxel>> buildSensorizingFunction(String name) { String spineTouch = "spinedTouch-(?<cpg>[tf])-(?<malfunction>[tf])-(?<noiseSigma>\\d+(\\.\\d+)?)"; String spineTouchSighted = "spinedTouchSighted-(?<cpg>[tf])-(?<malfunction>[tf])-(?<noiseSigma>\\d+(\\.\\d+)?)"; String uniform = "uniform-(?<sensors>(" + String.join("|", PREDEFINED_SENSORS.keySet()) + ")(\\+(" + String.join("|", PREDEFINED_SENSORS.keySet()) + "))*)-(?<noiseSigma>\\d+(\\.\\d+)?)"; String uniformAll = "uniformAll-(?<noiseSigma>\\d+(\\.\\d+)?)"; String empty = "empty"; Map<String, String> params; if ((params = params(spineTouch, name)) != null) { final Map<String, String> pars = params; double noiseSigma = Double.parseDouble(params.get("noiseSigma")); return body -> Grid.create(body.getW(), body.getH(), (x, y) -> { if (!body.get(x, y)) { return null; } return new SensingVoxel( Utils.ofNonNull( sensor("a", x, y, body), sensor("m", x, y, body, pars.get("malfunction").equals("t")), sensor("t", x, y, body, y == 0), sensor("vxy", x, y, body, y == body.getH() - 1), sensor("cpg", x, y, body, x == body.getW() - 1 && y == body.getH() - 1 && pars.get("cpg").equals("t")) ).stream() .map(s -> noiseSigma == 0 ? s : new Noisy(s, noiseSigma, 0)) .collect(Collectors.toList()) ); } ); } if ((params = params(spineTouchSighted, name)) != null) { final Map<String, String> pars = params; double noiseSigma = Double.parseDouble(params.get("noiseSigma")); return body -> Grid.create(body.getW(), body.getH(), (x, y) -> { if (!body.get(x, y)) { return null; } return new SensingVoxel( Utils.ofNonNull( sensor("a", x, y, body), sensor("m", x, y, body, pars.get("malfunction").equals("t")), sensor("t", x, y, body, y == 0), sensor("vxy", x, y, body, y == body.getH() - 1), sensor("cpg", x, y, body, x == body.getW() - 1 && y == body.getH() - 1 && pars.get("cpg").equals("t")), sensor("l5", x, y, body, x == body.getW() - 1) ).stream() .map(s -> noiseSigma == 0 ? s : new Noisy(s, noiseSigma, 0)) .collect(Collectors.toList()) ); } ); } if ((params = params(uniform, name)) != null) { final Map<String, String> pars = params; double noiseSigma = Double.parseDouble(params.get("noiseSigma")); return body -> Grid.create(body.getW(), body.getH(), (x, y) -> !body.get(x, y) ? null : new SensingVoxel( Arrays.stream(pars.get("sensors").split("\\+")) .map(n -> sensor(n, x, y, body)) .map(s -> noiseSigma == 0 ? s : new Noisy(s, noiseSigma, 0)) .collect(Collectors.toList()) )); } if ((params = params(uniformAll, name)) != null) { final Map<String, String> pars = params; double noiseSigma = Double.parseDouble(params.get("noiseSigma")); return body -> Grid.create(body.getW(), body.getH(), (x, y) -> !body.get(x, y) ? null : new SensingVoxel( PREDEFINED_SENSORS.keySet().stream() .map(n -> sensor(n, x, y, body)) .map(s -> noiseSigma == 0 ? s : new Noisy(s, noiseSigma, 0)) .collect(Collectors.toList()) )); } if ((params = params(empty, name)) != null) { return body -> Grid.create(body.getW(), body.getH(), (x, y) -> !body.get(x, y) ? null : new SensingVoxel(List.of())); } throw new IllegalArgumentException(String.format("Unknown sensorizing function name: %s", name)); } public static Sensor sensor(String name, int x, int y, Grid<Boolean> body) { return sensor(name, x, y, body, true); } public static Sensor sensor(String name, int x, int y, Grid<Boolean> body, boolean condition) { if (!condition) { return null; } return PREDEFINED_SENSORS.get(name).apply(new GridPosition(x, y, body.getW(), body.getH())); } public static Grid<Boolean> buildShape(String name) { String box = "(box|worm)-(?<w>\\d+)x(?<h>\\d+)"; String biped = "biped-(?<w>\\d+)x(?<h>\\d+)"; String tripod = "tripod-(?<w>\\d+)x(?<h>\\d+)"; String ball = "ball-(?<d>\\d+)"; String comb = "comb-(?<w>\\d+)x(?<h>\\d+)"; Map<String, String> params; if ((params = params(box, name)) != null) { int w = Integer.parseInt(params.get("w")); int h = Integer.parseInt(params.get("h")); return Grid.create(w, h, true); } if ((params = params(biped, name)) != null) { int w = Integer.parseInt(params.get("w")); int h = Integer.parseInt(params.get("h")); return Grid.create(w, h, (x, y) -> !(y < h / 2 && x >= w / 4 && x < w * 3 / 4)); } if ((params = params(tripod, name)) != null) { int w = Integer.parseInt(params.get("w")); int h = Integer.parseInt(params.get("h")); return Grid.create(w, h, (x, y) -> !(y < h / 2 && x != 0 && x != w - 1 && x != w / 2)); } if ((params = params(ball, name)) != null) { int d = Integer.parseInt(params.get("d")); return Grid.create( d, d, (x, y) -> Math.round(Math.sqrt((x - (d - 1) / 2d) * (x - (d - 1) / 2d) + (y - (d - 1) / 2d) * (y - (d - 1) / 2d))) <= (int) Math.floor(d / 2d) ); } if ((params = params(comb, name)) != null) { int w = Integer.parseInt(params.get("w")); int h = Integer.parseInt(params.get("h")); return Grid.create(w, h, (x, y) -> (y >= h / 2 || x % 2 == 0)); } throw new IllegalArgumentException(String.format("Unknown body name: %s", name)); } }
13,963
45.085809
211
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/util/Domain.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.util; import java.io.Serializable; import java.util.Arrays; public class Domain implements Serializable { private final double min; private final double max; private Domain(double min, double max) { this.min = min; this.max = max; } public static Domain of(double min, double max) { return new Domain(min, max); } public static Domain[] of(double min, double max, int n) { Domain[] domains = new Domain[n]; Arrays.fill(domains, Domain.of(min, max)); return domains; } public double getMin() { return min; } public double getMax() { return max; } @Override public String toString() { return String.format("[%.1f;%.1f]", min, max); } }
1,498
26.254545
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/util/SerializableFunction.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as eric) * * 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/>. */ package it.units.erallab.hmsrobots.util; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.Serializable; import java.util.function.Function; /** * @author Eric Medvet <eric.medvet@gmail.com> */ @FunctionalInterface @JsonSerialize(using = SerializationUtils.LambdaJsonSerializer.class) @JsonDeserialize(using = SerializationUtils.LambdaJsonDeserializer.class) public interface SerializableFunction<T, R> extends Function<T, R>, Serializable { }
1,274
36.5
82
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/util/SerializationUtils.java
package it.units.erallab.hmsrobots.util; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import java.io.*; import java.util.Base64; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * @author eric */ public class SerializationUtils { private SerializationUtils() { } public enum Mode {JAVA, JSON, PRETTY_JSON, GZIPPED_JAVA, GZIPPED_JSON} private static final Logger L = Logger.getLogger(Utils.class.getName()); private static final Mode DEFAULT_SERIALIZATION_MODE = Mode.GZIPPED_JSON; private static final Mode DEFAULT_CLONE_MODE = Mode.JAVA; private static final ObjectMapper OM; private static final ObjectMapper PRETTY_OM; static { OM = new ObjectMapper(); OM.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); OM.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.NONE); OM.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); PRETTY_OM = new ObjectMapper(); PRETTY_OM.enable(SerializationFeature.INDENT_OUTPUT); PRETTY_OM.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); PRETTY_OM.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.NONE); PRETTY_OM.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); } public static class LambdaJsonSerializer extends JsonSerializer<SerializableFunction<?, ?>> { @Override public void serialize(SerializableFunction<?, ?> serializableFunction, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { try ( ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream) ) { outputStream.writeObject(serializableFunction); jsonGenerator.writeBinary(byteArrayOutputStream.toByteArray()); } } @Override public void serializeWithType(SerializableFunction<?, ?> serializableFunction, JsonGenerator jsonGenerator, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { //WritableTypeId typeId = typeSer.typeId(serializableFunction, JsonToken.START_OBJECT); //typeSer.writeTypePrefix(jsonGenerator, typeId); //jsonGenerator.writeFieldName("ser"); serialize(serializableFunction, jsonGenerator, serializers); //typeSer.writeTypeSuffix(jsonGenerator, typeId); } } public static class LambdaJsonDeserializer extends JsonDeserializer<SerializableFunction<?, ?>> { @Override public SerializableFunction<?, ?> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { byte[] value = jsonParser.getBinaryValue(); try ( ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(value); ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream) ) { return (SerializableFunction<?, ?>) inputStream.readObject(); } catch (ClassNotFoundException e) { throw new IOException(e); } } @Override public Object deserializeWithType(JsonParser jsonParser, DeserializationContext deserializationContext, TypeDeserializer typeDeserializer) throws IOException { return deserialize(jsonParser, deserializationContext); } } public static String serialize(Object object) { return serialize(object, DEFAULT_SERIALIZATION_MODE); } public static <T> T deserialize(String string, Class<T> tClass) { return deserialize(string, tClass, DEFAULT_SERIALIZATION_MODE); } public static <T> T clone(T t) { return clone(t, DEFAULT_CLONE_MODE); } public static <T> T clone(T t, Mode mode) { return (T) deserialize(serialize(t, mode), t.getClass(), mode); } public static String serialize(Object object, Mode mode) { try { return switch (mode) { case JAVA -> encode(javaSerialize(object)); case JSON -> jsonSerialize(object, false); case PRETTY_JSON -> jsonSerialize(object, true); case GZIPPED_JAVA -> encode(gzip(javaSerialize(object))); case GZIPPED_JSON -> encode(gzip(jsonSerialize(object, false).getBytes())); }; } catch (IOException e) { L.log(Level.SEVERE, String.format("Cannot serialize due to %s", e), e); return ""; } } public static <T> T deserialize(String string, Class<T> tClass, Mode mode) { try { return switch (mode) { case JAVA -> javaDeserialize(decode(string), tClass); case JSON, PRETTY_JSON -> jsonDeserialize(string, tClass); case GZIPPED_JAVA -> javaDeserialize(ungzip(decode(string)), tClass); case GZIPPED_JSON -> jsonDeserialize(new String(ungzip(decode(string))), tClass); }; } catch (IOException e) { L.log(Level.SEVERE, String.format("Cannot deserialize due to %s", e), e); return null; } } private static byte[] javaSerialize(Object object) throws IOException { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos) ) { oos.writeObject(object); oos.flush(); return baos.toByteArray(); } } private static <T> T javaDeserialize(byte[] raw, Class<T> tClass) throws IOException { try ( ByteArrayInputStream bais = new ByteArrayInputStream(raw); ObjectInputStream ois = new ObjectInputStream(bais) ) { Object o = ois.readObject(); return (T) o; } catch (ClassNotFoundException e) { throw new IOException(e); } } private static String jsonSerialize(Object object, boolean pretty) throws IOException { return pretty ? PRETTY_OM.writeValueAsString(object) : OM.writeValueAsString(object); } private static <T> T jsonDeserialize(String string, Class<T> tClass) throws IOException { return OM.readValue(string, tClass); } private static byte[] gzip(byte[] raw) throws IOException { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos, true); ) { gos.write(raw); gos.flush(); gos.close(); return baos.toByteArray(); } } private static byte[] ungzip(byte[] raw) throws IOException { try ( ByteArrayInputStream bais = new ByteArrayInputStream(raw); GZIPInputStream gis = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ) { byte[] buf = new byte[1024]; while (true) { int read = gis.read(buf); if (read == -1) { break; } baos.write(buf, 0, read); } return baos.toByteArray(); } } private static String encode(byte[] raw) { return Base64.getEncoder().encodeToString(raw); } private static byte[] decode(String string) { return Base64.getDecoder().decode(string); } }
7,411
35.693069
188
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/util/Parametrized.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as eric) * * 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/>. */ package it.units.erallab.hmsrobots.util; public interface Parametrized { double[] getParams(); void setParams(double[] params); }
865
35.083333
74
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/util/Grid.java
/* * Copyright (C) 2020 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.util; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import java.io.Serializable; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class Grid<T> implements Iterable<Grid.Entry<T>>, Serializable { private final static char FULL_CELL_CHAR = '█'; private final static char EMPTY_CELL_CHAR = '░'; public static class Key implements Serializable { private final int x; private final int y; public Key(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Key key = (Key) o; return x == key.x && y == key.y; } @Override public int hashCode() { return Objects.hash(x, y); } } public static final class Entry<K> extends Key implements Serializable { private final K value; public Entry(int x, int y, K value) { super(x, y); this.value = value; } public K getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Entry<?> entry = (Entry<?>) o; return Objects.equals(value, entry.value); } @Override public int hashCode() { return Objects.hash(super.hashCode(), value); } } private static final class GridIterator<K> implements Iterator<Entry<K>> { private int c = 0; private final Grid<K> grid; public GridIterator(Grid<K> grid) { this.grid = grid; } @Override public boolean hasNext() { return c < grid.w * grid.h; } @Override public Entry<K> next() { int y = Math.floorDiv(c, grid.w); int x = c % grid.w; c = c + 1; return new Entry<>(x, y, grid.get(x, y)); } } @JsonProperty("items") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class") private final List<T> ts; @JsonProperty private final int w; @JsonProperty private final int h; @JsonCreator public Grid(@JsonProperty("w") int w, @JsonProperty("h") int h, @JsonProperty("items") List<T> ts) { this.w = w; this.h = h; this.ts = new ArrayList<>(w * h); for (int i = 0; i < w * h; i++) { if ((ts != null) && (i < ts.size())) { this.ts.add(ts.get(i)); } else { this.ts.add(null); } } } public T get(int x, int y) { if ((x < 0) || (x >= w)) { return null; } if ((y < 0) || (y >= h)) { return null; } return ts.get((y * w) + x); } public void set(int x, int y, T t) { if (x < 0 || x >= w || y < 0 || y >= h) { throw new IllegalArgumentException(String.format("Cannot set element at %d,%d on a %dx%d grid", x, y, w, h)); } ts.set((y * w) + x, t); } public int getW() { return w; } public int getH() { return h; } public static <S, T> Grid<T> create(Grid<S> source, Function<S, T> transformerFunction) { Grid<T> target = Grid.create(source); for (Entry<S> entry : source) { target.set(entry.getX(), entry.getY(), transformerFunction.apply(entry.getValue())); } return target; } public static <K> Grid<K> create(int w, int h, K k) { return create(w, h, (x, y) -> k); } public static <K> Grid<K> create(int w, int h, BiFunction<Integer, Integer, K> fillerFunction) { Grid<K> grid = new Grid<>(w, h, null); for (int x = 0; x < grid.getW(); x++) { for (int y = 0; y < grid.getH(); y++) { grid.set(x, y, fillerFunction.apply(x, y)); } } return grid; } public static <K> Grid<K> create(int w, int h) { return create(w, h, (K) null); } public static <K> Grid<K> create(Grid<?> other) { return create(other.getW(), other.getH()); } public static <K> Grid<K> copy(Grid<K> other) { Grid<K> grid = Grid.create(other); for (int x = 0; x < grid.w; x++) { for (int y = 0; y < grid.h; y++) { grid.set(x, y, other.get(x, y)); } } return grid; } @Override public Iterator<Entry<T>> iterator() { return new GridIterator<>(this); } public Stream<Entry<T>> stream() { return StreamSupport.stream(spliterator(), false); } public Collection<T> values() { return Collections.unmodifiableList(ts); } public long count(Predicate<T> predicate) { return values().stream().filter(predicate).count(); } public List<List<T>> rows() { List<List<T>> rows = new ArrayList<>(); for (int y = 0; y < h; y++) { List<T> row = new ArrayList<>(); for (int x = 0; x < w; x++) { row.add(get(x, y)); } rows.add(row); } return rows; } public List<List<T>> columns() { List<List<T>> columns = new ArrayList<>(); for (int x = 0; x < w; x++) { List<T> column = new ArrayList<>(); for (int y = 0; y < h; y++) { column.add(get(x, y)); } columns.add(column); } return columns; } public boolean[][] toArray(Predicate<T> p) { boolean[][] b = new boolean[w][h]; for (Entry<T> entry : this) { b[entry.getX()][entry.getY()] = p.test(entry.getValue()); } return b; } public static <K> String toString(Grid<K> grid, String format) { StringBuilder sb = new StringBuilder(); for (int y = 0; y < grid.getH(); y++) { for (int x = 0; x < grid.getW(); x++) { sb.append(String.format(format, grid.get(x, y))); } if (y < grid.getH() - 1) { sb.append(String.format("%n")); } } return sb.toString(); } public static String toString(Grid<Boolean> grid) { return toString(grid, (Predicate<Boolean>) b -> b); } public static <K> String toString(Grid<K> grid, Predicate<K> p) { return toString(grid, p, "\n"); } public static <K> String toString(Grid<K> grid, Predicate<K> p, String separator) { return toString(grid, (Entry<K> e) -> p.test(e.getValue()) ? FULL_CELL_CHAR : EMPTY_CELL_CHAR, separator); } public static <K> String toString(Grid<K> grid, Function<K, Character> function) { return toString(grid, (Entry<K> e) -> function.apply(e.getValue()), "\n"); } public static <K> String toString(Grid<K> grid, Function<Entry<K>, Character> function, String separator) { StringBuilder sb = new StringBuilder(); for (int y = 0; y < grid.getH(); y++) { for (int x = 0; x < grid.getW(); x++) { sb.append(function.apply(new Entry<>(x, y, grid.get(x, y)))); } if (y < grid.getH() - 1) { sb.append(separator); } } return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Grid<?> grid = (Grid<?>) o; return w == grid.w && h == grid.h && ts.equals(grid.ts); } @Override public int hashCode() { return Objects.hash(ts, w, h); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { sb.append(String.format("(%d,%d)=%s", x, y, get(x, y))); if ((x < (w - 1)) && (y < (h - 1))) { sb.append(", "); } } } sb.append("]"); return sb.toString(); } }
8,605
25.078788
115
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/viewers/VideoUtils.java
package it.units.erallab.hmsrobots.viewers; import org.jcodec.api.SequenceEncoder; import org.jcodec.common.Format; import org.jcodec.common.io.NIOUtils; import org.jcodec.common.io.SeekableByteChannel; import org.jcodec.common.model.Rational; import org.jcodec.scale.AWTUtil; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author eric */ public class VideoUtils { public enum EncoderFacility {JCODEC, FFMPEG_LARGE, FFMPEG_SMALL} private static final EncoderFacility DEFAULT_ENCODER = EncoderFacility.JCODEC; private static final Logger L = Logger.getLogger(VideoUtils.class.getName()); private VideoUtils() { } public static void encodeAndSave(List<BufferedImage> images, double frameRate, File file) throws IOException { encodeAndSave(images, frameRate, file, DEFAULT_ENCODER); } public static void encodeAndSave(List<BufferedImage> images, double frameRate, File file, EncoderFacility encoder) throws IOException { switch (encoder) { case JCODEC -> encodeAndSaveWithJCodec(images, frameRate, file); case FFMPEG_LARGE -> encodeAndSaveWithFFMpeg(images, frameRate, file, 18); case FFMPEG_SMALL -> encodeAndSaveWithFFMpeg(images, frameRate, file, 30); } } private static void encodeAndSaveWithJCodec(List<BufferedImage> images, double frameRate, File file) throws IOException { SeekableByteChannel channel = NIOUtils.writableChannel(file); SequenceEncoder encoder = new SequenceEncoder( channel, Rational.R((int) Math.round(frameRate), 1), Format.MOV, org.jcodec.common.Codec.H264, null ); //encode try { for (BufferedImage image : images) { encoder.encodeNativeFrame(AWTUtil.fromBufferedImageRGB(image)); } } catch (IOException ex) { L.severe(String.format("Cannot encode image due to %s", ex)); } encoder.finish(); NIOUtils.closeQuietly(channel); } private static void encodeAndSaveWithFFMpeg(List<BufferedImage> images, double frameRate, File file, int compression) throws IOException { //save all files String workingDirName = file.getAbsoluteFile().getParentFile().getPath(); String imagesDirName = workingDirName + File.separator + "imgs." + System.currentTimeMillis(); Files.createDirectories(Path.of(imagesDirName)); List<Path> toDeletePaths = new ArrayList<>(); L.fine(String.format("Saving %d files in %s", images.size(), imagesDirName)); for (int i = 0; i < images.size(); i++) { File imageFile = new File(imagesDirName + File.separator + String.format("frame%06d", i) + ".jpg"); ImageIO.write(images.get(i), "jpg", imageFile); toDeletePaths.add(imageFile.toPath()); } toDeletePaths.add(Path.of(imagesDirName)); //invoke ffmpeg String command = String.format( "ffmpeg -y -r %d -i %s/frame%%06d.jpg -vcodec libx264 -crf %d -pix_fmt yuv420p %s", (int) Math.round(frameRate), imagesDirName, compression, file.getPath() ); L.fine(String.format("Running: %s", command)); ProcessBuilder pb = new ProcessBuilder(command.split(" ")); pb.directory(new File(workingDirName)); StringBuilder sb = new StringBuilder(); try { Process process = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); int exitVal = process.waitFor(); if (exitVal < 0) { throw new IOException(String.format("Unexpected exit val: %d. Full output is:%n%s", exitVal, sb.toString())); } } catch (IOException | InterruptedException e) { throw (e instanceof IOException) ? (IOException) e : (new IOException(e)); } finally { //delete all files L.fine(String.format("Deleting %d paths", toDeletePaths.size())); for (Path path : toDeletePaths) { try { Files.delete(path); } catch (IOException e) { L.log(Level.WARNING, String.format("Cannot delete %s", path), e); } } } } }
4,464
35.598361
140
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/viewers/GridSnapshotListener.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.viewers; import it.units.erallab.hmsrobots.core.snapshots.SnapshotListener; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public interface GridSnapshotListener { SnapshotListener listener(int x, int y); }
1,009
33.827586
98
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/viewers/FramesImageBuilder.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.viewers; import it.units.erallab.hmsrobots.core.geometry.BoundingBox; import it.units.erallab.hmsrobots.core.snapshots.Snapshot; import it.units.erallab.hmsrobots.core.snapshots.SnapshotListener; import it.units.erallab.hmsrobots.viewers.drawers.Drawer; import java.awt.*; import java.awt.image.BufferedImage; import java.util.logging.Logger; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class FramesImageBuilder implements SnapshotListener { public enum Direction { HORIZONTAL, VERTICAL } private final double initialT; private final double finalT; private final double dT; private final int w; private final int h; private final Direction direction; private final Drawer drawer; private final BufferedImage image; private final int nOfFrames; private int frameCount; private double lastT = Double.NEGATIVE_INFINITY; private static final Logger L = Logger.getLogger(FramesImageBuilder.class.getName()); public FramesImageBuilder(double initialT, double finalT, double dT, int w, int h, Direction direction, Drawer drawer) { this.initialT = initialT; this.finalT = finalT; this.dT = dT; this.w = w; this.h = h; this.direction = direction; this.drawer = drawer; nOfFrames = (int) Math.ceil((finalT - initialT) / dT); int overallW = w; int overallH = h; if (direction.equals(Direction.HORIZONTAL)) { overallW = w * nOfFrames; } else { overallH = h * nOfFrames; } image = new BufferedImage(overallW, overallH, BufferedImage.TYPE_3BYTE_BGR); frameCount = 0; } public BufferedImage getImage() { return image; } @Override public void listen(double t, Snapshot snapshot) { if ((t < initialT) || (t >= finalT)) { //out of time window return; } if ((t - lastT) < dT) { //wait for next snapshot return; } lastT = t; BoundingBox imageFrame; if (direction.equals(Direction.HORIZONTAL)) { imageFrame = BoundingBox.of((double) frameCount / (double) nOfFrames, 0, (double) (frameCount + 1) / (double) nOfFrames, 1d); } else { imageFrame = BoundingBox.of(0, (double) frameCount / (double) nOfFrames, 1, (double) (frameCount + 1) / (double) nOfFrames); } L.info(String.format("Rendering frame %d on %s", frameCount, imageFrame)); frameCount = frameCount + 1; Graphics2D g = image.createGraphics(); g.setClip(0, 0, image.getWidth(), image.getHeight()); Drawer.clip(imageFrame, drawer).draw(t, snapshot, g); g.dispose(); } }
3,331
31.666667
131
java
null
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/hmsrobots/viewers/GridMultipleEpisodesRunner.java
/* * Copyright (C) 2021 Eric Medvet <eric.medvet@gmail.com> (as Eric Medvet <eric.medvet@gmail.com>) * * 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/>. */ package it.units.erallab.hmsrobots.viewers; import it.units.erallab.hmsrobots.tasks.Task; import it.units.erallab.hmsrobots.util.Grid; import it.units.erallab.hmsrobots.util.SerializationUtils; import org.apache.commons.lang3.tuple.Pair; import java.io.Flushable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; /** * @author Eric Medvet <eric.medvet@gmail.com> */ public class GridMultipleEpisodesRunner<S> implements Runnable { static { try { LogManager.getLogManager().readConfiguration(GridMultipleEpisodesRunner.class.getClassLoader().getResourceAsStream("logging.properties")); } catch (IOException | SecurityException ex) { //ignore } } private final Grid<Pair<S, Task<S, ?>>> solutionsGrid; private final GridSnapshotListener gridSnapshotListener; private final ExecutorService executor; private static final Logger L = Logger.getLogger(GridMultipleEpisodesRunner.class.getName()); public GridMultipleEpisodesRunner(Grid<Pair<S, Task<S, ?>>> solutionsGrid, GridSnapshotListener gridSnapshotListener, ExecutorService executor) { this.solutionsGrid = solutionsGrid; this.executor = executor; this.gridSnapshotListener = gridSnapshotListener; } @Override public void run() { //start episodes List<Future<?>> results = new ArrayList<>(); solutionsGrid.stream() .forEach(entry -> results.add(executor.submit(() -> { L.fine(String.format("Starting %s in position (%d,%d)", entry.getValue().getClass().getSimpleName(), entry.getX(), entry.getY())); S solution = entry.getValue().getLeft(); Task<S, ?> task = entry.getValue().getRight(); Object outcome = task.apply(SerializationUtils.clone(solution), gridSnapshotListener.listener(entry.getX(), entry.getY())); L.fine(String.format("Ended %s in position (%d,%d) with outcome %s", entry.getValue().getClass().getSimpleName(), entry.getX(), entry.getY(), outcome)); }))); //wait for results for (Future<?> result : results) { try { result.get(); } catch (InterruptedException | ExecutionException ex) { ex.printStackTrace(); //L.log(Level.SEVERE, String.format("Cannot obtain one result due to %s", ex), ex); } } //flush and write if (gridSnapshotListener instanceof Flushable) { try { L.finer(String.format("Flushing with %s", gridSnapshotListener.getClass().getSimpleName())); ((Flushable) gridSnapshotListener).flush(); L.finer("Flushed"); } catch (IOException e) { L.log(Level.SEVERE, String.format("Cannot flush video due to %s", e), e); } } } }
3,680
37.747368
162
java