- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想在 3D 中构建自适应网格细化。
基本原则如下:
我有一组具有唯一单元格 ID 的单元格。我测试每个细胞,看它是否需要改进。
我想使用 ForkJoin 框架和 Java 8 流来实现它。我读了this article ,但我不知道如何将它应用到我的案例中。
现在,我想到的是:
public class ForkJoinAttempt {
private final double[] cellIds;
public ForkJoinAttempt(double[] cellIds) {
this.cellIds = cellIds;
}
public void refineGrid() {
ForkJoinPool pool = ForkJoinPool.commonPool();
double[] result = pool.invoke(new RefineTask(100));
}
private class RefineTask extends RecursiveTask<double[]> {
final double cellId;
private RefineTask(double cellId) {
this.cellId = cellId;
}
@Override
protected double[] compute() {
return ForkJoinTask.invokeAll(createSubtasks())
.stream()
.map(ForkJoinTask::join)
.reduce(new double[0], new Concat());
}
}
private double[] refineCell(double cellId) {
double[] result;
if (checkCell()) {
result = new double[8];
for (int i = 0; i < 8; i++) {
result[i] = Math.random();
}
} else {
result = new double[1];
result[0] = cellId;
}
return result;
}
private Collection<RefineTask> createSubtasks() {
List<RefineTask> dividedTasks = new ArrayList<>();
for (int i = 0; i < cellIds.length; i++) {
dividedTasks.add(new RefineTask(cellIds[i]));
}
return dividedTasks;
}
private class Concat implements BinaryOperator<double[]> {
@Override
public double[] apply(double[] a, double[] b) {
int aLen = a.length;
int bLen = b.length;
@SuppressWarnings("unchecked")
double[] c = (double[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
}
public boolean checkCell() {
return Math.random() < 0.5;
}
}
...我被困在这里了。
目前这没什么用,因为我从来没有调用过 refineCell
函数。
我创建的所有那些 double[]
也可能存在性能问题。以这种方式合并它们可能也不是最有效的方式。
但首先,在这种情况下,任何人都可以帮助我实现 fork join 吗?
该算法的预期结果是叶单元 ID 数组 (double[]
)
感谢评论,我想出了一些更好用的东西。
一些变化:
为了这个例子,这让我可以更好地检查结果。
这是新的实现:
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ForkJoinAttempt {
private static final int THRESHOLD = 2;
private List<Long> leafCellIds;
public void refineGrid(List<Long> cellsToProcess) {
leafCellIds = ForkJoinPool.commonPool().invoke(new RefineTask(cellsToProcess));
}
public List<Long> getLeafCellIds() {
return leafCellIds;
}
private class RefineTask extends RecursiveTask<List<Long>> {
private final CopyOnWriteArrayList<Long> cellsToProcess = new CopyOnWriteArrayList<>();
private RefineTask(List<Long> cellsToProcess) {
this.cellsToProcess.addAll(cellsToProcess);
}
@Override
protected List<Long> compute() {
if (cellsToProcess.size() > THRESHOLD) {
System.out.println("Fork/Join");
return ForkJoinTask.invokeAll(createSubTasks())
.stream()
.map(ForkJoinTask::join)
.reduce(new ArrayList<>(), new Concat());
} else {
System.out.println("Direct computation");
List<Long> leafCells = new ArrayList<>();
for (Long cell : cellsToProcess) {
Long result = refineCell(cell);
if (result != null) {
leafCells.add(result);
}
}
return leafCells;
}
}
private Collection<RefineTask> createSubTasks() {
List<RefineTask> dividedTasks = new ArrayList<>();
for (List<Long> list : split(cellsToProcess)) {
dividedTasks.add(new RefineTask(list));
}
return dividedTasks;
}
private Long refineCell(Long cellId) {
if (checkCell(cellId)) {
for (int i = 0; i < 8; i++) {
Long newCell = cellId * 10 + i;
cellsToProcess.add(newCell);
System.out.println("Adding child " + newCell + " to cell " + cellId);
}
return null;
} else {
System.out.println("Leaf node " + cellId);
return cellId;
}
}
private List<List<Long>> split(List<Long> list)
{
int[] index = {0, (list.size() + 1)/2, list.size()};
List<List<Long>> lists = IntStream.rangeClosed(0, 1)
.mapToObj(i -> list.subList(index[i], index[i + 1]))
.collect(Collectors.toList());
return lists;
}
}
private class Concat implements BinaryOperator<List<Long>> {
@Override
public List<Long> apply(List<Long> listOne, List<Long> listTwo) {
return Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
}
}
public boolean checkCell(Long cellId) {
return cellId < 100;
}
}
及其测试方法:
int initialSize = 4;
List<Long> cellIds = new ArrayList<>(initialSize);
for (int i = 0; i < initialSize; i++) {
cellIds.add(Long.valueOf(i + 1));
}
ForkJoinAttempt test = new ForkJoinAttempt();
test.refineGrid(cellIds);
List<Long> leafCellIds = test.getLeafCellIds();
System.out.println("Leaf nodes: " + leafCellIds.size());
for (Long node : leafCellIds) {
System.out.println(node);
}
输出确认它向每个根单元格添加了 8 个子单元格。但它并没有走得更远。
我知道为什么,但我不知道如何解决:这是因为尽管 refineCell 方法将新单元格添加到要处理的单元格列表中。 createSubTask 方法没有被再次调用,所以它不知道我添加了新的单元格。
换句话说,我正在寻找一种机制,其中单元 ID 的 Queue
由一些 RecursiveTask
处理,而其他添加到 队列
并行。
最佳答案
首先,让我们从基于流的解决方案开始
public class Mesh {
public static long[] refineGrid(long[] cellsToProcess) {
return Arrays.stream(cellsToProcess).parallel().flatMap(Mesh::expand).toArray();
}
static LongStream expand(long d) {
return checkCell(d)? LongStream.of(d): generate(d).flatMap(Mesh::expand);
}
private static boolean checkCell(long cellId) {
return cellId > 100;
}
private static LongStream generate(long cellId) {
return LongStream.range(0, 8).map(j -> cellId * 10 + j);
}
}
虽然当前的 flatMap
实现有 known issues使用在网格太不平衡时可能应用的并行处理,您的实际任务的性能可能是合理的,因此在开始实现更复杂的事情之前,这个简单的解决方案总是值得一试。
如果您确实需要自定义实现,例如如果工作负载不平衡,Stream 实现不能很好地适应,你可以这样做:
public class MeshTask extends RecursiveTask<long[]> {
public static long[] refineGrid(long[] cellsToProcess) {
return new MeshTask(cellsToProcess, 0, cellsToProcess.length).compute();
}
private final long[] source;
private final int from, to;
private MeshTask(long[] src, int from, int to) {
source = src;
this.from = from;
this.to = to;
}
@Override
protected long[] compute() {
return compute(source, from, to);
}
private static long[] compute(long[] source, int from, int to) {
long[] result = new long[to - from];
ArrayDeque<MeshTask> next = new ArrayDeque<>();
while(getSurplusQueuedTaskCount()<3) {
int mid = (from+to)>>>1;
if(mid == from) break;
MeshTask task = new MeshTask(source, mid, to);
next.push(task);
task.fork();
to = mid;
}
int pos = 0;
for(; from < to; ) {
long value = source[from++];
if(checkCell(value)) result[pos++]=value;
else {
long[] array = generate(value);
array = compute(array, 0, array.length);
result = Arrays.copyOf(result, result.length+array.length-1);
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
while(from == to && !next.isEmpty()) {
MeshTask task = next.pop();
if(task.tryUnfork()) {
to = task.to;
}
else {
long[] array = task.join();
int newLen = pos+to-from+array.length;
if(newLen != result.length)
result = Arrays.copyOf(result, newLen);
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
}
}
return result;
}
static boolean checkCell(long cellId) {
return cellId > 1000;
}
static long[] generate(long cellId) {
long[] sub = new long[8];
for(int i = 0; i < sub.length; i++) sub[i] = cellId*10+i;
return sub;
}
}
此实现直接调用根任务的compute
方法,将调用线程合并到计算中。 compute
方法使用 getSurplusQueuedTaskCount()
决定是否拆分。正如它的文档所说,这个想法是总是有少量盈余,例如。 3
。这确保了评估可以适应不平衡的工作负载,因为空闲线程可以从其他任务中窃取工作。
拆分不是通过创建两个子任务并等待两者来完成的。相反,只有一个任务被拆分,代表待处理工作的后半部分,当前任务的工作量会调整以反射(reflect)前半部分。
然后,剩余的工作量在本地处理。之后,弹出最后推送的子任务并尝试 unfork .如果 unforking 成功,则当前工作负载的范围也将调整以覆盖后续任务的范围,并且本地迭代将继续。
这样,任何没有被另一个线程窃取的多余任务都以最简单和最轻量级的方式处理,就好像它从未被 fork 过一样。
如果任务已经被另一个线程拾取,我们现在必须等待它完成并合并结果数组。
请注意,当通过 join()
等待子任务时,底层实现还将检查是否可以取消 fork 和本地评估,以保持所有工作线程忙碌。然而,调整我们的循环变量并直接将结果累加到我们的目标数组中仍然比仍然需要合并结果数组的嵌套 compute
调用要好。
如果单元格不是叶子,则生成的节点将由相同的逻辑递归处理。这再次允许自适应本地和并发评估,因此执行将适应不平衡的工作负载,例如如果特定单元有更大的子树或特定单元的评估任务比其他单元长得多。
必须强调的是,在所有情况下,都需要大量的处理工作量才能从并行处理中获益。如果像示例中那样,主要只有数据复制,那么好处可能会小得多,甚至不存在,或者在最坏的情况下,并行处理的性能可能比顺序处理差。
关于java - 使用 ForkJoin 和 Streams 构建自适应网格细化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48168136/
我在使用 gradle 构建一个特定应用程序时遇到问题。该应用程序可以用 eclipse 编译和构建,它在平板电脑上运行良好。当我尝试使用 Gradle 构建它时,“compileDebugJava”
我有一个 C 程序,是一位离开的开发人员留给我的。我试图弄清楚他到底在做什么,并将软件重新安排成更合乎逻辑的东西,这样我就可以更轻松地构建它。我正在使用 CMake 构建,而他使用的是 Make。 有
我刚开始阅读“Pro Spring MVC with web flow”,它附带了一个我想遵循的代码示例。 我要什么 - 我想像书中那样构建应用程序,使用 Gradle 有什么问题 - 我没用过 Gr
我希望有人已经这样做了。我正在尝试为我的一个 angular 2 项目在 teamcity 中建立一个连续的构建。在做了一些研究之后,我按照以下步骤操作: 构建步骤 1:为 teamcity 安装 j
我有一个旧的 ASP.Net 网站解决方案,看起来像: 当我在 Visual Studio 中构建解决方案时,我得到以下输出: ------ Build started: Project: C:\..
我使用 gulp-usref、gulp-if、gulp-uglify、gulp-csso 和 gulp-file-include 来构建我的应用程序。除了 HTML 保持原样外,构建中的一切都运行良好
我正在使用 ionic2 开发内部移动应用程序。我可以通过以下方式成功构建 ios: ionic build ios and ionic build ios --prod 但当我这样做时,它一直失败
我是一位经验丰富的 .NET/C# 开发人员,但对这里的几乎所有技术/库(包括 SQL/DB 工作)都是新手。 我正在开发一个具有 Azure/Entity Framework .NET 后端和可移植
我正在使用 VS 2008。我可以使用 IDE 成功编译我的解决方案。但是,当我尝试使用 devenv.com 构建它时,它失败并提示“错误:找不到项目输出组'(无法确定名称)的输出”。该组、其配置或
版本: ember.js 2.7,ember-data 2.7 ember-cli 2.9.1//同样适用于 ember-cli 2.7 node 6.9.1, npm 3.10.9//也适用于 no
我第一次修补 AzureDevops,设置一些 CI 任务。 我有一个公共(public)存储库(开源)和一个包含 3 个 F# 项目的解决方案(.sln)。该解决方案在 Windows/Mac/Li
目前 5.1.5 版本或 STLPort CVS 存储库似乎仍不支持 VS2008。如果有人已经完成了这项工作,那么如果可能的话,分享会很有用:) 同样,了解 VS2005 或 2008 x64 构建
我有一个 Python 2.7 项目,到目前为止一直使用 gfortran 和 MinGW 来构建扩展。我使用 MinGW,因为它似乎支持 Fortran 代码中的写入语句和可分配数组,而 MSVC
关闭。这个问题是off-topic .它目前不接受答案。 想改进这个问题? Update the question所以它是on-topic对于堆栈溢出。 9年前关闭。 Improve this que
我想知道为什么在 Zimbra Wiki 中只列出了构建过程的特定平台。这意味着不可能在其他 Linux 发行版上构建 Zimbra? Zimbra 社区选择一个特殊的 Linux 发行版来构建 Zi
我将在 Swift 中构建一个 CLI 工具。我用这个命令创建了项目 swift package init --type executable当我构建我的项目并解析 时读取别名 Xcode 中的参数并
我想为添加到 docker 镜像的文件设置文件权限。我有这个简单的 Dockerfile: FROM ubuntu:utopic WORKDIR /app RUN groupadd -g 1000 b
当我使用 clBuildProgram在我的 OpenCl 代码中,它失败并显示错误代码 -11,没有任何日志信息。 这是我的代码的样子: ret = clBuildProgram(program
我有一个底部导航栏,它有一个列表页面,该页面使用状态块。 class _MainPageState extends State { int _index = 0; @override Wi
我在本地计算机上使用Jenkins(Jenkins URL未通过Internet公开,但该计算机上已启用Internet。) 我进行了以下配置更改: 在Jenkins工具上安装了Git和Github插
我是一名优秀的程序员,十分优秀!