英文:
Adding lines to allready exisiting file
问题
我目前正在处理一个优化问题,我想通过使用回调函数从每个IPOPT迭代中添加一些信息到文件中。我能够收集所需的信息,但当我尝试将其添加到文件时,它只添加了一些奇怪的迭代。这是我正在做的事情(简化版本):
我有一个外部迭代循环(k)和一个内部循环(IPOPT迭代)
thefile = "output.txt" # 创建一个新文件
f = open(thefile, "w") # 新文件的标题
@printf(f,"%-10s %-10s %-10s\n ", "outer", "inner", "objval")
k = 0
while k <= 100
iter = []
objValVector = []
function my_callback( alg_mod::Cint,
iter_count::Cint,
obj_value::Float64,
inf_pr::Float64,
inf_du::Float64,
mu::Float64,
d_norm::Float64,
regularization_size::Float64,
alpha_du::Float64,
alpha_pr::Float64,
ls_trials::Cint) # 使用回调函数获取obj.val
append!(objValvector, obj_value)
append!(iter, iter_count)
return true
end
MOI.set(model, Ipopt.CallbackFunction(), my_callback)
optimize!(model);
f = open(thefile, "a"); # 以追加“模式”打开文件以添加到现有文件
for i in 1:length(iter)
@printf(f, "%-10s %-10s %-10s\n",
k, iter[i], objValvector[i])
end
Do something...
k += 1;
end
英文:
I am currently working on an optimization problem where I want to add some information from each IPOPT iteration to a file by using a callback function. I am able to collect the information I need but when I try to add it to the file it only adds a few weird iterations. This is what I am doing (simplified)
I have an outer iteration loop (k) and an inner (the IPOPT iterations)
thefile = "output.txt". # Create a new file
f = open(thefile, "w"). # The header to my new file
@printf(f,"%-10s %-10s %-10s\n ", "outer", "inner", "objval" )
k = 0
while k <= 100
iter = []
objValVector = []
function my_callback( alg_mod::Cint,
iter_count::Cint,
obj_value::Float64,
inf_pr::Float64,
inf_du::Float64,
mu::Float64,
d_norm::Float64,
regularization_size::Float64,
alpha_du::Float64,
alpha_pr::Float64,
ls_trials::Cint) # Using the call back function to get the obj.val
append!(objValvector, obj_value)
append!(iter, iter_count)
return true
end
MOI.set(model, Ipopt.CallbackFunction(), my_callback)
optimize!(model);
f = open(thefile, "a"); # Open the file in append "mode" to add to the existing file
for i in 1:length(iter)
@printf(f, "%-10s %-10s %-10s\n",
k, iter[i], objValvector[i])
end
Do something...
k += 1;
end
I really don't understand why this should not work?
The file looks like this:
答案1
得分: 1
你打开了同一个文件两次(这不应该发生)。
而且你没有flush
缓冲区。
因此,你会看到一部分写入磁盘的内容和一部分没有写入磁盘的内容混合在一起。
在第四行和代码结尾处使用close(f)
。或者只打开一次。根据你的其他代码和情景,你可能还想使用flush(f)
。
英文:
You open the same file twice (which should not happen).
And you do not flush
the buffer.
Hence you are seeing a mix of what made to the disk and what did not make to the disk.
close(f)
in the fourth line and at the end of the code. Or just open it once. Depending on your other code and scenario you might want to flush(f)
as well.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论