Search in sources :

Example 11 with FinderExecuteException

use of exceptions.FinderExecuteException in project solution-finder by knewjade.

the class SetupEntryPoint method run.

@Override
public void run() throws FinderException {
    output("# Setup Field");
    // Setup init field
    Field initField = settings.getInitField();
    Verify.field(initField);
    // Setup need filled field
    Field needFilledField = settings.getNeedFilledField();
    Verify.needFilledField(needFilledField);
    // Setup not filled field
    Field notFilledField = settings.getNotFilledField();
    // Setup max height
    int maxHeight = settings.getMaxHeight();
    Verify.maxClearLineUnder10(maxHeight);
    // Setup reserved blocks
    BlockField reservedBlocks = settings.getReservedBlock();
    if (settings.isReserved()) {
        Verify.reservedBlocks(reservedBlocks);
        for (int y = maxHeight - 1; 0 <= y; y--) {
            StringBuilder builder = new StringBuilder();
            for (int x = 0; x < 10; x++) {
                if (reservedBlocks.getBlock(x, y) != null)
                    builder.append(reservedBlocks.getBlock(x, y).getName());
                else if (!initField.isEmpty(x, y))
                    builder.append('X');
                else if (!needFilledField.isEmpty(x, y))
                    builder.append('*');
                else if (!notFilledField.isEmpty(x, y))
                    builder.append('_');
                else
                    builder.append('.');
            }
            output(builder.toString());
        }
    } else {
        for (int y = maxHeight - 1; 0 <= y; y--) {
            StringBuilder builder = new StringBuilder();
            for (int x = 0; x < 10; x++) {
                if (!initField.isEmpty(x, y))
                    builder.append('X');
                else if (!needFilledField.isEmpty(x, y))
                    builder.append('*');
                else if (!notFilledField.isEmpty(x, y))
                    builder.append('_');
                else
                    builder.append('.');
            }
            output(builder.toString());
        }
    }
    // Setup min depth
    // 最低でも必要なミノ数
    int minDepth = Verify.minDepth(needFilledField);
    output();
    // ========================================
    // Output user-defined
    DropType dropType = settings.getDropType();
    output("# Initialize / User-defined");
    output("Max height: " + maxHeight);
    output("Drop: " + dropType.name().toLowerCase());
    output("Searching patterns:");
    // Setup patterns
    List<String> patterns = settings.getPatterns();
    PatternGenerator generator = Verify.patterns(patterns, minDepth);
    // Output patterns
    for (String pattern : patterns) output("  " + pattern);
    // Setup output file
    MyFile base = new MyFile(settings.getOutputBaseFilePath());
    base.mkdirs();
    base.verify();
    output();
    // ========================================
    // Setup core
    output("# Initialize / System");
    int core = Runtime.getRuntime().availableProcessors();
    // Output system-defined
    output("Version = " + FinderConstant.VERSION);
    output("Available processors = " + core);
    output("Need Pieces = " + minDepth);
    output();
    // ========================================
    output("# Search");
    output("  -> Stopwatch start");
    Stopwatch stopwatch = Stopwatch.createStartedStopwatch();
    // Initialize
    MinoFactory minoFactory = new MinoFactory();
    MinoShifter minoShifter = new MinoShifter();
    ColorConverter colorConverter = new ColorConverter();
    SizedBit sizedBit = decideSizedBitSolutionWidth(maxHeight);
    TaskResultHelper taskResultHelper = new BasicMinoPackingHelper();
    SolutionFilter solutionFilter = new ForPathSolutionFilter(generator, maxHeight);
    ThreadLocal<BuildUpStream> buildUpStreamThreadLocal = createBuildUpStreamThreadLocal(dropType, maxHeight);
    OneFumenParser fumenParser = new OneFumenParser(minoFactory, colorConverter);
    // ミノリストの作成
    long deleteKeyMask = getDeleteKeyMask(notFilledField, maxHeight);
    SeparableMinos separableMinos = SeparableMinos.createSeparableMinos(minoFactory, minoShifter, sizedBit, deleteKeyMask);
    // 絶対に置かないブロック
    List<InOutPairField> inOutPairFields = InOutPairField.createInOutPairFields(sizedBit, notFilledField);
    // 絶対に置く必要があるブロック
    ArrayList<BasicSolutions> basicSolutions = new ArrayList<>();
    List<ColumnField> needFillFields = InOutPairField.createInnerFields(sizedBit, needFilledField);
    {
        Field freeze = needFilledField.freeze(sizedBit.getHeight());
        for (ColumnField innerField : needFillFields) {
            // 最小限の部分だけを抽出する
            Field freeze1 = freeze.freeze(sizedBit.getHeight());
            for (int y = 0; y < sizedBit.getHeight(); y++) {
                int width = sizedBit.getWidth();
                for (int x = 0; x < width; x++) freeze1.removeBlock(x, y);
                for (int x = width + 3; x < 10; x++) freeze1.removeBlock(x, y);
            }
            OnDemandBasicSolutions solutions = new OnDemandBasicSolutions(separableMinos, sizedBit, innerField.getBoard(0), freeze1);
            basicSolutions.add(solutions);
            freeze.slideLeft(sizedBit.getWidth());
        }
    }
    // 探索
    SetupPackSearcher searcher = new SetupPackSearcher(inOutPairFields, basicSolutions, sizedBit, solutionFilter, taskResultHelper, needFillFields);
    List<Result> results = getResults(initField, sizedBit, buildUpStreamThreadLocal, searcher);
    output("     Found solution = " + results.size());
    stopwatch.stop();
    output("  -> Stopwatch stop : " + stopwatch.toMessage(TimeUnit.MILLISECONDS));
    output();
    // ========================================
    output("# Output file");
    HTMLBuilder<FieldHTMLColumn> htmlBuilder = new HTMLBuilder<>("Setup result");
    results.parallelStream().forEach(result -> {
        List<MinoOperationWithKey> operationWithKeys = result.getMemento().getSeparableMinoStream(sizedBit.getWidth()).map(SeparableMino::toMinoOperationWithKey).collect(Collectors.toList());
        Field allField = initField.freeze(maxHeight);
        Operations operations = OperationTransform.parseToOperations(allField, operationWithKeys, sizedBit.getHeight());
        List<? extends Operation> operationList = operations.getOperations();
        for (Operation operation : operationList) {
            Mino mino = minoFactory.create(operation.getPiece(), operation.getRotate());
            int x = operation.getX();
            int y = operation.getY();
            allField.put(mino, x, y);
        }
        // 譜面の作成
        String encode = fumenParser.parse(operationWithKeys, initField, maxHeight);
        String name = operationWithKeys.stream().map(OperationWithKey::getPiece).map(Piece::getName).collect(Collectors.joining());
        String link = String.format("<a href='http://fumen.zui.jp/?v115@%s' target='_blank'>%s</a>", encode, name);
        String line = String.format("<div>%s</div>", link);
        htmlBuilder.addColumn(new FieldHTMLColumn(allField, maxHeight), line);
    });
    ArrayList<FieldHTMLColumn> columns = new ArrayList<>(htmlBuilder.getRegisteredColumns());
    columns.sort(Comparator.comparing(FieldHTMLColumn::getTitle).reversed());
    try (BufferedWriter bufferedWriter = base.newBufferedWriter()) {
        for (String line : htmlBuilder.toList(columns, true)) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();
    } catch (IOException e) {
        throw new FinderExecuteException(e);
    }
    output();
    // ========================================
    output("# Finalize");
    output("done");
}
Also used : OnDemandBasicSolutions(searcher.pack.solutions.OnDemandBasicSolutions) MyFile(entry.path.output.MyFile) Stopwatch(lib.Stopwatch) ForPathSolutionFilter(entry.path.ForPathSolutionFilter) TaskResultHelper(searcher.pack.task.TaskResultHelper) Result(searcher.pack.task.Result) BufferedWriter(java.io.BufferedWriter) ColumnField(core.column_field.ColumnField) InOutPairField(searcher.pack.InOutPairField) Field(core.field.Field) SeparableMinos(searcher.pack.SeparableMinos) InOutPairField(searcher.pack.InOutPairField) ColorConverter(common.tetfu.common.ColorConverter) SeparableMino(searcher.pack.separable_mino.SeparableMino) Mino(core.mino.Mino) MinoFactory(core.mino.MinoFactory) BuildUpStream(common.buildup.BuildUpStream) PatternGenerator(common.pattern.PatternGenerator) OneFumenParser(entry.path.output.OneFumenParser) HTMLBuilder(output.HTMLBuilder) ColumnField(core.column_field.ColumnField) BasicMinoPackingHelper(searcher.pack.task.BasicMinoPackingHelper) IOException(java.io.IOException) EntryPoint(entry.EntryPoint) BasicSolutions(searcher.pack.calculator.BasicSolutions) OnDemandBasicSolutions(searcher.pack.solutions.OnDemandBasicSolutions) SetupPackSearcher(searcher.pack.task.SetupPackSearcher) SizedBit(searcher.pack.SizedBit) ForPathSolutionFilter(entry.path.ForPathSolutionFilter) SolutionFilter(searcher.pack.memento.SolutionFilter) MinoShifter(core.mino.MinoShifter) DropType(entry.DropType) FinderExecuteException(exceptions.FinderExecuteException)

