List of usage examples for java.util.stream IntStream range
public static IntStream range(int startInclusive, int endExclusive)
From source file:com.simiacryptus.mindseye.applications.ObjectLocationBase.java
/** * Run.//from w w w .j a va 2 s . co m * * @param log the log */ public void run(@Nonnull final NotebookOutput log) { // @Nonnull String logName = "cuda_" + log.getName() + ".log"; // log.p(log.file((String) null, logName, "GPU Log")); // CudaSystem.addLog(new PrintStream(log.file(logName))); ImageClassifierBase classifier = getClassifierNetwork(); Layer classifyNetwork = classifier.getNetwork(); ImageClassifierBase locator = getLocatorNetwork(); Layer locatorNetwork = locator.getNetwork(); ArtistryUtil.setPrecision((DAGNetwork) classifyNetwork, Precision.Float); ArtistryUtil.setPrecision((DAGNetwork) locatorNetwork, Precision.Float); Tensor[][] inputData = loadImages_library(); // Tensor[][] inputData = loadImage_Caltech101(log); double alphaPower = 0.8; final AtomicInteger index = new AtomicInteger(0); Arrays.stream(inputData).limit(10).forEach(row -> { log.h3("Image " + index.getAndIncrement()); final Tensor img = row[0]; log.p(log.image(img.toImage(), "")); Result classifyResult = classifyNetwork.eval(new MutableResult(row)); Result locationResult = locatorNetwork.eval(new MutableResult(row)); Tensor classification = classifyResult.getData().get(0); List<CharSequence> categories = classifier.getCategories(); int[] sortedIndices = IntStream.range(0, categories.size()).mapToObj(x -> x) .sorted(Comparator.comparing(i -> -classification.get(i))).mapToInt(x -> x).limit(10).toArray(); logger.info(Arrays.stream(sortedIndices) .mapToObj( i -> String.format("%s: %s = %s%%", i, categories.get(i), classification.get(i) * 100)) .reduce((a, b) -> a + "\n" + b).orElse("")); LinkedHashMap<CharSequence, Tensor> vectors = new LinkedHashMap<>(); List<CharSequence> predictionList = Arrays.stream(sortedIndices).mapToObj(categories::get) .collect(Collectors.toList()); Arrays.stream(sortedIndices).limit(6).forEach(category -> { CharSequence name = categories.get(category); log.h3(name); Tensor alphaTensor = renderAlpha(alphaPower, img, locationResult, classification, category); log.p(log.image(img.toRgbImageAlphaMask(0, 1, 2, alphaTensor), "")); vectors.put(name, alphaTensor.unit()); }); Tensor avgDetection = vectors.values().stream().reduce((a, b) -> a.add(b)).get() .scale(1.0 / vectors.size()); Array2DRowRealMatrix covarianceMatrix = new Array2DRowRealMatrix(predictionList.size(), predictionList.size()); for (int x = 0; x < predictionList.size(); x++) { for (int y = 0; y < predictionList.size(); y++) { Tensor l = vectors.get(predictionList.get(x)); Tensor r = vectors.get(predictionList.get(y)); covarianceMatrix.setEntry(x, y, null == l || null == r ? 0 : (l.minus(avgDetection)).dot(r.minus(avgDetection))); } } @Nonnull final EigenDecomposition decomposition = new EigenDecomposition(covarianceMatrix); for (int objectVector = 0; objectVector < 10; objectVector++) { log.h3("Eigenobject " + objectVector); double eigenvalue = decomposition.getRealEigenvalue(objectVector); RealVector eigenvector = decomposition.getEigenvector(objectVector); Tensor detectionRegion = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> { Tensor tensor = vectors.get(predictionList.get(i)); return null == tensor ? null : tensor.scale(eigenvector.getEntry(i)); }).filter(x -> null != x).reduce((a, b) -> a.add(b)).get(); detectionRegion = detectionRegion.scale(255.0 / detectionRegion.rms()); CharSequence categorization = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> { CharSequence category = predictionList.get(i); double component = eigenvector.getEntry(i); return String.format("<li>%s = %.4f</li>", category, component); }).reduce((a, b) -> a + "" + b).get(); log.p(String.format("Object Detected: <ol>%s</ol>", categorization)); log.p("Object Eigenvalue: " + eigenvalue); log.p("Object Region: " + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion), "")); log.p("Object Region Compliment: " + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion.scale(-1)), "")); } // final int[] orderedVectors = IntStream.range(0, 10).mapToObj(x -> x) // .sorted(Comparator.comparing(x -> -decomposition.getRealEigenvalue(x))).mapToInt(x -> x).toArray(); // IntStream.range(0, orderedVectors.length) // .mapToObj(i -> { // //double realEigenvalue = decomposition.getRealEigenvalue(orderedVectors[i]); // return decomposition.getEigenvector(orderedVectors[i]).toArray(); // } // ).toArray(i -> new double[i][]); log.p(String.format( "<table><tr><th>Cosine Distance</th>%s</tr>%s</table>", Arrays.stream(sortedIndices).limit(10) .mapToObj(col -> "<th>" + categories.get(col) + "</th>").reduce((a, b) -> a + b).get(), Arrays.stream(sortedIndices).limit(10).mapToObj(r -> { return String.format("<tr><td>%s</td>%s</tr>", categories.get(r), Arrays.stream(sortedIndices).limit(10).mapToObj(col -> { Tensor l = vectors.get(categories.get(r)); Tensor r2 = vectors.get(categories.get(col)); return String.format("<td>%.4f</td>", (null == l || null == r2) ? 0 : Math.acos(l.dot(r2))); }).reduce((a, b) -> a + b).get()); }).reduce((a, b) -> a + b).orElse(""))); }); log.setFrontMatterProperty("status", "OK"); }
From source file:Fasta.java
private static List<CharSequence> splitFasta2(String[] seq, int length) { List<CharSequence> collect = IntStream.range(0, length).mapToObj(start -> { List<CharSequence> primers = new ArrayList<>(); for (int i = start; i < seq[0].length() - length; i += length) { CharSequence s = seq[0].substring(i, i + length); primers.add(s);/* www .j ava 2s . co m*/ } return primers; }).flatMap((i) -> i.stream()).collect(Collectors.toList()); List<CharSequence> collect2 = IntStream.range(0, length).mapToObj(start -> { List<CharSequence> primers = new ArrayList<>(); for (int i = start; i < seq[1].length() - length; i += length) { CharSequence s = seq[1].substring(i, i + length); primers.add(s); } return primers; }).flatMap((i) -> i.stream()).collect(Collectors.toList()); collect.addAll(collect2); return collect; }
From source file:org.lightjason.agentspeak.action.buildin.math.linearprogram.CEquationConstraint.java
@Override public final IFuzzyValue<Boolean> execute(final IContext p_context, final boolean p_parallel, final List<ITerm> p_argument, final List<ITerm> p_return, final List<ITerm> p_annotation) { final List<ITerm> l_arguments = CCommon.flatcollection(p_argument).collect(Collectors.toList()); // first search the relation symbol and create splitting lists final int l_index = IntStream.range(1, l_arguments.size()).boxed() .mapToInt(i -> CCommon.rawvalueAssignableTo(l_arguments.get(i), String.class) ? i : -1) .filter(i -> i > -1).findFirst().orElseThrow(() -> new CIllegalArgumentException( org.lightjason.agentspeak.common.CCommon.languagestring(this, "relation"))); // create linear constraint based on an equation l_arguments.get(0).<Pair<LinearObjectiveFunction, Collection<LinearConstraint>>>raw().getRight() .add(new LinearConstraint( // c_i values l_arguments.stream().limit(l_index - 2).skip(1) .mapToDouble(i -> i.<Number>raw().doubleValue()).toArray(), // c_const value l_arguments.get(l_index - 1).<Number>raw().doubleValue(), // relation symbol this.getRelation(p_argument.get(l_index).<String>raw()), // r_i values l_arguments.stream().skip(l_index + 2).mapToDouble(i -> i.<Number>raw().doubleValue()) .toArray(),// w w w . ja v a2s . co m // r_const value l_arguments.get(p_argument.size() - 1).<Number>raw().doubleValue())); return CFuzzyValue.from(true); }
From source file:edu.cmu.lti.oaqa.baseqa.providers.ml.classifiers.LibSvmProvider.java
@Override public Map<String, Double> infer(Map<String, Double> features) { svm_node[] x = IntStream.range(1, fid2feat.size() + 1).mapToObj(j -> { svm_node node = new svm_node(); node.index = j;/*from w w w.j av a 2 s . c o m*/ node.value = features.getOrDefault(fid2feat.get(j), 0.0); return node; }).toArray(svm_node[]::new); double[] values = new double[lid2label.size()]; svm.svm_predict_values(model, x, values); int[] lids = new int[lid2label.size()]; svm.svm_get_labels(model, lids); return IntStream.range(0, values.length).boxed() .collect(toMap(i -> lid2label.get(lids[i]), i -> values[i])); }
From source file:com.github.mrenou.jacksonatic.internal.AnnotatedClassLogger.java
private static boolean hasAnnotationOrParameterAnnotation(AnnotatedWithParams annotatedWithParams) { return hasAnnotation(annotatedWithParams.annotations()) || IntStream .range(0, annotatedWithParams.getParameterCount()) .mapToObj(index -> annotatedWithParams.getParameterAnnotations(index)).reduce(false, (acc, annotationMap) -> acc | hasAnnotation(annotationMap), (acc1, acc2) -> acc1 | acc2); }
From source file:nl.rivm.cib.episim.model.disease.infection.MSEIRSPlot.java
@Override public void start(final Stage stage) { final SIRConfig conf = ConfigFactory.create(SIRConfig.class); final double[] t = conf.t(); final long[] pop = conf.population(); final double n0 = Arrays.stream(pop).sum(); final String[] colors = conf.colors(), colors2 = conf.colors2(); final Pane plot = new Pane(); plot.setPrefSize(400, 300);/*ww w . ja v a2s . com*/ plot.setMinSize(50, 50); final NumberAxis xAxis = new NumberAxis(t[0], t[1], (t[1] - t[0]) / 10); final NumberAxis yAxis = new NumberAxis(0, n0, n0 / 10); final Pane axes = new Pane(); axes.prefHeightProperty().bind(plot.heightProperty()); axes.prefWidthProperty().bind(plot.widthProperty()); xAxis.setSide(Side.BOTTOM); xAxis.setMinorTickVisible(false); xAxis.setPrefWidth(axes.getPrefWidth()); xAxis.prefWidthProperty().bind(axes.widthProperty()); xAxis.layoutYProperty().bind(axes.heightProperty()); yAxis.setSide(Side.LEFT); yAxis.setMinorTickVisible(false); yAxis.setPrefHeight(axes.getPrefHeight()); yAxis.prefHeightProperty().bind(axes.heightProperty()); yAxis.layoutXProperty().bind(Bindings.subtract(1, yAxis.widthProperty())); axes.getChildren().setAll(xAxis, yAxis); final Label lbl = new Label(String.format("R0=%.1f, recovery=%.1ft\nSIR(0)=%s", conf.reproduction(), conf.recovery(), Arrays.toString(pop))); lbl.setTextAlignment(TextAlignment.CENTER); lbl.setTextFill(Color.WHITE); final Path[] deterministic = { new Path(), new Path(), new Path() }; IntStream.range(0, pop.length).forEach(i -> { final Color color = Color.valueOf(colors[i]); final Path path = deterministic[i]; path.setStroke(color.deriveColor(0, 1, 1, 0.6)); path.setStrokeWidth(2); path.setClip(new Rectangle(0, 0, plot.getPrefWidth(), plot.getPrefHeight())); }); plot.getChildren().setAll(axes); // fill paths with integration estimates final double xl = xAxis.getLowerBound(), sx = plot.getPrefWidth() / (xAxis.getUpperBound() - xl), yh = plot.getPrefHeight(), sy = yh / (yAxis.getUpperBound() - yAxis.getLowerBound()); final TreeMap<Double, Integer> iDeterministic = new TreeMap<>(); MSEIRSTest.deterministic(conf, () -> new DormandPrince853Integrator(1.0E-8, 10, 1.0E-20, 1.0E-20)) .subscribe(yt -> { iDeterministic.put(yt.getKey(), deterministic[0].getElements().size()); final double[] y = yt.getValue(); final double x = (yt.getKey() - xl) * sx; for (int i = 0; i < y.length; i++) { final double yi = yh - y[i] * sy; final PathElement di = deterministic[i].getElements().isEmpty() ? new MoveTo(x, yi) : new LineTo(x, yi); deterministic[i].getElements().add(di); } }, e -> LOG.error("Problem", e), () -> plot.getChildren().addAll(deterministic)); final Path[] stochasticTau = { new Path(), new Path(), new Path() }; IntStream.range(0, pop.length).forEach(i -> { final Color color = Color.valueOf(colors[i]); final Path path = stochasticTau[i]; path.setStroke(color); path.setStrokeWidth(1); path.setClip(new Rectangle(0, 0, plot.getPrefWidth(), plot.getPrefHeight())); }); final TreeMap<Double, Integer> iStochasticTau = new TreeMap<>(); MSEIRSTest.stochasticGillespie(conf).subscribe(yt -> { final double x = (yt.getKey() - xl) * sx; iStochasticTau.put(yt.getKey(), stochasticTau[0].getElements().size()); final long[] y = yt.getValue(); for (int i = 0; i < y.length; i++) { final double yi = yh - y[i] * sy; final ObservableList<PathElement> path = stochasticTau[i].getElements(); if (path.isEmpty()) { path.add(new MoveTo(x, yi)); // first } else { final PathElement last = path.get(path.size() - 1); final double y_prev = last instanceof MoveTo ? ((MoveTo) last).getY() : ((LineTo) last).getY(); path.add(new LineTo(x, y_prev)); path.add(new LineTo(x, yi)); } } }, e -> LOG.error("Problem", e), () -> plot.getChildren().addAll(stochasticTau)); final Path[] stochasticRes = { new Path(), new Path(), new Path() }; IntStream.range(0, pop.length).forEach(i -> { final Color color = Color.valueOf(colors2[i]); final Path path = stochasticRes[i]; path.setStroke(color); path.setStrokeWidth(1); path.setClip(new Rectangle(0, 0, plot.getPrefWidth(), plot.getPrefHeight())); }); final TreeMap<Double, Integer> iStochasticRes = new TreeMap<>(); MSEIRSTest.stochasticSellke(conf).subscribe(yt -> { final double x = (yt.getKey() - xl) * sx; iStochasticRes.put(yt.getKey(), stochasticRes[0].getElements().size()); final long[] y = yt.getValue(); for (int i = 0; i < y.length; i++) { final double yi = yh - y[i] * sy; final ObservableList<PathElement> path = stochasticRes[i].getElements(); if (path.isEmpty()) { path.add(new MoveTo(x, yi)); // first } else { final PathElement last = path.get(path.size() - 1); final double y_prev = last instanceof MoveTo ? ((MoveTo) last).getY() : ((LineTo) last).getY(); path.add(new LineTo(x, y_prev)); path.add(new LineTo(x, yi)); } } }, e -> LOG.error("Problem", e), () -> plot.getChildren().addAll(stochasticRes)); // auto-scale on stage/plot resize // FIXME scaling around wrong origin, use ScatterChart? // xAxis.widthProperty() // .addListener( (ChangeListener<Number>) ( observable, // oldValue, newValue ) -> // { // final double scale = ((Double) newValue) // / plot.getPrefWidth(); // plot.getChildren().filtered( n -> n instanceof Path ) // .forEach( n -> // { // final Path path = (Path) n; // path.setScaleX( scale ); // path.setTranslateX( (path // .getBoundsInParent().getWidth() // - path.getLayoutBounds().getWidth()) // / 2 ); // } ); // } ); // plot.heightProperty() // .addListener( (ChangeListener<Number>) ( observable, // oldValue, newValue ) -> // { // final double scale = ((Double) newValue) // / plot.getPrefHeight(); // plot.getChildren().filtered( n -> n instanceof Path ) // .forEach( n -> // { // final Path path = (Path) n; // path.setScaleY( scale ); // path.setTranslateY( // (path.getBoundsInParent() // .getHeight() * (scale - 1)) // / 2 ); // } ); // } ); final StackPane layout = new StackPane(lbl, plot); layout.setAlignment(Pos.TOP_CENTER); layout.setPadding(new Insets(50)); layout.setStyle("-fx-background-color: rgb(35, 39, 50);"); final Line vertiCross = new Line(); vertiCross.setStroke(Color.SILVER); vertiCross.setStrokeWidth(1); vertiCross.setVisible(false); axes.getChildren().add(vertiCross); final Tooltip tip = new Tooltip(""); tip.setAutoHide(false); tip.hide(); axes.setOnMouseExited(ev -> tip.hide()); axes.setOnMouseMoved(ev -> { final Double x = (Double) xAxis.getValueForDisplay(ev.getX()); if (x > xAxis.getUpperBound() || x < xAxis.getLowerBound()) { tip.hide(); vertiCross.setVisible(false); return; } final Double y = (Double) yAxis.getValueForDisplay(ev.getY()); if (y > yAxis.getUpperBound() || y < yAxis.getLowerBound()) { tip.hide(); vertiCross.setVisible(false); return; } final double xs = xAxis.getDisplayPosition(x); vertiCross.setStartX(xs); vertiCross.setStartY(yAxis.getDisplayPosition(0)); vertiCross.setEndX(xs); vertiCross.setEndY(yAxis.getDisplayPosition(yAxis.getUpperBound())); vertiCross.setVisible(true); final int i = (iDeterministic.firstKey() > x ? iDeterministic.firstEntry() : iDeterministic.floorEntry(x)).getValue(); final Object[] yi = Arrays.stream(deterministic).mapToDouble(p -> getY(p, i)) .mapToObj(yAxis::getValueForDisplay).map(n -> DecimalUtil.toScale(n, 1)).toArray(); final int j = (iStochasticTau.firstKey() > x ? iStochasticTau.firstEntry() : iStochasticTau.floorEntry(x)).getValue(); final Object[] yj = Arrays.stream(stochasticTau).mapToDouble(p -> getY(p, j)) .mapToObj(yAxis::getValueForDisplay).map(n -> DecimalUtil.toScale(n, 0)).toArray(); final int k = (iStochasticRes.firstKey() > x ? iStochasticRes.firstEntry() : iStochasticRes.floorEntry(x)).getValue(); final Object[] yk = Arrays.stream(stochasticRes).mapToDouble(p -> getY(p, k)) .mapToObj(yAxis::getValueForDisplay).map(n -> DecimalUtil.toScale(n, 0)).toArray(); final String txt = String.format("SIR(t=%.1f)\n" + "~det%s\n" + "~tau%s\n" + "~res%s", x, Arrays.toString(yi), Arrays.toString(yj), Arrays.toString(yk)); tip.setText(txt); tip.show(axes, ev.getScreenX() - ev.getSceneX() + xs, ev.getScreenY() + 15); }); try { stage.getIcons().add(new Image(FileUtil.toInputStream("icon.jpg"))); } catch (final IOException e) { LOG.error("Problem", e); } stage.setTitle("Deterministic vs. Stochastic"); stage.setScene(new Scene(layout, Color.rgb(35, 39, 50))); // stage.setOnHidden( ev -> tip.hide() ); stage.show(); }
From source file:cpcc.demo.setup.builder.SquareDemoBuilder.java
/** * @param outputDirectory the output folder. * @throws IOException in case of errors. * @throws JsonProcessingException in case of errors. */// w w w . ja v a 2 s.c om public void write(File outputDirectory) throws IOException, JsonProcessingException { FileUtils.forceMkdir(outputDirectory); List<RealVehicle> rvs = new ArrayList<>(); rvs.add(setUpGroundStation(1)); rvs.addAll(IntStream .range(0, nrCellsWide).mapToObj(x -> IntStream.range(0, nrCellsHigh) .mapToObj(y -> setupRealVehicle(x, y)).collect(Collectors.toList())) .flatMap(List::stream).collect(Collectors.toList())); new GlobalSetupWriter().write(new File(outputDirectory, "db-setup-all.sql"), rvs); rvs.stream().forEach(rethrowConsumer(x -> new RealVehicleBasicWriter(pm.getBasePort()) .write(new File(outputDirectory, "db-setup-" + x.getName() + "-rv.sql"), x))); rvs.stream().forEach(rethrowConsumer(x -> new RealVehicleCameraWriter() .write(new File(outputDirectory, "db-setup-" + x.getName() + "-cam.sql"), x))); }
From source file:io.galeb.router.tests.hostselectors.GuavaConsistentHashTest.java
@SuppressWarnings("unchecked") @Test/*from ww w . j ava 2 s . co m*/ public void checkIfChoiceIsConsistent() { int samples = 10000; int[] keys = new int[] { 1, 13 }; int[][] results = new int[][] { // "numBackends" backends, two cases new int[] { 8, 0, 8, 4 }, new int[] { 0, 3, 5, 7 }, // only one backend new int[] { 0, 0, 0, 0 }, // two backends new int[] { 0, 0, 1, 0 } }; final Map<HashFunction, Integer>[] hashs = new Map[] { ImmutableMap.of(md5(), results[0][0], sipHash24(), results[0][1], murmur3_128(), results[0][2], sha256(), results[0][3]), ImmutableMap.of(md5(), results[1][0], sipHash24(), results[1][1], murmur3_128(), results[1][2], sha256(), results[1][3]), ImmutableMap.of(md5(), results[2][0], sipHash24(), results[2][1], murmur3_128(), results[2][2], sha256(), results[2][3]), ImmutableMap.of(md5(), results[3][0], sipHash24(), results[3][1], murmur3_128(), results[3][2], sha256(), results[3][3]) }; IntStream.range(0, samples).forEach(x -> { hashs[x % 2].forEach((hash, result) -> assertThat(Hashing.consistentHash(hash.hashInt(keys[x % 2]), (int) numBackends)) .isEqualTo(result)); hashs[2].forEach( (hash, result) -> assertThat(Hashing.consistentHash(hash.hashInt(1), 1)).isEqualTo(result)); hashs[3].forEach( (hash, result) -> assertThat(Hashing.consistentHash(hash.hashInt(1), 2)).isEqualTo(result)); }); }
From source file:com.github.blindpirate.gogradle.util.StringUtils.java
public static Stream<String> eachSubPathReverse(String packagePath) { Path path = Paths.get(packagePath); return IntStream.range(0, path.getNameCount()).mapToObj(i -> path.subpath(0, path.getNameCount() - i)) .map(StringUtils::toUnixString); }
From source file:lda.inference.internal.CollapsedGibbsSampler.java
/** * Get the full conditional distribution over topics. * docID and vocabID are passed to this distribution for parameters. * @param numTopics//from w ww. ja v a2 s .co m * @param docID * @param vocabID * @return the integer distribution over topics */ IntegerDistribution getFullConditionalDistribution(final int numTopics, final int docID, final int vocabID) { int[] topics = IntStream.range(0, numTopics).toArray(); double[] probabilities = Arrays.stream(topics).mapToDouble(t -> getTheta(docID, t) * getPhi(t, vocabID)) .toArray(); return new EnumeratedIntegerDistribution(topics, probabilities); }