Skip to content

Commit a769cec

Browse files
committed
reworked simulation or evolution in run_main python script
1 parent aba71f7 commit a769cec

File tree

4 files changed

+77
-25
lines changed

4 files changed

+77
-25
lines changed

helper_funcs.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
dir_name = None
2+
def rename_file(file_name):
3+
if dir_name is None: return file_name
4+
return dir_name + '/' + file_name

load_data.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import numpy as np
77
from matplotlib import pyplot as plt
88
import random
9+
import helper_funcs as hf
910

1011
N_muscles = 24; # Number of muscles alongside the body
1112
N_units = 10; # Number of neural units in VNC
@@ -20,7 +21,7 @@
2021

2122
### Worm neuron/muscle activation
2223

23-
act_data = np.loadtxt('act.dat').T
24+
act_data = np.loadtxt(hf.rename_file('act.dat')).T
2425

2526
offset=1
2627

@@ -64,7 +65,7 @@
6465

6566
### Worm body curvature
6667

67-
curv_data = np.loadtxt('curv.dat')
68+
curv_data = np.loadtxt(hf.rename_file('curv.dat'))
6869
curv_data_less_time = curv_data.T[1:,:]
6970

7071
axs[3, 1].set_title('Body curvature', fontsize=title_font_size)
@@ -73,7 +74,7 @@
7374
### Body position
7475

7576

76-
body_data = np.loadtxt('body.dat').T
77+
body_data = np.loadtxt(hf.rename_file('body.dat')).T
7778

7879
tmax = 1520
7980
if tmax >= body_data.shape[1]:
@@ -103,7 +104,7 @@
103104
axs[3, 0].set_aspect('equal')
104105

105106

106-
plt.savefig("ExampleActivity.png", bbox_inches="tight", dpi=300)
107+
plt.savefig(hf.rename_file("ExampleActivity.png"), bbox_inches="tight", dpi=300)
107108

108109
plt.show()
109110

main.cpp

+12-9
Original file line numberDiff line numberDiff line change
@@ -270,16 +270,18 @@ int main (int argc, const char* argv[])
270270

271271
if (argc==2) randomseed += atoi(argv[1]);
272272

273+
bool do_evol = 1;
273274

