Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 50 additions & 24 deletions optimizer/Core.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ def htmlTable(self,header_list,data):
def htmlPciture(self,inp):
return "<p align=\"center\"><img style=\"border:none;\" src=\""+inp+"\" ></p>"

def htmlPdf(self, inp):
return "<p align=\"center\"><embed src = \""+inp+"#toolbar=0&navpanes=0&scrollbar=0\" width = \"800px\" height = \"630px\" /></p>"

def Print(self):
print([self.option_handler.GetFileOption(),
Expand All @@ -136,11 +138,13 @@ def FirstStep(self,args):
self.option_handler.SetFileOptions(args.get("file"))
self.option_handler.SetInputOptions(args.get("input"))

self.data_handler.Read([self.option_handler.input_dir],self.option_handler.input_size,self.option_handler.input_scale,self.option_handler.input_length,self.option_handler.input_freq,self.option_handler.type[-1])


if self.option_handler.type[-1]=='features':
self.option_handler.input_size= len(self.data_handler.features_data['stim_amp'])
stim_type = self.option_handler.type[-1]
if stim_type == "hippounit":
self.option_handler.SetSimParam(["hippounit", []])
else:
self.data_handler.Read([self.option_handler.input_dir],self.option_handler.input_size,self.option_handler.input_scale,self.option_handler.input_length,self.option_handler.input_freq,stim_type)
if stim_type == "features":
self.option_handler.input_size= len(self.data_handler.features_data['stim_amp'])

def LoadModel(self,args):
"""
Expand All @@ -156,6 +160,8 @@ def LoadModel(self,args):
if self.option_handler.GetSimParam()[0]=="Neuron":
self.option_handler.SetModelOptions(args.get("model"))
self.model_handler=modelHandlerNeuron(self.option_handler.model_path,self.option_handler.model_spec_dir,self.option_handler.base_dir)
elif self.option_handler.GetSimParam()[0] == "hippounit":
return
else:
self.model_handler=externalHandler(self.option_handler.GetSimParam()[1])
self.model_handler.SetNParams(self.option_handler)
Expand Down Expand Up @@ -347,7 +353,7 @@ def ThirdStep(self,args):
#tmp.append(args.get("starting_points"))
self.option_handler.SetOptimizerOptions(tmp)

if self.option_handler.type[-1]!='features':
if self.option_handler.type[-1]!='features' and self.option_handler.type[-1]!='hippounit':
if self.option_handler.run_controll_dt<self.data_handler.data.step:
print("re-sampling because integration step is smaller then data step")
print((self.option_handler.run_controll_dt,self.data_handler.data.step))
Expand Down Expand Up @@ -376,7 +382,9 @@ def ThirdStep(self,args):

exec("self.optimizer="+self.option_handler.algorithm_name+"(self.data_handler,self.option_handler)")

if self.option_handler.type[-1]!= 'features':
if self.option_handler.type[-1] == 'hippounit':
self.option_handler.feat_str = "" # TODO
elif self.option_handler.type[-1]!= 'features':
self.option_handler.feat_str=", ".join([self.ffun_mapper[x.__name__] for x in self.option_handler.feats])
else:
self.option_handler.feat_str=", ".join(self.option_handler.feats)
Expand Down Expand Up @@ -435,22 +443,29 @@ def FourthStep(self,args={}):
A report of the results is generated in the form of a html document.
:param args: currently not in use
"""
if self.option_handler.type[-1] == 'hippounit':
self.optimizer.fit_obj.is_figures_saved = True

self.best_fit=self.optimizer.fit_obj.single_objective_fitness([self.optimizer.fit_obj.normalize(self.optimal_params)],delete_model=False)
self.final_result=[]
self.error_comps=[]
if self.option_handler.type[-1]!= 'features':
k_range=self.data_handler.number_of_traces()
if self.option_handler.type[-1] == 'hippounit':
k_range = 1
self.error_comps.append(self.optimizer.fit_obj.getTestErrorComponents())
else:
k_range=len(self.data_handler.features_data["stim_amp"])

for k in range(k_range):
self.error_comps.append(self.optimizer.fit_obj.getErrorComponents(k, self.optimizer.fit_obj.model_trace[k]))
trace_handler=open("result_trace"+str(k)+".txt","w+")
for l in self.optimizer.fit_obj.model_trace[k]:
trace_handler.write(str(l))
trace_handler.write("\n")
trace_handler.close()
self.final_result.append(self.optimizer.fit_obj.model_trace[k])
if self.option_handler.type[-1]!= 'features':
k_range=self.data_handler.number_of_traces()
else:
k_range=len(self.data_handler.features_data["stim_amp"])

for k in range(k_range):
self.error_comps.append(self.optimizer.fit_obj.getErrorComponents(k, self.optimizer.fit_obj.model_trace[k]))
trace_handler=open("result_trace"+str(k)+".txt","w+")
for l in self.optimizer.fit_obj.model_trace[k]:
trace_handler.write(str(l))
trace_handler.write("\n")
trace_handler.close()
self.final_result.append(self.optimizer.fit_obj.model_trace[k])

if isinstance(self.optimizer.fit_obj.model, externalHandler):
self.optimizer.fit_obj.model.record[0]=[]
Expand All @@ -469,7 +484,15 @@ def FourthStep(self,args={}):
tmp_str+=self.htmlTable(["Parameter Name","Minimum","Maximum","Optimum"], tmp_list)+"\n"
tmp_str+="<center><p>"+self.htmlStrBold("Fitness: ")
tmp_str+=self.htmlStrBold(str(self.best_fit))+"</p></center>\n"
tmp_str+=self.htmlPciture("result_trace.png")+"\n"
if self.option_handler.type[-1] == "hippounit":
hippounit_settings = self.optimizer.fit_obj.model.settings
model_name = hippounit_settings["model"]["name"]
test_name = 'somaticfeat'
dataset_name = hippounit_settings["model"]["dataset"]
pdf_path = "output/figs/{}_{}/{}/traces.pdf".format(test_name, dataset_name, model_name)
tmp_str+=self.htmlPdf(pdf_path)+"\n"
else:
tmp_str+=self.htmlPciture("result_trace.png")+"\n"
for k in list(self.option_handler.GetOptimizerOptions().keys()):
tmp_str+="<p><b>"+k+" =</b> "+str(self.option_handler.GetOptimizerOptions()[k])+"</p>\n"
tmp_str+="<p><b>feats =</b> "+self.option_handler.feat_str +"</p>\n"
Expand All @@ -483,7 +506,7 @@ def FourthStep(self,args={}):
tmp_list=[]
for t in self.error_comps:
for c in t:
if self.option_handler.type[-1]!='features':
if self.option_handler.type[-1]!='features' and self.option_handler.type[-1]!= 'hippounit':
#tmp_str.append( "*".join([str(c[0]),c[1].__name__]))
tmp_list.append([self.ffun_mapper[c[1].__name__],
str(c[2]),
Expand All @@ -507,7 +530,7 @@ def FourthStep(self,args={}):
tmp[1]+=c[t_idx][2]
tmp[2]=c[t_idx][0]
tmp[3]+=c[t_idx][2]*c[t_idx][0]
if self.option_handler.type[-1]!='features':
if self.option_handler.type[-1]!='features' and self.option_handler.type[-1]!= 'hippounit':
tmp[0]=self.ffun_mapper[c[t_idx][1].__name__]
else:
tmp[0]=(c[t_idx][1])
Expand All @@ -525,8 +548,11 @@ def FourthStep(self,args={}):
target_dict = {"data_type":self.option_handler.type[-1],"file_name":self.option_handler.input_dir.split('/')[-1],"number_of_traces":k_range,"stim_delay":self.option_handler.stim_del,
"stim_duration":self.option_handler.stim_dur}
json_var = {"model":self.name,"optimization":opt_dict,"parameters":param_dict,"error_function":error_dict, "algorithm":alg_dict,"target_data":target_dict}

if self.option_handler.type[-1]=='features':

if self.option_handler.type[-1]=='hippounit':
with open('metadata.json', 'w+') as outfile:
json.dump(json_var, outfile, indent=4)
elif self.option_handler.type[-1]=='features':
with open(self.option_handler.input_dir, 'r') as outfile:
input_features=json.load(outfile)
amp_dict={amp_vals:[] for amp_vals in input_features["stimuli"]["amplitudes"]}
Expand Down
75 changes: 38 additions & 37 deletions optimizer/cmd_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def main(fname, param=None):
"""
try:
with open(fname, "r") as f:
json_data = json.load(f)
json_data = json.load(f)
except IOError as ioe:
print(ioe)
sys.exit("File not found!\n")
Expand All @@ -46,45 +46,46 @@ def main(fname, param=None):
core.ThirdStep(kwargs)
core.FourthStep()
print("resulting parameters: ", core.optimal_params)
fig = figure(1, figsize=(7, 6))
fig = figure(figsize=(7, 6))
axes = fig.add_subplot(111)
exp_data = []
model_data = []
if core.option_handler.type[-1] != 'features':
for n in range(core.data_handler.number_of_traces()):
exp_data.extend(core.data_handler.data.GetTrace(n))
model_data.extend(core.final_result[n])
no_traces = core.data_handler.number_of_traces()
else:
for n in range(len(core.data_handler.features_data["stim_amp"])):
model_data.extend(core.final_result[n])
no_traces = len(core.data_handler.features_data["stim_amp"])
if core.option_handler.type[-1] != 'features':
t = int(ceil(core.option_handler.input_length))
else:
t = int(ceil(core.option_handler.run_controll_tstop))
step = core.option_handler.run_controll_dt
axes.set_xticks([n for n in range(0, int((t * no_traces) / (step)), int((t * no_traces) / (step) / 5.0)) ])
axes.set_xticklabels([str(n) for n in range(0, int(t * no_traces), int((t * no_traces) / 5))])
if core.option_handler.type[-1] != 'hippounit':
if core.option_handler.type[-1] != 'features':
for n in range(core.data_handler.number_of_traces()):
exp_data.extend(core.data_handler.data.GetTrace(n))
model_data.extend(core.final_result[n])
no_traces = core.data_handler.number_of_traces()
else:
for n in range(len(core.data_handler.features_data["stim_amp"])):
model_data.extend(core.final_result[n])
no_traces = len(core.data_handler.features_data["stim_amp"])
if core.option_handler.type[-1] != 'features' and core.option_handler.type[-1] != 'hippounit':
t = int(ceil(core.option_handler.input_length))
else:
t = int(ceil(core.option_handler.run_controll_tstop))
step = core.option_handler.run_controll_dt
axes.set_xticks([n for n in range(0, int((t * no_traces) / (step)), int((t * no_traces) / (step) / 5.0)) ])
axes.set_xticklabels([str(n) for n in range(0, int(t * no_traces), int((t * no_traces) / 5))])

axes.set_xlabel("time [ms]")
if core.option_handler.type[-1]!= 'features':
_type = core.data_handler.data.type
else:
_type = "Voltage" if core.option_handler.run_controll_record =="v" else "Current" if core.option_handler.run_controll_record == "c" else ""
axes.set_ylabel(_type + " [" + core.option_handler.input_scale + "]")
if core.option_handler.type[-1]!= 'features':
axes.plot(list(range(0, len(exp_data))), exp_data)
axes.plot(list(range(0, len(model_data))), model_data, 'r')
axes.legend(["target", "model"])
else:
axes.plot(list(range(0, len(model_data))), model_data, 'r')
axes.legend(["model"])
fig.savefig("result_trace.png", dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1)
fig.savefig("result_trace.eps", dpi=None, facecolor='w', edgecolor='w')
fig.savefig("result_trace.svg", dpi=None, facecolor='w', edgecolor='w')

axes.set_xlabel("time [ms]")
if core.option_handler.type[-1]!= 'features' and core.option_handler.type[-1] != 'hippounit':
_type = core.data_handler.data.type
else:
_type = "Voltage" if core.option_handler.run_controll_record =="v" else "Current" if core.option_handler.run_controll_record == "c" else ""
axes.set_ylabel(_type + " [" + core.option_handler.input_scale + "]")
if core.option_handler.type[-1]!= 'features' and core.option_handler.type[-1] != 'hippounit':
axes.plot(list(range(0, len(exp_data))), exp_data)
axes.plot(list(range(0, len(model_data))), model_data, 'r')
axes.legend(["target", "model"])
else:
axes.plot(list(range(0, len(model_data))), model_data, 'r')
axes.legend(["model"])
fig.savefig("result_trace.png", dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1)
fig.savefig("result_trace.eps", dpi=None, facecolor='w', edgecolor='w')
fig.savefig("result_trace.svg", dpi=None, facecolor='w', edgecolor='w')


Loading