我发现初始化我的模型非常慢。完成需要 40 秒!
我的代码包含两个主要部分:1)CSV 数据阅读器将首先运行以加载数据,完成读取和处理 35000+ 行需要不到 1 秒的时间(请参见下面的第一部分代码);2) 随后初始化代理和边。特别是,边缘初始化将利用 CSV 阅读器中加载的数据(参见下面的第二部分代码)。
第一部分:CSVReader 代码
public class DataReader {
private String csvFile;
private List<String> sub = new ArrayList<String>();
private List<List> master = new ArrayList<List>();
public void ReadFromCSV(String csvFile) {
String line = "";
String cvsSplitBy = ",";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
System.out.println("Header " + br.readLine());
while ((line = br.readLine()) != null) {
// use comma as separator
String[] list = line.split(cvsSplitBy);
// System.out.println("the size is " + country[1]);
for (int i = 0; i < list.length; i++) {
sub.add(list[i]);
}
List<String> temp = (List<String>) ((ArrayList<String>) sub).clone();
// master.add(new ArrayList<String>(sub));
master.add(temp);
sub.removeAll(sub);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(master);
}
public List<List> getMaster() {
return master;
}
}
这是 CSVReader 使用的输入文件:
第二部分:边缘(路由)初始化代码。我怀疑是查询循环消耗了大部分初始化时间:
// add route network
Network<Object> net = (Network<Object>)context.getProjection("IntraCity Network");
IndexedIterable<Object> local_hubs = context.getObjects(LocalHub.class);
for (int i = 0; i <= CSV_reader_route.getMaster().size() - 1; i++) {
String source = (String) CSV_reader_route.getMaster().get(i).get(0);
String target = (String) CSV_reader_route.getMaster().get(i).get(3);
double dist = Double.parseDouble((String) CSV_reader_route.getMaster().get(i).get(6));
double time = Double.parseDouble((String) CSV_reader_route.getMaster().get(i).get(7));
Object source_hub = null;
Object target_hub = null;
Query<Object> source_query = new PropertyEquals<Object>(context, "hub_code", source);
for (Object o : source_query.query()) {
if (o instanceof LocalHub) {
source_hub = (LocalHub) o;
}
if (o instanceof GatewayHub) {
source_hub = (GatewayHub) o;
}
}
Query<Object> target_query = new PropertyEquals<Object>(context, "hub_code", target);
for (Object o : target_query.query()) {
if (o instanceof LocalHub) {
target_hub = (LocalHub) o;
}
if (o instanceof GatewayHub) {
target_hub = (GatewayHub) o;
}
}
if (net.getEdge(source_hub, target_hub) == null) {
Route this_route = (Route) net.addEdge(source_hub, target_hub);
context.add(this_route);
this_route.setDist(dist);
this_route.setTime(time); }
}
}
更新:根据我的测试,我发现这条线会大大减慢初始化过程。
context.add(this_route);
如果没有这条线,它只需要 3 秒就可以完成。使用这条线,模型需要 20 秒!context.add() 的底层机制是什么?如何解决和改善这个问题?