# 2 modes: 'only_reaches' and 'free_run', 'free_run_with_feedback' mode = 'free_run' # 2 modes: 'from_ID' and 'from_ANN' (where muscle excitations come from) excite_mode = 'from_ID' # used only for 'free_run' duration = 7 # load in model and experiment current_model = model.load('upper_arm_0') current_experiment = model.load('8-17-20') current_muscle_tracker = model.load('test2') current_simulation = model.Simulation(sim_name, current_model, f_s) # whether or not to manually set the model's initial joint angles, if false, # initial joint angles will be obtained from the loaded experiment manual_init = False init_joint_angles = [] for joint_data in current_experiment.joints: init_joint_angles.append(joint_data.angle[0]) manual_init_joint_angles = [1.5708, 3.1416] for i, joint_data in enumerate(current_simulation.joints): if manual_init == True: joint_data.angle.append(manual_init_joint_angles[i]) elif manual_init == False:
def main(args): GRAPHICS = bool(args.graphics) STIME = int(args.stime) SDIR = args.save_dir if SDIR[-1] != '/': SDIR += '/' DUMP = int(args.dump) LOAD = int(args.load) SEED = int(args.seed) if args.seed is not None else None log_sensors = open(SDIR + "log_sensors", "w") log_cont_sensors = open(SDIR + "log_cont_sensors", "w") log_position = open(SDIR + "log_position", "w") log_predictions = open(SDIR + "log_predictions", "w") log_targets = open(SDIR + "log_targets", "w") log_weights = open(SDIR + "log_weights", "w") log_trials = open(SDIR + "log_trials", "w") dumpfile = SDIR + "dumped_robot" if LOAD: print "loading ..." with gzip.open(dumpfile, 'rb') as f: (simulation, state) = pickle.load(f) rng = np.random.RandomState(simulation.seed) rng.set_state(state) simulation.rng = rng else: if SEED is not None: rng = np.random.RandomState(SEED) simulation = model.Simulation(rng) else: simulation = model.Simulation() SEED = simulation.seed with open(SDIR + "seed", "w") as f: f.write("%d" % SEED) simulation.log_sensors = log_sensors simulation.log_cont_sensors = log_cont_sensors simulation.log_position = log_position simulation.log_predictions = log_predictions simulation.log_targets = log_targets simulation.log_weights = log_weights simulation.log_trials = log_trials print "simulating ..." if GRAPHICS: from model import plotter plotter.graph_main(simulation) else: bar = progressbar.ProgressBar(maxval=STIME, widgets=[ progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage() ], term_width=30) bar.start() for t in range(STIME): simulation.step() bar.update(t + 1) bar.finish() if DUMP: print "dumping ..." with gzip.open(dumpfile, 'wb') as f: state = simulation.rng.get_state() simulation.init_streams() pickle.dump((simulation, state), f)
x = 0 y = 0 for energy in energies: # Define calorimeter mycal.reset() print("* Initialising incident particle *") # particle properties electron = model.Electron(0.0, x, y, energy, 0, 0) print("Energy: ", energy) print("* ...SIMULATING... *") # Run simulation sim = model.Simulation(mycal) tic = time.time() # counts by layer _, counts_layers_run = sim.simulate(electron, sigma, num_runs) toc = time.time() nested_dict = { "Energy": energy, "num_runs": num_runs, "enterx": x, "entery": y, "sigma": sigma, "time_taken": toc - tic } energies_dict[str(energy)] = nested_dict
def resultsView(request): # returns finalDict from getAPI.py # ie. {'How old is your patient?': '38', ... } flow.parse() endem, age, cirr, ALT, HBV_DNA, gender = flow.parse() inputs = "Your " + str(age) + " year old " + str(gender).lower() + " patient " if (cirr == 'Yes'): inputs += "with Cirrhosis." else: inputs += "without Cirrhosis, " inputs += str(ALT).lower() + " ALT level, " inputs += "and " + str(HBV_DNA) + " HBV DNA." #model, labels = rd.generate_model(file='./matrix.xlsx', age=age, female=False) #start = np.zeros(len(model[0])) if (cirr == 'Yes'): start = md.CIRR_STATE elif (ALT == 'Persistently Abnormal' and HBV_DNA == '>20,000 IU/ml'): start = md.CHB_STATE else: start = md.INACTIVE_STATE if (gender == 'Male'): sim_gender = False else: sim_gender = True simulator = md.Simulation(int(age), sim_gender, start, 'e1n') hbv_nat = simulator.get_data(STAGES+1) hcc_nat = simulator.get_data(STAGES+1, term='hcc') cirr_nat = simulator.get_data(STAGES+1, term='cirr') simulator = md.Simulation(int(age), sim_gender, start, 'e1t') hbv_trt = simulator.get_data(STAGES+1) hcc_trt = simulator.get_data(STAGES+1, term='hcc') cirr_trt = simulator.get_data(STAGES+1, term='cirr') hbv_data = [['Stages','Natural History', 'Treatment']] hcc_data = [['Stages','Natural History', 'Treatment']] cirr_data = [['Stages','Natural History', 'Treatment']] for t in range(0, STAGES+1): cirr_data.append([t, cirr_nat[t][2], cirr_trt[t][2]]) hcc_data.append([t, hcc_nat[t][4], hcc_trt[t][4]]) hbv_data.append([t, hbv_nat[t][11], hbv_trt[t][11]]) tableArr = [['Years', 'DeathHBV', '', 'Liver Cancer', '']] if (cirr != 'Yes'): tableArr[0] += ['Cirrhosis', 'Cirrhosis'] sample_indices = [5, 10, 20] for i in sample_indices: entry = [i, str(round(hbv_data[i+1][1],2))+"%", str(round(hbv_data[i+1][2],2))+"%", str(round(hcc_data[i+1][1],2))+"%", str(round(hcc_data[i+1][2],2))+"%"] if (cirr != 'Yes'): entry += [str(round(cirr_data[i+1][1], 2))+"%", str(round(cirr_data[i+1][2], 2))+"%"] tableArr.append(entry) deathDiff = str(round((hbv_data[20+1][1] - hbv_data[20+1][2])/hbv_data[20+1][1], 2)) # Generate recommendation. recommendation = flow.getWhoRec(cirr, age, ALT, HBV_DNA) whoRec = 'Your Patient Needs ' + recommendation t_heading = recommendation if (cirr == 'Yes'): ifCirr = 0 else: ifCirr = 1 # Dump data. dumpDict = { 'deathHBV_Final': json.dumps(hbv_data), 'hcc_Final': json.dumps(hcc_data), 'cirrhosis_Final': json.dumps(cirr_data), # 'deathHBV1': json.dumps(deathHBV1), # 'deathHBV2': json.dumps(deathHBV2), # 'cirrhosis1': json.dumps(cirrhosis1), # 'cirrhosis2': json.dumps(cirrhosis2), # 'hcc1': json.dumps(hcc1), # 'hcc2': json.dumps(hcc2), # 'lt1': json.dumps(lt1), # 'lt2': json.dumps(lt2), 'inputStr': inputs, 'whoRec': whoRec, 'tableArr': tableArr, 'ifCirr': ifCirr, 't_heading': t_heading, 'deathDiff': deathDiff, } return render_to_response('markov/results.html', dumpDict)
def objective(params): Kp, Ki, Kd = params['Kp'], params['Ki'], params['Kd'] current_simulation = model.Simulation(sim_name, current_model, f_s) current_muscle_tracker = model.load('test') # whether or not to manually set the model's initial joint angles, if false, # initial joint angles will be obtained from the loaded experiment manual_init = False init_joint_angles = [] for joint_data in current_experiment.joints: init_joint_angles.append(joint_data.angle[0]) manual_init_joint_angles = [1.5708, 3.1416] for i, joint_data in enumerate(current_simulation.joints): if manual_init == True: joint_data.angle.append(manual_init_joint_angles[i]) elif manual_init == False: joint_data.angle.append(init_joint_angles[i]) for muscle_data in current_muscle_tracker.muscles: if excite_mode == 'from_ID': muscle_data.forward_excite = muscle_data.excitation elif excite_mode == 'from_ANN': # externally produced muscle excitations are written in another script pass t = current_muscle_tracker.t tau = 0.01 for muscle_data in current_muscle_tracker.muscles: muscle_data.forward_excite_interp = UnivariateSpline( t, muscle_data.forward_excite, s=0) def act_derivative(time, act, tau, muscle_data): u = muscle_data.forward_excite_interp(time) dadt = (u - act) / tau return dadt tspan = t xinit = [muscle_data.activation[0]] sol = solve_ivp(act_derivative, [tspan[0], tspan[-1]], xinit, t_eval=tspan, args=(tau, muscle_data), rtol=1e-4) muscle_data.forward_act = list(sol.y[0]) muscle_data.forward_act_interp = UnivariateSpline( t, muscle_data.forward_act, s=0) start_time = current_experiment.reach_times[0] tspan = np.arange(0, start_time, 1 / f_s) current_simulation.t.extend(list(tspan)) # writes the values of the joint angles throughout the rest period rest_samples = current_experiment.rest_time * f_s for j, joint_data in enumerate(current_simulation.joints): joint_data.angle.extend( [float(current_experiment.joints[j].angle_interp(start_time))] * (rest_samples)) current_sample_idx = int(start_time * f_s) feedback_period = samples_before_update / f_s shoulder_previous_error = 0 shoulder_error_integral = 0 shoulder_error_derivative = 0 elbow_previous_error = 0 elbow_error_integral = 0 elbow_error_derivative = 0 total_joint_error = 0 while current_sample_idx < (len(t) - 1): start_time = t[current_sample_idx] tspan = np.linspace(start_time, t[current_sample_idx + samples_before_update], num=5) current_simulation.t.extend(list(tspan)) # initial guesses xinit = [ current_simulation.joints[0].angle[-1], current_simulation.joints[0].velocity[-1], current_simulation.joints[1].angle[-1], current_simulation.joints[1].velocity[-1] ] sol = solve_ivp(f2, [tspan[0], tspan[-1]], xinit, t_eval=tspan, method='Radau', args=(current_model, current_experiment), rtol=1e-4, atol=1e-10) current_simulation.joints[0].angle.extend(list(sol.y[0])) current_simulation.joints[0].velocity.extend(list(sol.y[1])) current_simulation.joints[1].angle.extend(list(sol.y[2])) current_simulation.joints[1].velocity.extend(list(sol.y[3])) current_sample_idx += samples_before_update print(current_sample_idx) # shoulder feedback shoulder_error = current_experiment.joints[0].angle[ current_sample_idx] - current_simulation.joints[0].angle[-1] shoulder_error_integral += shoulder_error shoulder_error_derivative = (shoulder_error - shoulder_previous_error) / feedback_period shoulder_feedback(current_sample_idx, shoulder_error, shoulder_error_integral, shoulder_error_derivative, Kp, Ki, Kd) # elbow feedback elbow_error = current_experiment.joints[1].angle[ current_sample_idx] - current_simulation.joints[1].angle[-1] elbow_error_integral += elbow_error elbow_error_derivative = (elbow_error - elbow_previous_error) / feedback_period elbow_feedback(current_sample_idx, elbow_error, elbow_error_integral, elbow_error_derivative, Kp, Ki, Kd) shoulder_previous_error = shoulder_error elbow_previous_error = elbow_error current_muscle_tracker.trim_acts() for j, joint_data in enumerate(current_experiment.joints): total_joint_error += abs( joint_data.angle[current_sample_idx] - current_simulation.joints[j].angle[current_sample_idx]) if total_joint_error > 1000: total_joint_error = 1000 + (len(t) - current_sample_idx) break return total_joint_error