Example 12 with FinderExecuteException

use of exceptions.FinderExecuteException in project solution-finder by knewjade.

the class CSVPathOutput method outputOperationsToCSV.

private void outputOperationsToCSV(Field field, MyFile file, List<PathPair> pathPairs, SizedBit sizedBit) throws FinderExecuteException {
    LockedBuildUpListUpThreadLocal threadLocal = new LockedBuildUpListUpThreadLocal(sizedBit.getHeight());
    List<List<MinoOperationWithKey>> samples = pathPairs.parallelStream().map(resultPair -> {
        Result result = resultPair.getResult();
        LinkedList<MinoOperationWithKey> operations = result.getMemento().getSeparableMinoStream(sizedBit.getWidth()).map(SeparableMino::toMinoOperationWithKey).collect(Collectors.toCollection(LinkedList::new));
        BuildUpStream buildUpStream = threadLocal.get();
        return buildUpStream.existsValidBuildPatternDirectly(field, operations).findFirst().orElse(Collections.emptyList());
    }).collect(Collectors.toList());
    try (BufferedWriter writer = file.newBufferedWriter()) {
        for (List<MinoOperationWithKey> operationWithKeys : samples) {
            Operations operations = OperationTransform.parseToOperations(field, operationWithKeys, sizedBit.getHeight());
            String operationLine = OperationInterpreter.parseToString(operations);
            writer.write(operationLine);
            writer.newLine();
        }
        writer.flush();
    } catch (IOException e) {
        throw new FinderExecuteException("Failed to output file", e);
    }
}
Also used : OperationTransform(common.parser.OperationTransform) entry.path(entry.path) BufferedWriter(java.io.BufferedWriter) Result(searcher.pack.task.Result) LongPieces(common.datastore.blocks.LongPieces) MinoOperationWithKey(common.datastore.MinoOperationWithKey) IOException(java.io.IOException) OperationInterpreter(common.parser.OperationInterpreter) FinderExecuteException(exceptions.FinderExecuteException) FinderInitializeException(exceptions.FinderInitializeException) Collectors(java.util.stream.Collectors) File(java.io.File) Operations(common.datastore.Operations) SizedBit(searcher.pack.SizedBit) List(java.util.List) Field(core.field.Field) SeparableMino(searcher.pack.separable_mino.SeparableMino) LinkedList(java.util.LinkedList) Collections(java.util.Collections) BuildUpStream(common.buildup.BuildUpStream) SeparableMino(searcher.pack.separable_mino.SeparableMino) IOException(java.io.IOException) LinkedList(java.util.LinkedList) Result(searcher.pack.task.Result) BufferedWriter(java.io.BufferedWriter) MinoOperationWithKey(common.datastore.MinoOperationWithKey) List(java.util.List) LinkedList(java.util.LinkedList) FinderExecuteException(exceptions.FinderExecuteException) BuildUpStream(common.buildup.BuildUpStream) Operations(common.datastore.Operations)