274275
if (argc>2){
275276

276277
const bool is_even = ((argc-1) % 2) == 0; //todo: check even
277278

278279
bool seed_flag = 1;
279-
280+
280281
for (int arg = 1; arg<argc; arg+=2)
281282
{
282-
//if (strcmp(argv[arg],"--doevol")==0) {do_evol = atoi(argv[arg+1]);}
283+
if (strcmp(argv[arg],"--doevol")==0) do_evol = atoi(argv[arg+1]);
284+
if (strcmp(argv[arg],"--folder")==0) dir_name = argv[arg+1];
283285
if (seed_flag){
284286
if (strcmp(argv[arg],"-R")==0) randomseed = atoi(argv[arg+1]);
285287
if (strcmp(argv[arg],"-r")==0) randomseed += atoi(argv[arg+1]);
@@ -291,28 +293,29 @@ int main (int argc, const char* argv[])
291293

292294
}
293295

294-
bool do_evol;
296+
/* bool do_evol;
295297
cout << "Do you want to perform an evolutionary search (E) or run a simulation (S) ";
296298
string ans;
297299
while(true){
298300
getline(cin,ans);
299301
if (ans == "E" || ans == "e") {do_evol = 1;break;}
300302
if (ans == "S" || ans == "s") {do_evol = 0;break;}
301303
cout << "Try again ";
302-
};
304+
}; */
303305

304306
InitializeBodyConstants();
305307

306308
if (do_evol){
307309

310+
/*
308311
std::cout << "Directory name to save genotype data, leave blank for current directory: ";
309312
getline(cin,dir_name);
310313
//TODO: check for directory name safety, length
311314
while (dir_name != "" && mkdir(dir_name.c_str(), 0777) != 0){
312315
//cerr << "Error : " << strerror(errno) << endl;
313316
std::cout << "Folder exists. Try again or leave blank for current directory: ";
314317
getline(cin,dir_name);
315-
}
318+
} */
316319

317320

318321

@@ -363,22 +366,22 @@ int main (int argc, const char* argv[])
363366
evolfile.close();
364367
#endif
365368

366-
std::cout << "Finished, now rerunning simulation with the best fit...\n";
369+
std::cout << "Finished, now saving the best fit...\n";
367370

368371
}
369372

370373
else
371374
{
372375

373-
std::cout << "Directory name for saved genotype data, leave blank for current directory: ";
376+
/* std::cout << "Directory name for saved genotype data, leave blank for current directory: ";
374377
getline(cin,dir_name);
375378
//TODO: check for directory name safety, length
376379
struct stat st;
377380
while (dir_name != "" && stat(dir_name.c_str(), &st) != 0){
378381
//cerr << "Error : " << strerror(errno) << endl;
379382
std::cout << "Folder does not exist, try again or leave blank for current directory: ";
380383
getline(cin,dir_name);
381-
}
384+
} */
382385

383386
RandomState rs;
384387
long seed = static_cast<long>(time(NULL));
@@ -389,7 +392,7 @@ int main (int argc, const char* argv[])
389392
Best >> best;
390393
save_traces(best, rs);
391394

392-
std::cout << "Finished final run\n" << endl;
395+
std::cout << "Finished run, saving data\n" << endl;
393396

394397
}
395398

run_main.py

+56-12
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,81 @@
11
import subprocess
22
import argparse
3+
import os
4+
import sys
5+
import helper_funcs as hf
6+
7+
def make_directory(directory_name):
8+
try:
9+
os.mkdir(directory_name)
10+
print(f"Directory '{directory_name}' created successfully.")
11+
return True
12+
except FileExistsError:
13+
print(f"Directory '{directory_name}' already exists.")
14+
return False
15+
except PermissionError:
16+
print(f"Permission denied: Unable to create '{directory_name}'.")
17+
sys.exit(1)
18+
except Exception as e:
19+
print(f"An error occurred: {e}")
20+
sys.exit(1)
21+
322

423
def run_cpp_program():
5-
24+
625
parser=argparse.ArgumentParser(description="argument parser")
726

827
parser.add_argument("-R", "--Rand_seed", type=int, nargs='?', default=42)
928
parser.add_argument("-r", "--rand_seed", type=int, nargs='?', default=42)
1029
parser.add_argument('-p', "--pop_size", type=int, nargs='?', default=96)
1130
parser.add_argument('-d', "--duration", type=int, nargs='?', default=24)
12-
31+
32+
while True:
33+
do_evol_str = input("Do you want to perform an evolutionary search (E) or run a simulation (S)? ")
34+
if do_evol_str == "E":
35+
do_evol = 1
36+
while True:
37+
folder_name = input("Please enter the name of a folder to store data: ")
38+
if make_directory(folder_name): break
39+
break
40+
if do_evol_str == "S":
41+
do_evol = 0
42+
while True:
43+
folder_name = str(input("Please enter the name of a folder to read data: "))
44+
if os.path.isdir(folder_name): break
45+
print("Folder does not exist.")
46+
break
47+
48+
1349
args=parser.parse_args()
1450
if args.Rand_seed is not None:
15-
cmd = ['./main', '-R', str(args.Rand_seed), '-p', str(args.pop_size), '-d', str(args.duration)]
51+
cmd = ['./main', '-R', str(args.Rand_seed)]
1652
else:
17-
cmd = ['./main', '-r', str(args.rand_seed), '-p', str(args.pop_size), '-d', str(args.duration)]
18-
53+
cmd = ['./main', '-r', str(args.rand_seed)]
54+
55+
cmd += ['-p', str(args.pop_size),
56+
'-d', str(args.duration),
57+
'--doevol', str(do_evol),
58+
'--folder', folder_name]
59+
1960
# Run the C++
20-
#result = subprocess.run(cmd, capture_output=True, text=True)
61+
result = subprocess.run(cmd, capture_output=True, text=True)
2162
#result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
2263
#output, errors = result.communicate()
2364

24-
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
25-
output = p.communicate(input='some data'.encode())[0]
26-
27-
print(output)
65+
#p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
66+
67+
#print(output)
2868

29-
""" if result.stdout:
69+
if result.stdout:
3070
print(result.stdout)
3171

3272
if result.stderr:
3373
print("Error:")
34-
print(result.stderr) """
74+
print(result.stderr)
75+
76+
if not do_evol:
77+
hf.dir_name = folder_name
78+
import load_data
3579

3680
if __name__ == "__main__":
3781
run_cpp_program()

0 commit comments

Comments
 (0)