I have Julia code as shown
if cxp1_v1 < cxp1_v2
d_min = cxp1_v1
d_max = cxp1_v2
else
d_min = cxp1_v2
d_max = cxp1_v1
end
or
if cxp1_v1 < cxp1_v2 d_min, d_max = cxp1_v1, cxp1_v2 else d_min, d_max = cxp1_v2, cxp1_v1 end
Is there a way to accomplish this same in the ternary operator? I tried something like as shown
cxp1_v1 < cxp1_v2 ? d_min, d_max = cxp1_v1, cxp1_v2:d_min, d_max = cxp1_v2, cxp1_v1
but I get
syntax: colon expected in "?" expression
Stacktrace:
[1] top-level scope
# In[422]:11
[2] eval
# ./boot.jl:373 [inlined]
[3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
# Base ./loading.jl:1196
cxp1_v1 < cxp1_v2 ? (d_min, d_max) = (cxp1_v1, cxp1_v2) : (d_min, d_max) = (cxp1_v2, cxp1_v1)
but I would probably write it as:
d_min, d_max = cxp1_v1 < cxp1_v2 ? (cxp1_v1, cxp1_v2) : (cxp1_v2, cxp1_v1)
since it seems a bit easier to read, or even:
d_min, d_max = minmax(cxp1_v1, cxp1_v2)
Related
i am trying to use a code in a paper but the code for gurobi seems changed these days, it showed some error and i want to put the gurobi environment setting below into my optimization.
the gurobi environment setting is below :
function setup_gurobi_env(; quiet_mode = true, method_type = :barrier, use_time_limit = true, time_limit = 60.0)
env = Gurobi.Env()
if quiet_mode
setparams!(env; OutputFlag = 0)
end
if method_type == :barrier
setparams!(env; Method = 2)
elseif method_type == :method3
setparams!(env; Method = 3)
elseif method_type != :default
error("Enter a valid method type for Gurobi.")
end
if use_time_limit
setparams!(env; TimeLimit = time_limit)
end
return env
end
the author of the paper use the method below to use this setting:
function portfolio_simplex_jump_setup(Sigma::Matrix{Float64}, gamma::Float64; gurobiEnv = setup_gurobi_env(method_type = :default, use_time_limit = false))
(d, d2) = size(Sigma)
if d != d2
error("Sigma dimensions don't match")
end
mod = Model(with_optimizer(Gurobi.Optimizer, gurobiEnv))
#variable(mod, w[1:d] >= 0)
#constraint(mod, sum(w[i] for i = 1:d) <= 1)
#constraint(mod, w'*Sigma*w <= gamma)
function local_portfolio_oracle(c::Vector{Float64})
#objective(mod, Min, dot(c, w))
optimize!(mod)
z_ast = objective_value(mod)
w_ast = value.(w)
return (z_ast, w_ast)
end
return c -> local_portfolio_oracle(c)
end
i changed the function into this but it still showed error for not be able to use gurobi since my coding is too old.
function portfolio_simplex_jump_setup(; gurobiEnv = setup_gurobi_env(method_type = :default, use_time_limit = false))
mod = Model(Gurobi.Optimizer)
#variable(mod, 0 <=w[1:d] <= 1)
#constraint(mod, sum(w[i] for i = 1:d) <= 3)
function local_portfolio_oracle(c::Vector{Float64})
#objective(mod, Min, dot(c, w))
optimize!(mod)
z_ast = objective_value(mod)
w_ast = value.(w)
return (z_ast, w_ast)
end
return c -> local_portfolio_oracle(c)
end
i think the problem is in here
mod = Model(with_optimizer(Gurobi.Optimizer, gurobiEnv))
maybe gurobi just upload the new coding method?
Thank you to everyone who replied to me~
This is the current pattern to use Gurobi (taken from one of my academic codes):
const GRB_ENV = Gurobi.Env()
m = Model(()->Gurobi.Optimizer(GRB_ENV))
set_optimizer_attribute(m, "OutputFlag", 0)
set_optimizer_attribute(m, "TimeLimit", 100)
set_optimizer_attribute(m, "MIPGap", 0.001)
set_optimizer_attribute(m, "Threads", min(length(Sys.cpu_info()),16))
thanks for your read and help.
I have download a genebank flat file from NCBI, which contains many entries. I would like to extract three entries from each gene and make them into a table. How to realize it? Thank you much. the file from NCBI---->The table I hope to get
my friend writes it for me with python:
================================================================================
import os
import pandas as pd
from tqdm import tqdm
import sys
def search_line(gene_dict,gene_name,target,info,mode,l):
if '/{}='.format(target) in l:
if len(l.split('"')) == 3:
gene_dict[gene_name][mode].append('{} = '.format(target) + l.split('"')[1].strip('\n'))
keep_read = 0
info = []
else:
info = [l.split('"')[1].strip('\n')]
keep_read = target_list.index(target)
else:
if '"' in l:
info.append(l.strip().strip('"\n'))
if '{} = '.format(target) + ' '.join(info) not in gene_dict[gene_name][mode]:
gene_dict[gene_name][mode].append('{} = '.format(target) + ' '.join(info))
keep_read = 0
info = []
else:
info.append(l.strip())
keep_read = target_list.index(target)
return gene_dict,info,keep_read
def init_frame_dict(gene_dict,ids,mode):
frame_dict = {'gene': gene_dict[ids]['gene'], 'source': mode}
for target in target_list[1:]:
frame_dict[target] = ''
return frame_dict
def gen_frame(gene_dict,flat):
frame = []
for ids in gene_dict.keys():
for mode in gene_dict[ids].keys():
if mode not in extract_list:
continue
# print(mode)
data = gene_dict[ids][mode]
frame_dict = init_frame_dict(gene_dict, ids, mode)
for target_data in data:
for target in target_list[1:]:
if '{} = '.format(target) in target_data:
if frame_dict[target] != '':
frame.append(frame_dict)
# print(frame_dict)
frame_dict = init_frame_dict(gene_dict, ids, mode)
frame_dict[target] = target_data.split('{} = '.format(target))[1]
frame.append(frame_dict)
pd.DataFrame(frame).to_csv('{}.csv'.format(flat[:-5]))
def main():
for flat in os.listdir(path_root):
gene_dict = {}
if flat[-4:] != 'flat':
continue
with open (os.path.join(path_root,flat)) as f:
lines = f.read()
genes = lines.split('/gene=')
skip = False
for gene in tqdm(genes[1:]):
if skip:
break
lines = gene.split('\n')
gene_name = lines[0].split('"')[1]
#init paras
mode = 'init'
target = 'none'
read_mode = 0
info = []
#init dict
if gene_name not in gene_dict:
gene_dict[gene_name] = {'gene':gene_name,'mRNA':[],'ncRNA':[],'CDS':[],'misc_RNA':[],'exon':[],}
#proc lines
for l in lines:
if 'ORIGIN' in l:
skip = True
break
if ' mRNA' in l:
mode = 'mRNA'
elif ' ncRNA' in l:
mode = 'ncRNA'
elif ' CDS' in l:
mode = 'CDS'
elif ' misc_RNA' in l:
mode = 'misc_RNA'
elif ' exon' in l:
mode = 'exon'
# search_line(gene_dict, gene_name, target, info, mode, l)
if '/product=' in l and mode != 'init' or (target == 'product' and read_mode == target_list.index('product')):
target = 'product'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
if '/protein_id=' in l and mode != 'init' or (target == 'protein_id' and read_mode == target_list.index('protein_id')):
target = 'protein_id'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
if '/note=' in l and mode != 'init' or (target == 'note' and read_mode == target_list.index('note')):
target = 'note'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
if '/transcript_id=' in l and mode != 'init' or (target == 'note' and read_mode == target_list.index('transcript_id')):
target = 'transcript_id'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
gen_frame(gene_dict,flat)
if __name__ == '__main__':
target_list = ['none', 'product', 'transcript_id','protein_id','note']
extract_list = ['mRNA']
path_root = 'flats'
if not os.path.exists(path_root):
print('Please put your flat files in flats/ directory !')
sys.exit()
if len(os.listdir(path_root)) == 0:
print('No files found in flats/ directory.')
sys.exit()
main()
How do you guys handle console input validation? In C++, case/switch is my goto...
I was trying a recursive function but was getting locked in lower levels. Plus that might be overdoing it. I did manage a while loop with an "exclusive or" but, that is not really scalable.
function prob6()
println("Pick a number; any number:")
x = readline(stdin)
y = parse(Int64, x)
z = 0
println("Select 1 or 2")
p1 = readline(stdin)
p2 = parse(Int64, p1)
select = p2
while xor((p2 == 1), (p2 == 2)) == false
println("Select 1 or 2")
p1 = readline(stdin)
p2 = parse(Int64, p1)
select = p2
end
if select == 1
for i in 1:y
print("$i ")
z = z + i
end
else
z = 1
for i in 1:y
print("$i ")
z = z * i
end
end
println(z)
end
Any alternatives?
There are many ways. I usually create a validation loop to check the type of the input item, and will use tryparse instead of parse, since it will not throw an error if input is malformed:
function queryprompt(query, typ)
while true
print(query, ": ")
choice = uppercase(strip(readline(stdin)))
if (ret = tryparse(typ, choice)) != nothing
return ret
end
println()
end
end
n = queryprompt("Integer please", Int64)
println(n)
x = queryprompt("Float please", Float64)
println(x)
So I have two vector of vectors like:
matchings_vec = Vector{Vector{Vector{Vector{Any}}}}(num_tilt1)
Minfoall_vec = Vector{Vector{Vector{Vector{Vector{Vector{Float64}}}}}}(num_tilt1)
I defined it as:
matchings_vec = [Vector{Any}() for i in 1:num_tilt1]
Minfoall_vec = [Vector{Float64}() for i in 1:num_tilt1]
Then I am trying to resize the inner vectors like:
for tt = 1:num_tilt1
t_tt = t[tt] #; t1 = t_tt; t2 = 1;
if t_tt == 1
num_rot1 = 1
else
num_rot1 = round(Int, num_rot_t2 * t_tt/2)
if rem.(num_rot1, 2) == 1.0
num_rot1 += 1
end
num_rot1 /= 2
end
num_rot1 = round(Int, num_rot1)
#resize!(matchings_vec[tt], num_rot1)
matchings_vec[tt] = Vector{Any}(num_rot1)
#resize!(Minfoall_vec[tt], num_rot1)
Minfoall_vec[tt] = Vector{Float64}(num_rot1)
for rr = 1:num_rot1
num_tilt2 = round(Int, num_tilt2)
#resize!(matchings_vec[tt][rr], num_tilt2)
matchings_vec[tt][rr] = Vector{Any}(num_tilt2)
#resize!(Minfoall_vec[tt][rr], num_tilt2)
Minfoall_vec[tt][rr] = Vector{Float64}(num_tilt2)
for tt2 = 1:num_tilt2
t_im2 = t[tt2]
#t_im2_1 = t_im2; t_im2_2 = 1;
if t_im2 == 1
num_rot1_2 = 1
else
num_rot1_2 = round(Int, num_rot_t2 * t_im2/2)
if rem.(num_rot1_2, 2) == 1.0
num_rot1_2 += 1
end
num_rot1_2 /= 2
end
num_rot1_2 = round(Int, num_rot1_2)
#resize!(matchings_vec[tt][rr][tt2], num_rot1_2)
matchings_vec[tt][rr][tt2] = Vector{Any}(num_rot1_2)
#resize!(Minfoall_vec[tt][rr][tt2], num_rot1_2)
Minfoall_vec[tt][rr][tt2] = Vector{Float64}(num_rot1_2)
end
end
end
I am getting this error:
MethodError: Cannot convert an object of type Array{Float64,1} to an
object of type Float64 This may have arisen from a call to the
constructor Float64(...), since type constructors fall back to convert
methods.
Stacktrace: [1] setindex!(::Array{Float64,1}, ::Array{Float64,1},
::Int64) at ./array.jl:578 [2] macro expansion at ./In[32]:22
[inlined] [3] anonymous at ./:?
Can you suggest what I am doing wrong? Thanks!
Im using chainer and im try to do topic modeling. The code for the training phase contains the following:
optimizer = O.Adam()
optimizer.setup(self.train_model)
clip = chainer.optimizer.GradientClipping(5.0)
optimizer.add_hook(clip)
j = 0
msgs = defaultdict(list)
for epoch in range(epochs):
print "epoch : ",epoch
data = prepare_topics(cuda.to_cpu(self.train_model.mixture.weights.W.data).copy(),
cuda.to_cpu(self.train_model.mixture.factors.W.data).copy(),
cuda.to_cpu(self.train_model.sampler.W.data).copy(),
self.words)
top_words = print_top_words_per_topic(data)
if j % 100 == 0 and j > 100:
coherence = topic_coherence(top_words)
for j in range(self.n_topics):
print j, coherence[(j, 'cv')]
kw = dict(top_words=top_words, coherence=coherence, epoch=epoch)
data['doc_lengths'] = self.doc_lengths
data['term_frequency'] = self.term_frequency
for d, f in utils.chunks(self.batchsize, self.doc_ids, self.flattened):
t0 = time.time()
self.train_model.cleargrads()
l = self.train_model.fit_partial(d.copy(), f.copy(), update_words = update_words, update_topics = update_topics)
prior = self.train_model.prior()
loss = prior * self.fraction
loss.backward()
optimizer.update()
msg = ("J:{j:05d} E:{epoch:05d} L:{loss:1.3e} "
"P:{prior:1.3e} R:{rate:1.3e}")
prior.to_cpu()
loss.to_cpu()
t1 = time.time()
dt = t1 - t0
rate = self.batchsize / dt
msgs["E"].append(epoch)
msgs["L"].append(float(l))
j += 1
logs = dict(loss=float(l), epoch=epoch, j=j, prior=float(prior.data), rate=rate)
print msg.format(**logs)
print "\n ================================= \n"
#serializers.save_hdf5("lda2vec.hdf5", self.model)
msgs["loss_per_epoch"].append(float(l))
whn i execute the code i get for example:
J:00200 E:00380 L:0.000e+00 P:-2.997e+04 R:2.421e+04
only the L(loss) dont change, can someone please help to know why this value remain zero?