本文整理匯總了Java中org.apache.commons.math3.random.MersenneTwister類的典型用法代碼示例。如果您正苦於以下問題:Java MersenneTwister類的具體用法?Java MersenneTwister怎麽用?Java MersenneTwister使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
MersenneTwister類屬於org.apache.commons.math3.random包,在下文中一共展示了MersenneTwister類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testDifference
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
/**
* Test if two clusters are significantly different in the metrics we look at for balancing.
*
* @param orig the utilization matrix from the original cluster
* @param optimized the utilization matrix from the optimized cluster
* @return The P value that the various derived resources come from the same probability distribution. The probability
* that the null hypothesis is correct.
*/
public static double[] testDifference(double[][] orig, double[][] optimized) {
int nResources = RawAndDerivedResource.values().length;
if (orig.length != nResources) {
throw new IllegalArgumentException("orig must have number of rows equal to RawAndDerivedResource.");
}
if (optimized.length != nResources) {
throw new IllegalArgumentException("optimized must have number of rows equal to RawAndDerivedResource.");
}
if (orig[0].length != optimized[0].length) {
throw new IllegalArgumentException("The number of brokers must be the same.");
}
double[] pValues = new double[orig.length];
//TODO: For small N we want to do statistical bootstrapping (not the same as bootstrapping data).
for (int resourceIndex = 0; resourceIndex < nResources; resourceIndex++) {
RandomGenerator rng = new MersenneTwister(0x5d11121018463324L);
KolmogorovSmirnovTest kolmogorovSmirnovTest = new KolmogorovSmirnovTest(rng);
pValues[resourceIndex] =
kolmogorovSmirnovTest.kolmogorovSmirnovTest(orig[resourceIndex], optimized[resourceIndex]);
}
return pValues;
}
示例2: extract
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
/**
* Randomly extracts sequences with limited total length.
* @param sequenceLength0Upper
* @param random
* @param sequence
* @return
*/
public static Pair<ArrayList<Sequence>, ArrayList<Sequence>> extract(int sequenceLength0Upper, MersenneTwister random, List<Sequence> sequence)
{
ArrayList<Sequence> all=sequence.stream().collect(CollectionUtils.arrayListCollector());
all=RandomUtils.permutation(all, random);
int length=0;
int num0=0;
while(num0<all.size())
{
int len=all.get(num0).getLength();
if(length+len>=sequenceLength0Upper) break;
++num0;
length+=len;
}
ArrayList<Sequence> sequence0=all.subList(0, num0).stream().collect(CollectionUtils.arrayListCollector());
ArrayList<Sequence> sequence1=all.subList(num0, all.size()).stream().collect(CollectionUtils.arrayListCollector());
return new Pair<>(sequence0, sequence1);
}
示例3: create
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
/**
* Creates {@link BatchData} by loading wave files and converting them into spectrograms.
*
* @param numLowerLabel Number of sub-divisions in a single element.
* @param silentLabelFunc A converter from the number of labels and sub-divisions to the index for the silent label.
* @param finalInputHeight Input height of the spectrogram, seen from the final output layer.
* @param waveFileDir Directory of wave files.
* @param stftParam Parameters for short time Fourier transformation.
* @param dpssParam Parameter for discrete prolate spheroidal sequences.
* @param freqOffset Beginning of the frequency band.
* @param freqLength Length of the frequency band.
* @param spectrogramMeanSd Mean and SD of the spectrograms in the training data. Used for input scaling.
* @param inputHeightUpper Upper value of the combined input spectrogram.
* @return
* @throws IOException
* @throws UnsupportedAudioFileException
* @throws NotConvergedException
*/
public static BatchData create(List<Sequence> sequence, MersenneTwister random, int numLowerLabel, IntBinaryOperator silentLabelFunc, int finalInputHeight, Path waveFileDir, STFTParam stftParam, int dpssParam, int freqOffset, int freqLength, double[] spectrogramMeanSd, int inputHeightUpper) throws IOException, UnsupportedAudioFileException, NotConvergedException
{
int marginBegin=finalInputHeight/2;
int marginEnd=finalInputHeight/2-1;
HashMap<Sequence, WavePosition> wavePosition=Sequence.wavePositionMap(sequence, waveFileDir);
for(WavePosition wp: wavePosition.values())
{
int waveBegin=wp.getPosition()-marginBegin*stftParam.getShiftLength();
int waveEnd=wp.getEnd()+marginEnd*stftParam.getShiftLength();
wp.setPosition(waveBegin);
wp.setLength(waveEnd-waveBegin);
}
HashMap<Sequence, float[]> spectrogram=SoundUtils.spectrogram(wavePosition, stftParam, dpssParam, freqOffset, freqLength);
SoundUtils.whiteSpectrogram(spectrogram.values(), spectrogramMeanSd[0], spectrogramMeanSd[1]);
ArrayList<float[]> spectrogramList=sequence.stream().map(s->spectrogram.get(s)).collect(Collectors.toCollection(ArrayList::new));
ArrayList<ArrayList<Integer>> packedSpectrogram=packedSpectrogramIndex(inputHeightUpper, spectrogramList, random, freqLength);
int packedHeight=packedSpectrogram.stream()
.mapToInt(spec->spec.stream().mapToInt(s->spectrogram.get(sequence.get(s)).length/freqLength).sum())
.max().getAsInt();
return new BatchData(spectrogramList, packedHeight, packedSpectrogram, sequence, numLowerLabel, silentLabelFunc, marginBegin, marginEnd, finalInputHeight, stftParam);
}
示例4: test1
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
@Test
public void test1() {
IFeatureCollection<IFeature> featColl = ShapefileReader
.read(getClass().getClassLoader().getResource("parcelDecomposition/parcelle.shp").toString());
IPolygon pol = (IPolygon) FromGeomToSurface.convertGeom(featColl.get(0).getGeom()).get(0);
double maximalArea = 100;
double maximalWidth = 20;
RandomGenerator rng = new MersenneTwister(42);
double epsilon = 0;
double noise = 10;
OBBBlockDecomposition obb = new OBBBlockDecomposition(pol, maximalArea, maximalWidth, rng, epsilon, noise);
try {
IFeatureCollection<IFeature> featCOut = obb.decompParcel();
assertNotNull(featCOut);
assertTrue(! featCOut.isEmpty());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
assertTrue(false);
}
}
示例5: getCenterMostPoint
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
/**
* Returns the point closest to the exact center of the area spanned by the
* graph.
* @param graph The graph.
* @return The point of the graph closest to the exact center of the area
* spanned by the graph.
*/
private Point getCenterMostPoint(Graph<?> graph) {
final ImmutableList<Point> extremes = Graphs.getExtremes(graph);
final Point exactCenter =
Point.divide(Point.add(extremes.get(0), extremes.get(1)), 2d);
Point center = graph.getRandomNode(new MersenneTwister());
double distance = Point.distance(center, exactCenter);
for (final Point p : graph.getNodes()) {
final double pDistance = Point.distance(p, exactCenter);
if (pDistance < distance) {
center = p;
distance = pDistance;
}
if (center.equals(exactCenter)) {
return center;
}
}
return center;
}
示例6: main
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
public static void main(String[] args) {
if (args.length != 5) {
System.err.println(usage());
System.exit(1);
}
try {
final Supplier<Agent> AGENT = createAgentFactoryByReflection(new File(args[0]), args[1]);
final int REPEATS = Integer.parseInt(args[2]);
final Duration ACTION_TIME_LIMIT = Duration.ofNanos((int) (Double.parseDouble(args[3]) * 1000 * 1000));
final long RANDOM_SEED = Long.parseLong(args[4]);
RandomDataGenerator random = new RandomDataGenerator(new MersenneTwister(RANDOM_SEED));
MultipleGamesResult result = new Game(ACTION_TIME_LIMIT).playMultiple(AGENT, REPEATS, random);
System.out.println(result.toCvsRow());
} catch (Exception e) {
System.err.println(e.toString());
System.err.println();
System.err.println(usage());
System.exit(1);
}
}
示例7: Model
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
/**
* @param configFileName String with the address of the configuration file
* @param outputFolder String with the address of the folder for storing results
*/
public Model(String configFileName, String outputFolder) {
// TODO: Check that random numbers are working properly!
config = new Config(configFileName);
rand = new MersenneTwister(config.SEED);
government = new Government();
demographics = new Demographics();
construction = new Construction();
centralBank = new CentralBank();
bank = new Bank();
households = new ArrayList<>(config.TARGET_POPULATION*2);
houseSaleMarket = new HouseSaleMarket();
houseRentalMarket = new HouseRentalMarket();
recorder = new collectors.Recorder(outputFolder);
transactionRecorder = new collectors.MicroDataRecorder(outputFolder);
creditSupply = new collectors.CreditSupply(outputFolder);
coreIndicators = new collectors.CoreIndicators();
householdStats = new collectors.HouseholdStats();
housingMarketStats = new collectors.HousingMarketStats(houseSaleMarket);
rentalMarketStats = new collectors.RentalMarketStats(housingMarketStats, houseRentalMarket);
nSimulation = 0;
}
示例8: main
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
/**
* Starts the demo.
* @param args No args.
*/
public static void main(String[] args) {
final String string = "AgentWise";
final List<Point> points = measureString(string, 30, 30, 0);
final RandomGenerator rng = new MersenneTwister(123);
final Simulator sim = new Simulator(rng, Measure.valueOf(1000L,
SI.MILLI(SI.SECOND)));
sim.register(new PlaneRoadModel(new Point(0, 0), new Point(4500, 1200),
SI.METER, Measure.valueOf(1000d, NonSI.KILOMETERS_PER_HOUR)));
sim.configure();
for (final Point p : points) {
sim.register(new Vehicle(p, rng));
}
View.create(sim)
.with(new PlaneRoadModelRenderer(), new VehicleRenderer(),
new DemoPanel(string, rng)).show();
}
示例9: BeaconTruck
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
public BeaconTruck(VehicleDTO pDto, int seed,
double beaconRadius, double commRadius, double commReliability,
SchedulingStrategy pickupStrategy, SchedulingStrategy deliveryStrategy,
boolean doExchange) {
super(pDto);
this.beaconRadius = beaconRadius;
this.commReliability = commReliability;
this.commRadius = commRadius;
this.doExchange = doExchange;
this.messageStore = new MessageStore();
this.pickupQueue = new ArrayList<BeaconParcel>();
this.auctionActivity = new AuctionActivity(this, messageStore);
this.fetchActivity = new FetchActivity(this, pickupStrategy);
this.transportActivity = new TransportActivity(this, deliveryStrategy);
this.exchangeActivity = new ExchangeActivity(this,messageStore);
this.pickupActivity = new PickupActivity(this);
this.deliverActivity = new DeliverActivity(this);
this.discoverActivity = new DiscoverActivity(auctionActivity, this);
this.exploreActivity = new ExploreActivity(this, new MersenneTwister(seed));
this.setBeaconStatus(BeaconStatus.ACTIVE);
}
示例10: drawMnist
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
public static void drawMnist(DataSet mnist,INDArray reconstruct) throws InterruptedException {
for(int j = 0; j < mnist.numExamples(); j++) {
INDArray draw1 = mnist.get(j).getFeatureMatrix().mul(255);
INDArray reconstructed2 = reconstruct.getRow(j);
INDArray draw2 = Sampling.binomial(reconstructed2, 1, new MersenneTwister(123)).mul(255);
DrawReconstruction d = new DrawReconstruction(draw1);
d.title = "REAL";
d.draw();
DrawReconstruction d2 = new DrawReconstruction(draw2,1000,1000);
d2.title = "TEST";
d2.draw();
Thread.sleep(1000);
d.frame.dispose();
d2.frame.dispose();
}
}
示例11: configure
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
@Override
protected void configure() {
// Network API
bind(Network.class).to(FastNetwork.class);
bind(DynamicNetwork.class).to(DynamicFastNetwork.class);
// NetworkModel API
bind(Configuration.class).to(PropertiesConfiguration.class);
bind(RandomGenerator.class).to(MersenneTwister.class);
bind(BAModel.class).to(DefaultBAModel.class);
bind(BAForestModel.class).to(DefaultBAForestModel.class);
bind(KRegularModel.class).to(DefaultKRegularModel.class);
bind(ERModel.class).to(EERModel.class);
bind(GilbertModel.class).to(EGilberModel.class);
bind(WSModel.class).to(DefaultWSModel.class);
}
示例12: testRandomNode
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
@Test
public void testRandomNode() {
RandomGenerator random = new MersenneTwister(0);
HashMap<Integer, Integer> count = new HashMap<>();
int numNodes = 10;
int[] exclude = { 1, 2, 3, 4, 5};
for (int i = 0; i < 100000; i++) {
int randomN = NetworkModelUtils.getRandomNode(random, numNodes,
exclude);
if (count.containsKey(randomN)) {
count.put(randomN, (count.get(randomN) + 1));
} else {
count.put(randomN, 1);
}
for (int e : exclude) {
assertNotSame(e, randomN);
}
}
for(int k: count.keySet()){
System.out.println("node: "+k+" c: "+count.get(k));
}
}
示例13: packedSpectrogramIndex
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
private static ArrayList<ArrayList<Integer>> packedSpectrogramIndex(int heightUpper, List<float[]> spectrogram, MersenneTwister random, int inputWidth)
{
int[] shuffleSpectrogram;
if(random!=null) shuffleSpectrogram=RandomUtils.permutation(spectrogram.size(), random);
else shuffleSpectrogram=ArrayUtils.createSequence(0, spectrogram.size());
ArrayList<int[]> dataHeight=new ArrayList<int[]>();
HashMap<Integer, LinkedList<Integer>> inputSpec=new HashMap<>();
for(int s: shuffleSpectrogram)
{
float[] spec=spectrogram.get(s);
int specHeight=spec.length/inputWidth;
int[] minHeight=null;
if(dataHeight.size()>0) minHeight=Collections.min(dataHeight, (o1, o2)->o1[1]-o2[1]);
if(dataHeight.size()>0 && heightUpper-minHeight[1]>=specHeight)
{
minHeight[1]+=specHeight;
inputSpec.putIfAbsent(minHeight[0], new LinkedList<>());
inputSpec.get(minHeight[0]).add(s);
}
else
{
inputSpec.putIfAbsent(dataHeight.size(), new LinkedList<>());
inputSpec.get(dataHeight.size()).add(s);
dataHeight.add(new int[]{dataHeight.size(), specHeight});
}
}
ArrayList<ArrayList<Integer>> packedIndex=new ArrayList<>(inputSpec.size());
for(int packed=0; packed<inputSpec.size(); ++packed) packedIndex.add(new ArrayList<Integer>(inputSpec.get(packed)));
return packedIndex;
}
示例14: batch
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
/**
* Makes batch inputs.
* This method must be called before training or recognition with a DNN.
* @param maxBatchSize
* @param randomShuffle
* @param inputWidth
* @throws IOException
*/
public void batch(int maxBatchSize, MersenneTwister randomShuffle, int inputWidth) throws IOException
{
this.maxBatchSize=maxBatchSize;
numBatch=MathUtils.ceil(inputData.size(), maxBatchSize);
batchData=new ArrayList<>(numBatch);
batchLabel=new ArrayList<>(numBatch);
int[] shuffleInput;
if(randomShuffle!=null) shuffleInput=RandomUtils.permutation(inputData.size(), randomShuffle);
else shuffleInput=ArrayUtils.createSequence(0, inputData.size());
packBatchIndex=new ArrayList<int[]>();
for(int p=0; p<inputData.size(); ++p) packBatchIndex.add(null);
for(int b=0; b<numBatch; ++b)
{
batchData.add(new ArrayList<float[]>(maxBatchSize));
batchLabel.add(new byte[labelHeight*maxBatchSize]);
for(int i=0; i<maxBatchSize; ++i)
{
int in=i*numBatch+b;
if(in<inputData.size())
{
int si=shuffleInput[in];
batchData.get(b).add(inputData.get(si));
System.arraycopy(inputLabel.get(si), 0, batchLabel.get(b), i*labelHeight, labelHeight);
packBatchIndex.set(si, new int[]{b, i});
}
else
{
for(int i1=i; i1<maxBatchSize; ++i1) batchData.get(b).add(new float[packedHeight*inputWidth]);
Arrays.fill(batchLabel.get(b), i*packedHeight, batchLabel.get(b).length, (byte)-1);
break;
}
}
}
}
示例15: initParam
import org.apache.commons.math3.random.MersenneTwister; //導入依賴的package包/類
/**
* Initializes network parameters according to http://arxiv.org/abs/1502.01852.
* @see http://arxiv.org/abs/1502.01852
* @param layer
* @param random
*/
public static void initParam(List<Layer> layer, MersenneTwister random)
{
for(Layer la: layer) if(la instanceof ParamLayer)
{
int size=0;
ConvLayer cl=(ConvLayer)la;
size=cl.getLower().getNumChannel()*cl.getFilterHeight()*cl.getFilterHeight();
double scale=Math.sqrt(2.0/size);
for(int i=0; i<cl.getWeightF().length; ++i) cl.getWeightF()[i]=(float)(random.nextGaussian()*scale);
for(int i=0; i<cl.getBiasF().length; ++i) cl.getBiasF()[i]=0;
}
}