Example 13 with FinderExecuteException

use of exceptions.FinderExecuteException in project solution-finder by knewjade.

the class LinkPathOutput method outputOperationsToSimpleHTML.

private void outputOperationsToSimpleHTML(Field field, MyFile file, List<PathPair> pathPairs, SizedBit sizedBit) throws FinderExecuteException {
    // Get height
    int maxClearLine = sizedBit.getHeight();
    // テト譜用のフィールド作成
    ColoredField initField = ColoredFieldFactory.createField(24);
    for (int y = 0; y < maxClearLine; y++) for (int x = 0; x < 10; x++) if (!field.isEmpty(x, y))
        initField.setColorType(ColorType.Gray, x, y);
    // 並び替える
    Comparator<PathPair> comparator = new PathPairComparator();
    pathPairs.sort(comparator);
    // HTMLの生成  // true: ライン消去あり, false: ライン消去なし
    HTMLBuilder<HTMLColumn> htmlBuilder = new HTMLBuilder<>("Path Result");
    htmlBuilder.addHeader(String.format("<div>%dパターン</div>", pathPairs.size()));
    pathPairs.parallelStream().forEach(pathPair -> {
        PathHTMLColumn htmlColumn = getHTMLColumn(pathPair);
        Pair<String, Integer> linkAndPriority = createALink(pathPair);
        String line = String.format("<div>%s</div>", linkAndPriority.getKey());
        htmlBuilder.addColumn(htmlColumn, line, -linkAndPriority.getValue());
    });
    // 出力
    try (BufferedWriter writer = file.newBufferedWriter()) {
        List<HTMLColumn> priorityList = Arrays.asList(PathHTMLColumn.NotDeletedLine, PathHTMLColumn.DeletedLine);
        for (String line : htmlBuilder.toList(priorityList, false)) writer.write(line);
        writer.flush();
    } catch (Exception e) {
        throw new FinderExecuteException("Failed to output file", e);
    }
}
Also used : ColoredField(common.tetfu.field.ColoredField) HTMLBuilder(output.HTMLBuilder) FinderExecuteException(exceptions.FinderExecuteException) FinderInitializeException(exceptions.FinderInitializeException) BufferedWriter(java.io.BufferedWriter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HTMLColumn(output.HTMLColumn) FinderExecuteException(exceptions.FinderExecuteException)

Example 14 with FinderExecuteException

use of exceptions.FinderExecuteException in project solution-finder by knewjade.

the class MoveEntryPoint method close.

@Override
public void close() throws FinderTerminateException {
    try {
        flush();
        logWriter.close();
    } catch (IOException | FinderExecuteException e) {
        throw new FinderTerminateException(e);
    }
}
Also used : IOException(java.io.IOException) FinderExecuteException(exceptions.FinderExecuteException) FinderTerminateException(exceptions.FinderTerminateException)

Example 15 with FinderExecuteException

use of exceptions.FinderExecuteException in project solution-finder by knewjade.

the class MoveEntryPoint method run.

@Override
public void run() throws FinderException {
    output("# Setup Field");
    // Setup field
    Field field = settings.getField();
    Verify.field(field);
    int maxClearLine = settings.getMaxClearLine();
    output(FieldView.toString(field, maxClearLine));
    // Setup max depth
    // パフェに必要なミノ数
    int maxDepth = Verify.maxDepth(field, maxClearLine);
    output();
    // ========================================
    output("Searching patterns:");
    // Setup patterns
    List<String> patterns = settings.getPatterns();
    PatternGenerator generator = Verify.patterns(patterns);
    // Output patterns
    for (String pattern : patterns) output("  " + pattern);
    output();
    // ========================================
    // baseファイル
    MyFile base = new MyFile(settings.getOutputBaseFilePath());
    base.mkdirs();
    MinoFactory minoFactory = new MinoFactory();
    MinoShifter minoShifter = new MinoShifter();
    MinoRotation minoRotation = new MinoRotation();
    ColorConverter colorConverter = new ColorConverter();
    PerfectValidator perfectValidator = new PerfectValidator();
    PutterNoHold<Action> putter = new PutterNoHold<>(minoFactory, perfectValidator);
    output("# Calculate");
    try (BufferedWriter bw = base.newBufferedWriter()) {
        List<Pieces> pieces = generator.blocksStream().collect(Collectors.toList());
        for (Pieces piece : pieces) {
            String using = piece.blockStream().map(Piece::getName).collect(Collectors.joining());
            output("   -> " + using);
            TreeSet<Order> first = putter.first(field, piece.getPieceArray(), new LockedCandidate(minoFactory, minoShifter, minoRotation, maxClearLine), maxClearLine, maxDepth);
            for (Order order : first) {
                Stream<Operation> operationStream = order.getHistory().getOperationStream();
                List<MinoOperationWithKey> operationWithKeys = OperationTransform.parseToOperationWithKeys(field, new Operations(operationStream), minoFactory, maxClearLine);
                BlockField blockField = OperationTransform.parseToBlockField(operationWithKeys, minoFactory, maxClearLine);
                String encodeColor = encodeColor(field, minoFactory, colorConverter, blockField);
                String encodeGray = encodeGray(order.getField(), minoFactory, colorConverter);
                bw.write(String.format("%s,%s,%s", using, encodeColor, encodeGray));
                bw.newLine();
            }
        }
        bw.flush();
    } catch (IOException e) {
        throw new FinderExecuteException("Failed to output file", e);
    }
}
Also used : Action(common.datastore.action.Action) MyFile(entry.path.output.MyFile) Operation(common.datastore.Operation) BufferedWriter(java.io.BufferedWriter) BlockField(common.datastore.BlockField) Field(core.field.Field) ColoredField(common.tetfu.field.ColoredField) LockedCandidate(core.action.candidate.LockedCandidate) MinoOperationWithKey(common.datastore.MinoOperationWithKey) BlockField(common.datastore.BlockField) ColorConverter(common.tetfu.common.ColorConverter) MinoFactory(core.mino.MinoFactory) PutterNoHold(searcher.PutterNoHold) PerfectValidator(searcher.common.validator.PerfectValidator) Operations(common.datastore.Operations) Pieces(common.datastore.blocks.Pieces) Order(common.datastore.order.Order) PatternGenerator(common.pattern.PatternGenerator) IOException(java.io.IOException) EntryPoint(entry.EntryPoint) MinoRotation(core.srs.MinoRotation) MinoShifter(core.mino.MinoShifter) FinderExecuteException(exceptions.FinderExecuteException)

Aggregations

FinderExecuteException (exceptions.FinderExecuteException)15 IOException (java.io.IOException)10 Pieces (common.datastore.blocks.Pieces)6 Field (core.field.Field)6 FinderInitializeException (exceptions.FinderInitializeException)5 SizedBit (searcher.pack.SizedBit)5 PatternGenerator (common.pattern.PatternGenerator)4 ConcurrentVisitedTree (common.tree.ConcurrentVisitedTree)4 CheckerCommonObj (concurrent.checker.invoker.CheckerCommonObj)4 BufferedWriter (java.io.BufferedWriter)4 ArrayList (java.util.ArrayList)4 LongPieces (common.datastore.blocks.LongPieces)3 Piece (core.mino.Piece)3 PathEntryPoint (entry.path.PathEntryPoint)3 PathPair (entry.path.PathPair)3 PathSettings (entry.path.PathSettings)3 FinderTerminateException (exceptions.FinderTerminateException)3 File (java.io.File)3 ExecutionException (java.util.concurrent.ExecutionException)3 Collectors (java.util.stream.Collectors)3