use of java.util.stream.Stream in project fx2048 by brunoborges.
the class GameManager method moveTiles.
/**
* Moves the tiles according to given direction
* At any move, takes care of merge tiles, add a new one and perform the
* required animations
* It updates the score and checks if the user won the game or if the game is over
*
* @param direction is the selected direction to move the tiles
*/
private void moveTiles(Direction direction) {
synchronized (gameGrid) {
if (movingTiles) {
return;
}
}
board.setPoints(0);
mergedToBeRemoved.clear();
ParallelTransition parallelTransition = new ParallelTransition();
gridOperator.sortGrid(direction);
final int tilesWereMoved = gridOperator.traverseGrid((x, y) -> {
Location thisloc = new Location(x, y);
// farthest available location
Location farthestLocation = findFarthestLocation(thisloc, direction);
Optional<Tile> opTile = optionalTile(thisloc);
AtomicInteger result = new AtomicInteger();
// calculates to a possible merge
Location nextLocation = farthestLocation.offset(direction);
optionalTile(nextLocation).filter(t -> t.isMergeable(opTile) && !t.isMerged()).ifPresent(t -> {
Tile tile = opTile.get();
t.merge(tile);
t.toFront();
gameGrid.put(nextLocation, t);
gameGrid.replace(thisloc, null);
parallelTransition.getChildren().add(animateExistingTile(tile, t.getLocation()));
parallelTransition.getChildren().add(animateMergedTile(t));
mergedToBeRemoved.add(tile);
board.addPoints(t.getValue());
if (t.getValue() == FINAL_VALUE_TO_WIN) {
board.setGameWin(true);
}
result.set(1);
});
if (result.get() == 0 && opTile.isPresent() && !farthestLocation.equals(thisloc)) {
Tile tile = opTile.get();
parallelTransition.getChildren().add(animateExistingTile(tile, farthestLocation));
gameGrid.put(farthestLocation, tile);
gameGrid.replace(thisloc, null);
tile.setLocation(farthestLocation);
result.set(1);
}
return result.get();
});
board.animateScore();
if (parallelTransition.getChildren().size() > 0) {
parallelTransition.setOnFinished(e -> {
board.getGridGroup().getChildren().removeAll(mergedToBeRemoved);
gameGrid.values().stream().filter(Objects::nonNull).forEach(Tile::clearMerge);
Location randomAvailableLocation = findRandomAvailableLocation();
if (randomAvailableLocation == null && mergeMovementsAvailable() == 0) {
board.setGameOver(true);
} else if (randomAvailableLocation != null && tilesWereMoved > 0) {
synchronized (gameGrid) {
movingTiles = false;
}
addAndAnimateRandomTile(randomAvailableLocation);
}
});
synchronized (gameGrid) {
movingTiles = true;
}
parallelTransition.play();
}
}
use of java.util.stream.Stream in project Gargoyle by callakrsos.
the class FileSearcher method listClases.
public static List<ProjectInfo> listClases(String classDirName) throws Exception {
File file = new File(classDirName);
// 기본적인 파일의 존재유무 및 디렉토리인지 체크.
if (!file.exists())
throw new FileNotFoundException(file + " Not found!");
//
if (!file.isDirectory())
throw new IllegalArgumentException("only directory.");
/*
* 디렉토리안에 클래스패스 정보가 존재하는지 확인하고 존재한다면 classpath에 기술된 정보 기준으로 클래스 파일을
* 로드한다. 프로그램내에서 workspace를 선택한 경우일수있고, 프로젝트를 선택한 두가지의 경우가 있기때문에 두가지의
* 케이스를 고려한 로직이 들어간다.
*/
/*
* 일단 워크스페이스를 선택한경우라고 가정하고 워크스페이스내에 폴더들을 순차적으로 돌아보면서 classpath의 존재유무를 찾고
* 존재하는케이스는 따로 모아놓는다. 파일레벨은 워크스페이스(0레벨)-프로젝트(1레벨)로 가정하여 1레벨까지만 이동한다.
*/
List<File> listFiles = findClassPaths(file);
/*
* classpath파일을 찾은경우 그 파일path를 기준으로 클래스들을 로딩한다.
*/
List<ProjectInfo> allClasses = new ArrayList<>();
if (listFiles != null && !listFiles.isEmpty())
LOGGER.debug(" im will working...");
long startTime = System.currentTimeMillis();
int searchedDirCount = 0;
StringBuffer srchedDirNames = new StringBuffer();
for (File f : listFiles) {
try {
ClassPath parsingClassPath = parsingClassPath(f.getAbsolutePath());
// 프로젝트파일.
File projectFile = f.getParentFile();
// output 속성값의 존재유무만 확인하여 컴파일되는 경로를 찾는다.
List<ProjectInfo> collect = parsingClassPath.toStream().filter(entry -> {
boolean notEmpty = ValueUtil.isNotEmpty(entry.getOutput());
LOGGER.debug(String.format("srch entry path : %s is Traget %b ", entry.getPath(), notEmpty));
return notEmpty;
}).map(pram -> pram.getOutput()).distinct().parallel().flatMap(new Function<String, Stream<ProjectInfo>>() {
@Override
public Stream<ProjectInfo> apply(String entry) {
LOGGER.debug(String.format("entry : %s", entry));
File compiledFilePath = new File(projectFile, entry);
int length = compiledFilePath.getAbsolutePath().length() + 1;
List<String> findClases = findClases(projectFile.getAbsolutePath(), compiledFilePath, length);
LOGGER.debug(compiledFilePath.toString());
LOGGER.debug(findClases.toString());
LOGGER.debug(String.valueOf(findClases.size()));
ProjectInfo classInfo = new ProjectInfo();
classInfo.setProjectName(projectFile.getName());
classInfo.setProjectDir(compiledFilePath.getAbsolutePath());
classInfo.setClasses(findClases);
return Stream.of(classInfo);
}
}).collect(Collectors.toList());
allClasses.addAll(collect);
searchedDirCount++;
srchedDirNames.append(f.getAbsolutePath()).append(SystemUtils.LINE_SEPARATOR);
} catch (SAXParseException e) {
LOGGER.error(String.format("정상적인 XML 형태가 아님. 파일명 : %s", f.getAbsolutePath()));
LOGGER.error(String.format("%d 행 :: %d 열", e.getLineNumber(), e.getColumnNumber()));
}
}
long endTime = System.currentTimeMillis();
long costMillisend = endTime - startTime;
LOGGER.debug(String.format("Total Cost time : %s (ms) searched Directory Count : %d ", costMillisend, searchedDirCount));
LOGGER.debug(String.format("Searched Dirs info \n%s", srchedDirNames.toString()));
return allClasses;
}
use of java.util.stream.Stream in project gatk by broadinstitute.
the class CoverageModelEMWorkspace method getCopyRatioSegmentsSpark.
/**
* Fetch copy ratio segments from compute blocks (Spark implementation)
*
* @return a list of {@link CopyRatioHMMResults}
*/
private List<List<HiddenStateSegmentRecord<STATE, Target>>> getCopyRatioSegmentsSpark() {
/* local final member variables for lambda capture */
final List<Target> processedTargetList = new ArrayList<>();
processedTargetList.addAll(this.processedTargetList);
final List<SexGenotypeData> processedSampleSexGenotypeData = new ArrayList<>();
processedSampleSexGenotypeData.addAll(this.processedSampleSexGenotypeData);
final List<String> processedSampleNameList = new ArrayList<>();
processedSampleNameList.addAll(this.processedSampleNameList);
final INDArray sampleReadDepths = Transforms.exp(sampleMeanLogReadDepths, true);
final CopyRatioExpectationsCalculator<CoverageModelCopyRatioEmissionData, STATE> copyRatioExpectationsCalculator = this.copyRatioExpectationsCalculator;
final BiFunction<SexGenotypeData, Target, STATE> referenceStateFactory = this.referenceStateFactory;
return fetchCopyRatioEmissionDataSpark().mapPartitionsToPair(it -> {
final List<Tuple2<Integer, CopyRatioHMMResults<CoverageModelCopyRatioEmissionData, STATE>>> newPartitionData = new ArrayList<>();
while (it.hasNext()) {
final Tuple2<Integer, List<CoverageModelCopyRatioEmissionData>> prevDatum = it.next();
final int sampleIndex = prevDatum._1;
final CopyRatioCallingMetadata copyRatioCallingMetadata = CopyRatioCallingMetadata.builder().sampleName(processedSampleNameList.get(sampleIndex)).sampleSexGenotypeData(processedSampleSexGenotypeData.get(sampleIndex)).sampleCoverageDepth(sampleReadDepths.getDouble(sampleIndex)).emissionCalculationStrategy(EmissionCalculationStrategy.HYBRID_POISSON_GAUSSIAN).build();
newPartitionData.add(new Tuple2<>(sampleIndex, copyRatioExpectationsCalculator.getCopyRatioHMMResults(copyRatioCallingMetadata, processedTargetList, prevDatum._2)));
}
return newPartitionData.iterator();
}, true).mapPartitionsToPair(it -> {
final List<Tuple2<Integer, List<HiddenStateSegmentRecord<STATE, Target>>>> newPartitionData = new ArrayList<>();
while (it.hasNext()) {
final Tuple2<Integer, CopyRatioHMMResults<CoverageModelCopyRatioEmissionData, STATE>> prevDatum = it.next();
final int sampleIndex = prevDatum._1;
final CopyRatioHMMResults<CoverageModelCopyRatioEmissionData, STATE> result = prevDatum._2;
final HMMSegmentProcessor<CoverageModelCopyRatioEmissionData, STATE, Target> processor = new HMMSegmentProcessor<>(Collections.singletonList(result.getMetaData().getSampleName()), Collections.singletonList(result.getMetaData().getSampleSexGenotypeData()), referenceStateFactory, Collections.singletonList(new HashedListTargetCollection<>(processedTargetList)), Collections.singletonList(result.getForwardBackwardResult()), Collections.singletonList(result.getViterbiResult()));
newPartitionData.add(new Tuple2<>(sampleIndex, processor.getSegmentsAsList()));
}
return newPartitionData.iterator();
}).collect().stream().sorted(Comparator.comparingInt(t -> t._1)).map(t -> t._2).collect(Collectors.toList());
}
use of java.util.stream.Stream in project gatk-protected by broadinstitute.
the class CoverageModelEMWorkspace method updateSampleUnexplainedVariance.
/**
* E-step update of the sample-specific unexplained variance
*
* @return a {@link SubroutineSignal} containing the update size (key: "error_norm") and the average
* number of function evaluations per sample (key: "iterations")
*/
@EvaluatesRDD
@UpdatesRDD
@CachesRDD
public SubroutineSignal updateSampleUnexplainedVariance() {
mapWorkers(cb -> cb.cloneWithUpdatedCachesByTag(CoverageModelEMComputeBlock.CoverageModelICGCacheTag.E_STEP_GAMMA));
cacheWorkers("after E-step for sample unexplained variance initialization");
/* create a compound objective function for simultaneous multi-sample queries */
final java.util.function.Function<Map<Integer, Double>, Map<Integer, Double>> objFunc = arg -> {
if (arg.isEmpty()) {
return Collections.emptyMap();
}
final int[] sampleIndices = arg.keySet().stream().mapToInt(i -> i).toArray();
final INDArray gammaValues = Nd4j.create(Arrays.stream(sampleIndices).mapToDouble(arg::get).toArray(), new int[] { sampleIndices.length, 1 });
final INDArray eval = mapWorkersAndReduce(cb -> cb.calculateSampleSpecificVarianceObjectiveFunctionMultiSample(sampleIndices, gammaValues), INDArray::add);
final Map<Integer, Double> output = new HashMap<>();
IntStream.range(0, sampleIndices.length).forEach(evalIdx -> output.put(sampleIndices[evalIdx], eval.getDouble(evalIdx)));
return output;
};
final java.util.function.Function<UnivariateSolverSpecifications, AbstractUnivariateSolver> solverFactory = spec -> new RobustBrentSolver(spec.getRelativeAccuracy(), spec.getAbsoluteAccuracy(), spec.getFunctionValueAccuracy(), null, config.getSampleSpecificVarianceSolverNumBisections(), config.getSampleSpecificVarianceSolverRefinementDepth());
/* instantiate a synchronized multi-sample root finder and add jobs */
final SynchronizedUnivariateSolver syncSolver = new SynchronizedUnivariateSolver(objFunc, solverFactory, numSamples);
IntStream.range(0, numSamples).forEach(si -> {
final double x0 = 0.5 * config.getSampleSpecificVarianceUpperLimit();
syncSolver.add(si, 0, config.getSampleSpecificVarianceUpperLimit(), x0, config.getSampleSpecificVarianceAbsoluteTolerance(), config.getSampleSpecificVarianceRelativeTolerance(), config.getSampleSpecificVarianceMaximumIterations());
});
/* solve and collect statistics */
final INDArray newSampleUnexplainedVariance = Nd4j.create(numSamples, 1);
final List<Integer> numberOfEvaluations = new ArrayList<>(numSamples);
try {
final Map<Integer, SynchronizedUnivariateSolver.UnivariateSolverSummary> newSampleSpecificVarianceMap = syncSolver.solve();
newSampleSpecificVarianceMap.entrySet().forEach(entry -> {
final int sampleIndex = entry.getKey();
final SynchronizedUnivariateSolver.UnivariateSolverSummary summary = entry.getValue();
double val = 0;
switch(summary.status) {
case SUCCESS:
val = summary.x;
break;
case TOO_MANY_EVALUATIONS:
logger.warn("Could not locate the root of gamma -- increase the maximum number of" + "function evaluations");
break;
}
newSampleUnexplainedVariance.put(sampleIndex, 0, val);
numberOfEvaluations.add(summary.evaluations);
});
} catch (final InterruptedException ex) {
throw new RuntimeException("The update of sample unexplained variance was interrupted -- can not continue");
}
/* admix */
final INDArray newSampleUnexplainedVarianceAdmixed = newSampleUnexplainedVariance.mul(config.getMeanFieldAdmixingRatio()).addi(sampleUnexplainedVariance.mul(1 - config.getMeanFieldAdmixingRatio()));
/* calculate the error */
final double errorNormInfinity = CoverageModelEMWorkspaceMathUtils.getINDArrayNormInfinity(newSampleUnexplainedVarianceAdmixed.sub(sampleUnexplainedVariance));
/* update local copy */
sampleUnexplainedVariance.assign(newSampleUnexplainedVarianceAdmixed);
/* push to workers */
pushToWorkers(newSampleUnexplainedVarianceAdmixed, (arr, cb) -> cb.cloneWithUpdatedPrimitive(CoverageModelEMComputeBlock.CoverageModelICGCacheNode.gamma_s, newSampleUnexplainedVarianceAdmixed));
final int iterations = (int) (numberOfEvaluations.stream().mapToDouble(d -> d).sum() / numSamples);
return SubroutineSignal.builder().put(StandardSubroutineSignals.RESIDUAL_ERROR_NORM, errorNormInfinity).put(StandardSubroutineSignals.ITERATIONS, iterations).build();
}
use of java.util.stream.Stream in project Gargoyle by callakrsos.
the class DaoWizardViewController method btnExecOnMouseClick.
/**
* 텍스트에 기술된 SQL문을 실행한다. 기본적으로 ROWNUM 기술문을 100개를 감싸서 SQL을 조회한다.
*
* @작성자 : KYJ
* @작성일 : 2015. 10. 21.
*/
@FXML
public void btnExecOnMouseClick(MouseEvent e) {
LOGGER.debug("event] btnExecOnMouseClick");
String velocitySQL = txtSql.getText().trim();
if (velocitySQL == null || velocitySQL.isEmpty())
return;
LOGGER.debug(String.format("velocitySQL : %s", velocitySQL));
// 파라미터 컬럼값 반환받는다.
ObservableList<TbpSysDaoFieldsDVO> items = tbParams.getItems();
Map<String, TbpSysDaoColumnsDVO> unmapping = this.tbMappings.getItems().stream().filter(v -> {
String lockYn = v.getLockYn();
if ("Y".equals(lockYn))
return true;
return false;
}).collect(Collectors.toMap(TbpSysDaoColumnsDVO::getColumnName, v -> v));
Map<String, Object> paramMap = items.stream().filter(vo -> vo.getTestValue() != null && !vo.getTestValue().isEmpty()).collect(Collectors.toMap(TbpSysDaoFieldsDVO::getFieldName, new Function<TbpSysDaoFieldsDVO, Object>() {
@Override
public Object apply(TbpSysDaoFieldsDVO t) {
if ("Arrays".equals(t.getType())) {
String pattern = "'[^']{0,}'";
List<String> regexMatchs = ValueUtil.regexMatchs(pattern, t.getTestValue(), str -> {
return str.substring(1, str.length() - 1);
});
return regexMatchs;
}
return t.getTestValue();
}
}));
SimpleSQLResultView simpleSQLResultView = new SimpleSQLResultView(velocitySQL, paramMap);
try {
simpleSQLResultView.show();
List<TableModelDVO> columns = simpleSQLResultView.getColumns();
List<TbpSysDaoColumnsDVO> resultList = columns.stream().map(vo -> {
TbpSysDaoColumnsDVO dvo = new TbpSysDaoColumnsDVO();
dvo.setColumnName(vo.getDatabaseColumnName());
String databaseTypeName = vo.getDatabaseTypeName();
dvo.setColumnType(databaseTypeName);
if (unmapping.containsKey(vo.getDatabaseColumnName())) {
TbpSysDaoColumnsDVO tmp = unmapping.get(vo.getDatabaseColumnName());
dvo.setProgramType(tmp.getProgramType());
dvo.setLockYn(tmp.getLockYn());
} else {
String programType = DatabaseTypeMappingResourceLoader.getInstance().get(databaseTypeName);
dvo.setProgramType(programType);
}
return dvo;
}).collect(Collectors.toList());
// if (!this.tbMappings.getItems().isEmpty())
if (!resultList.isEmpty()) {
try {
this.tbMappings.getItems().clear();
getSelectedMethodItem().getTbpSysDaoColumnsDVOList().clear();
this.tbMappings.getItems().addAll(resultList);
getSelectedMethodItem().getTbpSysDaoColumnsDVOList().addAll(resultList);
} catch (NullPointerException n) {
DialogUtil.showMessageDialog("메소드를 선택해주세요.");
}
}
} catch (IOException e1) {
LOGGER.error(ValueUtil.toString(e1));
DialogUtil.showExceptionDailog(e1);
}
}
Aggregations