void exec( ) throw( general_error ) { //if ( 0 >= load_library("typelib") ) throw exec_error( "tcsgeneric_solar", util::format("could not load the tcs type library.") ); //bool debug_mode = (__DEBUG__ == 1); // When compiled in VS debug mode, this will use the trnsys weather file; otherwise, it will attempt to open the file with name that was passed in // type260_genericsolar uses 'poa_beam' from the weather reader, which is not available from a "trnsys_weatherreader", so this must be set to false bool debug_mode = false; //Add weather file reader unit int weather = 0; if(debug_mode) weather = add_unit("trnsys_weatherreader", "TRNSYS weather reader"); else weather = add_unit("weatherreader", "TCS weather reader"); // Add time-of-use reader int tou = add_unit("tou_translator", "Time of Use Translator"); //Add Physical Solar Field Model int type260_genericsolar = add_unit( "sam_mw_gen_type260", "Generic solar model" ); if(debug_mode) { set_unit_value( weather, "file_name", "C:/svn_NREL/main/ssc/tcsdata/typelib/TRNSYS_weather_outputs/tucson_trnsys_weather.out" ); set_unit_value( weather, "i_hour", "TIME" ); set_unit_value( weather, "i_month", "month" ); set_unit_value( weather, "i_day", "day" ); set_unit_value( weather, "i_global", "GlobalHorizontal" ); set_unit_value( weather, "i_beam", "DNI" ); set_unit_value( weather, "i_diff", "DiffuseHorizontal" ); set_unit_value( weather, "i_tdry", "T_dry" ); set_unit_value( weather, "i_twet", "T_wet" ); set_unit_value( weather, "i_tdew", "T_dew" ); set_unit_value( weather, "i_wspd", "WindSpeed" ); set_unit_value( weather, "i_wdir", "WindDir" ); set_unit_value( weather, "i_rhum", "RelHum" ); set_unit_value( weather, "i_pres", "AtmPres" ); set_unit_value( weather, "i_snow", "SnowCover" ); set_unit_value( weather, "i_albedo", "GroundAlbedo" ); set_unit_value( weather, "i_poa", "POA" ); set_unit_value( weather, "i_solazi", "Azimuth" ); set_unit_value( weather, "i_solzen", "Zenith" ); set_unit_value( weather, "i_lat", "Latitude" ); set_unit_value( weather, "i_lon", "Longitude" ); set_unit_value( weather, "i_shift", "Shift" ); } else { //Set weatherreader parameters set_unit_value_ssc_string( weather, "file_name" ); set_unit_value_ssc_double( weather, "track_mode" ); //, 1 ); set_unit_value_ssc_double( weather, "tilt" ); //, 0 ); set_unit_value_ssc_double( weather, "azimuth" ); //, 0 ); } set_unit_value_ssc_matrix(tou, "weekday_schedule"); // tou values from control will be between 1 and 9 set_unit_value_ssc_matrix(tou, "weekend_schedule"); //Set parameters set_unit_value_ssc_double(type260_genericsolar, "latitude" ); //, 35); set_unit_value_ssc_double(type260_genericsolar, "longitude" ); //, -117); set_unit_value_ssc_double(type260_genericsolar, "istableunsorted"); set_unit_value_ssc_matrix(type260_genericsolar, "OpticalTable" ); //, opt_data); //set_unit_value_ssc_matrix(type260_genericsolar, "OpticalTableUns" ); set_unit_value_ssc_double(type260_genericsolar, "timezone" ); //, -8); set_unit_value_ssc_double(type260_genericsolar, "theta_stow" ); //, 170); set_unit_value_ssc_double(type260_genericsolar, "theta_dep" ); //, 10); set_unit_value_ssc_double(type260_genericsolar, "interp_arr" ); //, 1); set_unit_value_ssc_double(type260_genericsolar, "rad_type" ); //, 1); set_unit_value_ssc_double(type260_genericsolar, "solarm" ); //, solarm); set_unit_value_ssc_double(type260_genericsolar, "T_sfdes" ); //, T_sfdes); set_unit_value_ssc_double(type260_genericsolar, "irr_des" ); //, irr_des); set_unit_value_ssc_double(type260_genericsolar, "eta_opt_soil" ); //, eta_opt_soil); set_unit_value_ssc_double(type260_genericsolar, "eta_opt_gen" ); //, eta_opt_gen); set_unit_value_ssc_double(type260_genericsolar, "f_sfhl_ref" ); //, f_sfhl_ref); set_unit_value_ssc_array(type260_genericsolar, "sfhlQ_coefs" ); //, [1,-0.1,0,0]); set_unit_value_ssc_array(type260_genericsolar, "sfhlT_coefs" ); //, [1,0.005,0,0]); set_unit_value_ssc_array(type260_genericsolar, "sfhlV_coefs" ); //, [1,0.01,0,0]); set_unit_value_ssc_double(type260_genericsolar, "qsf_des" ); //, q_sf); set_unit_value_ssc_double(type260_genericsolar, "w_des" ); //, w_gr_des); set_unit_value_ssc_double(type260_genericsolar, "eta_des" ); //, eta_cycle_des); set_unit_value_ssc_double(type260_genericsolar, "f_wmax" ); //, 1.05); set_unit_value_ssc_double(type260_genericsolar, "f_wmin" ); //, 0.25); set_unit_value_ssc_double(type260_genericsolar, "f_startup" ); //, 0.2); set_unit_value_ssc_double(type260_genericsolar, "eta_lhv" ); //, 0.9); set_unit_value_ssc_array(type260_genericsolar, "etaQ_coefs" ); //, [0.9,0.1,0,0,0]); set_unit_value_ssc_array(type260_genericsolar, "etaT_coefs" ); //, [1,-0.002,0,0,0]); set_unit_value_ssc_double(type260_genericsolar, "T_pcdes" ); //, 21); set_unit_value_ssc_double(type260_genericsolar, "PC_T_corr" ); //, 1); set_unit_value_ssc_double(type260_genericsolar, "f_Wpar_fixed" ); //, f_Wpar_fixed); set_unit_value_ssc_double(type260_genericsolar, "f_Wpar_prod" ); //, f_Wpar_prod); set_unit_value_ssc_array(type260_genericsolar, "Wpar_prodQ_coefs" ); //, [1,0,0,0]); set_unit_value_ssc_array(type260_genericsolar, "Wpar_prodT_coefs" ); //, [1,0,0,0]); set_unit_value_ssc_array(type260_genericsolar, "Wpar_prodD_coefs" ); //, [1,0,0,0]); set_unit_value_ssc_double(type260_genericsolar, "hrs_tes" ); //, hrs_tes); set_unit_value_ssc_double(type260_genericsolar, "f_charge" ); //, 0.98); set_unit_value_ssc_double(type260_genericsolar, "f_disch" ); //, 0.98); set_unit_value_ssc_double(type260_genericsolar, "f_etes_0" ); //, 0.1); set_unit_value_ssc_double(type260_genericsolar, "f_teshl_ref" ); //, 0.35); set_unit_value_ssc_array(type260_genericsolar, "teshlX_coefs" ); //, [1,0,0,0]); set_unit_value_ssc_array(type260_genericsolar, "teshlT_coefs" ); //, [1,0,0,0]); set_unit_value_ssc_double(type260_genericsolar, "ntod" ); //, 9); set_unit_value_ssc_array(type260_genericsolar, "disws" ); //, [0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]); set_unit_value_ssc_array(type260_genericsolar, "diswos" ); //, [0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]); set_unit_value_ssc_array(type260_genericsolar, "qdisp" ); //, [1,1,1,1,1,1,1,1,1]); set_unit_value_ssc_array(type260_genericsolar, "fdisp" ); //, [0,0,0,0,0,0,0,0,0]); set_unit_value_ssc_matrix(type260_genericsolar, "exergy_table" ); set_unit_value_ssc_double(type260_genericsolar, "storage_config"); //Direct storage=0,Indirect storage=1 //Set the initial values set_unit_value_ssc_double(type260_genericsolar, "ibn" ); //, 0.); //Beam-normal (DNI) irradiation set_unit_value_ssc_double(type260_genericsolar, "ibh" ); //, 0.); // Beam-horizontal irradiation set_unit_value_ssc_double(type260_genericsolar, "itoth" ); //, 0.); // Total horizontal irradiation set_unit_value_ssc_double(type260_genericsolar, "tdb" ); //, 15.); // Ambient dry-bulb temperature set_unit_value_ssc_double(type260_genericsolar, "twb" ); //, 10.); // Ambient wet-bulb temperature set_unit_value_ssc_double(type260_genericsolar, "vwind" ); //, 1.); // Wind velocity // Connect the units bool bConnected = connect(weather, "beam", type260_genericsolar, "ibn"); bConnected &= connect(weather, "global", type260_genericsolar, "itoth"); bConnected &= connect(weather, "poa_beam", type260_genericsolar, "ibh"); bConnected &= connect(weather, "tdry", type260_genericsolar, "tdb"); bConnected &= connect(weather, "twet", type260_genericsolar, "twb"); bConnected &= connect(weather, "wspd", type260_genericsolar, "vwind"); //location bConnected &= connect(weather, "lat", type260_genericsolar, "latitude"); bConnected &= connect(weather, "lon", type260_genericsolar, "longitude"); bConnected &= connect(weather, "tz", type260_genericsolar, "timezone"); bConnected &= connect(tou, "tou_value", type260_genericsolar, "TOUPeriod"); // Example for changing an input variable name in the SSC interface // set_unit_value( u3, "m_dot_htf", as_double("m_dot_htf_init") ); // check if all connections worked if ( !bConnected ) throw exec_error( "tcsgeneric_solar", util::format("there was a problem connecting outputs of one unit to inputs of another for the simulation.") ); size_t hours = 8760; //Load the solar field adjustment factors sf_adjustment_factors sf_haf(this); if (!sf_haf.setup()) throw exec_error("tcsgeneric_solar", "failed to setup sf adjustment factors: " + sf_haf.error()); //allocate array to pass to tcs ssc_number_t *sf_adjust = allocate("sf_adjust", hours); for( size_t i=0; i<hours; i++) sf_adjust[i] = sf_haf(i); set_unit_value_ssc_array(type260_genericsolar, "sf_adjust"); // Run simulation if (0 > simulate(3600.0, hours*3600.0, 3600.0) ) throw exec_error( "tcsgeneric_solar", util::format("there was a problem simulating in tcsgeneric_solar.") ); // get the outputs if (!set_all_output_arrays() ) throw exec_error( "tcsgeneric_solar", util::format("there was a problem returning the results from the simulation.") ); // annual accumulations size_t count = 0; ssc_number_t *enet = as_array("enet", &count); if (!enet || count != 8760) throw exec_error("tcsgeneric_solar", "Failed to retrieve hourly net energy"); adjustment_factors haf(this, "adjust"); if (!haf.setup()) throw exec_error("tcsgeneric_solar", "failed to setup adjustment factors: " + haf.error()); ssc_number_t *hourly = allocate("gen", count); for (size_t i = 0; i < count; i++) { hourly[i] = enet[i] * 1000 * haf(i); // convert from MWh to kWh } accumulate_annual("gen", "annual_energy"); accumulate_annual("w_gr", "annual_w_gr",1000); // convert from MWh to kWh accumulate_annual("q_sf", "annual_q_sf"); accumulate_annual("q_to_pb", "annual_q_to_pb"); accumulate_annual("q_to_tes", "annual_q_to_tes"); accumulate_annual("q_from_tes", "annual_q_from_tes"); accumulate_annual("q_hl_sf", "annual_q_hl_sf"); accumulate_annual("q_hl_tes", "annual_q_hl_tes"); accumulate_annual("q_dump_tot", "annual_q_dump_tot"); accumulate_annual("q_startup", "annual_q_startup"); double fuel_MWht = accumulate_annual("q_fossil", "annual_q_fossil"); // monthly accumulations accumulate_monthly("gen", "monthly_energy"); accumulate_monthly("w_gr", "monthly_w_gr",1000); // convert from MWh to kWh accumulate_monthly("q_sf", "monthly_q_sf"); accumulate_monthly("q_to_pb", "monthly_q_to_pb"); accumulate_monthly("q_to_tes", "monthly_q_to_tes"); accumulate_monthly("q_from_tes", "monthly_q_from_tes"); accumulate_monthly("q_hl_sf", "monthly_q_hl_sf"); accumulate_monthly("q_hl_tes", "monthly_q_hl_tes"); accumulate_monthly("q_dump_tot", "monthly_q_dump_tot"); accumulate_monthly("q_startup", "monthly_q_startup"); accumulate_monthly("q_fossil", "monthly_q_fossil"); ssc_number_t ae = as_number("annual_energy"); ssc_number_t pg = as_number("annual_w_gr"); ssc_number_t convfactor = (pg != 0) ? 100 * ae / pg : 0; assign("conversion_factor", convfactor); // metric outputs moved to technology double kWhperkW = 0.0; double nameplate = as_double("system_capacity"); double annual_energy = 0.0; for (int i = 0; i < 8760; i++) annual_energy += hourly[i]; if (nameplate > 0) kWhperkW = annual_energy / nameplate; assign("capacity_factor", var_data((ssc_number_t)(kWhperkW / 87.6))); assign("kwh_per_kw", var_data((ssc_number_t)kWhperkW)); assign("system_heat_rate", (ssc_number_t)3.413); // samsim tcsgeneric_solar assign("annual_fuel_usage", var_data((ssc_number_t)(fuel_MWht * 1000.0))); }
int main(int argc, char *argv[]) { int rc; int num_tasks; int task_id; double *old, *current, *next, *ret; int t_max, i_max; double time; rc = MPI_Init(&argc, &argv); // Initialize MPI runtime if (rc != MPI_SUCCESS) { // Check for success fprintf(stderr, "Unable to set up MPI\n"); MPI_Abort(MPI_COMM_WORLD, rc); // Abort MPI runtime } /* Parse commandline args */ if (argc < 3) { printf("Usage: %s i_max t_max num_threads [initial_data]\n", argv[0]); printf(" - i_max: number of discrete amplitude points, should be >2\n"); printf(" - t_max: number of discrete timesteps, should be >=1\n"); printf(" - num_threads: number of threads to use for simulation, " "should be >=1\n"); printf(" - initial_data: select what data should be used for the first " "two generation.\n"); printf(" Available options are:\n"); printf(" * sin: one period of the sinus function at the start.\n"); printf(" * sinfull: entire data is filled with the sinus.\n"); printf(" * gauss: a single gauss-function at the start.\n"); printf(" * file <2 filenames>: allows you to specify a file with on " "each line a float for both generations.\n"); return EXIT_FAILURE; } i_max = atoi(argv[1]); t_max = atoi(argv[2]); if (i_max < 3) { printf("argument error: i_max should be >2.\n"); return EXIT_FAILURE; } if (t_max < 1) { printf("argument error: t_max should be >=1.\n"); return EXIT_FAILURE; } if (task_id == 0) { timer_start(); } /* Get MPI rankings */ MPI_Comm_size(MPI_COMM_WORLD, &num_tasks); MPI_Comm_rank(MPI_COMM_WORLD, &task_id); /* Scale i_max to the number of threads * with halo cells in mind(left and right) */ i_max = (i_max/num_tasks) + 2; /* Allocate and initialize buffers. */ old = malloc(i_max * sizeof(double)); current = malloc(i_max * sizeof(double)); next = malloc(i_max * sizeof(double)); if (old == NULL || current == NULL || next == NULL) { fprintf(stderr, "Could not allocate enough memory, aborting.\n"); return EXIT_FAILURE; } memset(old, 0, i_max * sizeof(double)); memset(current, 0, i_max * sizeof(double)); memset(next, 0, i_max * sizeof(double)); /* How should we will our first two generations? This is determined by the * optional further commandline arguments. */ if (argc > 3) { if (strcmp(argv[3], "sin") == 0) { fill(old, 1, i_max/4, 0, 2*3.14, num_tasks, task_id, sin); fill(current, 2, i_max/4, 0, 2*3.14, num_tasks, task_id, sin); } else if (strcmp(argv[3], "sinfull") == 0) { fill(old, 1, i_max-2, 0, 10*3.14, num_tasks, task_id, sin); fill(current, 2, i_max-3, 0, 10*3.14, num_tasks, task_id, sin); } else if (strcmp(argv[3], "gauss") == 0) { fill(old, 1, i_max/4, -3, 3, num_tasks, task_id, gauss); fill(current, 2, i_max/4, -3, 3, num_tasks, task_id, gauss); } else if (strcmp(argv[3], "file") == 0) { if (argc < 6) { printf("No files specified!\n"); return EXIT_FAILURE; } file_read_double_array(argv[4], old, i_max); file_read_double_array(argv[5], current, i_max); } else { printf("Unknown initial mode: %s.\n", argv[3]); return EXIT_FAILURE; } } else { /* Default to sinus. */ fill(old, 1, i_max/4, 0, 2*3.14, num_tasks, task_id, sin); fill(current, 2, i_max/4, 0, 2*3.14, num_tasks, task_id, sin); } /* Call the actual simulation that should be implemented in simulate.c. */ ret = simulate(i_max, t_max, old, current, next, num_tasks, task_id); /* If not controlling process, send message that calculation is done */ MPI_Barrier(MPI_COMM_WORLD); if (!task_id) { time = timer_end(); printf("Took %g seconds\n", time); printf("Normalized: %g seconds\n", time / (1. * i_max * t_max)); /* Write own data */ file_write_double_array("result.txt", ret+1, i_max-1, "w"); /* Receive the data from all the other users */ for (int i = 1; i < num_tasks; i++) { MPI_Recv(ret, i_max, MPI_DOUBLE, i, MSG_WRITE, MPI_COMM_WORLD, NULL); file_write_double_array("result.txt", ret+1, i_max-1, "a+"); } } /* Non-Controller */ if (task_id) { /* Send to controller */ MPI_Send(ret, i_max, MPI_DOUBLE, 0, MSG_WRITE, MPI_COMM_WORLD); } MPI_Finalize(); fprintf(stderr, "Finalized\n"); free(old); free(current); free(next); fprintf(stderr, "Done\n"); return EXIT_SUCCESS; }
int main(int argc, char** argv) { MICROTUBULE_BINDING_DISTANCE = -std::numeric_limits<double>::infinity(); MICROTUBULE_REPULSION_FORCE = 0.0; ONEBOUND_UNBINDING_FORCE = std::numeric_limits<double>::infinity(); T = 100; int iters = iterations / data_generation_skip_iterations; if (argc != 2) { printf("Error, TITLE variable must have underscores, not spaces.\n"); exit(1); } char* f_appended_name = argv[1]; char *config_fname = new char[200]; char *movie_config_fname = new char[200]; char *data_fname = new char[200]; sprintf(data_fname, "data/onebound_data_%s.bin", f_appended_name); sprintf(config_fname, "data/ob_config_%s.txt", f_appended_name); sprintf(movie_config_fname, "data/movie_config_%s.txt", f_appended_name); write_movie_config(movie_config_fname, iterations*dt); write_config_file(config_fname, CONFIG_INCLUDE_SKIPINFO, "Initial state: onebound\nInitial conformation: equilibrium\n"); void* job_msg[4]; job_msg[0] = (double*) &iterations; double current_time = clock(); job_msg[1] = ¤t_time; char run_msg[512]; sprintf(run_msg, "seed = %d", (int) RAND_INIT_SEED); job_msg[2] = run_msg; int data_fd = open(data_fname, O_RDWR | O_CREAT | O_TRUNC, S_IRWXU | S_IRGRP | S_IROTH); if (errno) { perror("Error creating data file"); exit(errno); } ftruncate(data_fd, iters*sizeof(onebound_data_generate_struct)); if (errno) { perror("Error ftruncating data file"); exit(errno); } void* data_mem = mmap(NULL, iters*sizeof(onebound_data_generate_struct), PROT_WRITE, MAP_SHARED, data_fd, 0); if (data_mem == MAP_FAILED) { perror("Error using mmap: "); exit(EXIT_FAILURE); } job_msg[3] = data_mem; onebound_equilibrium_angles eq = onebound_post_powerstroke_internal_angles; double init_position[] = {eq.bba, eq.bma + eq.bba - M_PI, eq.ta + eq.bma + eq.bba - M_PI, eq.ta + eq.bma + eq.bba - eq.uma, 0, 0}; simulate(iterations*dt, RAND_INIT_SEED, NEARBOUND, init_position, write_onebound_data_callback_with_avging, job_msg, NULL); munmap(data_mem, iters*sizeof(onebound_data_generate_struct)); close(data_fd); return EXIT_SUCCESS; }
int main(int argc, char **argv) { bool sys = 0, plot = 0; int mode = 0; double duration = 5, republish = 2; std::string config_file, out_file; Argo a; a.addSwitch('s', "system", sys,"Act as system"); a.addSwitch('p',"plot",plot,"Plot results"); a.addSwitch('V', "Verbose", verbose,"Verbose"); a.addDouble('d', "duration", duration,5.0,"Duration of the simulation"); a.addDouble('T',"period", Ts,0.02,"Period"); a.addDouble('r', "republish",republish, 0.0,"Republish output after this number of periods"); a.addInt('m',"mode",mode, 0,"Connection mode (0:TCP, 1:NOD, 2:UDP)"); a.addString('f', "config", config_file,std::string(getenv("HOME")) + std::string("/.rospacket/controller.yaml"),"Specify config file"); a.addString('o', "out-file",out_file, "rlc.dat","Specify output file"); a.process(argc, argv); ros::init(argc, argv, "controller", ros::init_options::AnonymousName); ros::NodeHandle n; std::cerr << "Reading config file " << config_file << std::endl; try{ YAML::Node config = YAML::LoadFile(config_file); if (YAML::Node parameter = config["T"]){ Ts = parameter.as<double>(); } if (YAML::Node parameter = config["R"]){ R = parameter.as<double>(); } if (YAML::Node parameter = config["L"]){ L = parameter.as<double>(); } if (YAML::Node parameter = config["C"]){ C = parameter.as<double>(); } if (YAML::Node parameter = config["K"]){ K = parameter.as<double>(); } if (YAML::Node parameter = config["size"]){ size = parameter.as<int>(); } if (YAML::Node parameter = config["mode"]){ mode = parameter.as<int>(); } std::cerr << "Done." << std::endl; }catch(YAML::ParserException &e){ std::cerr << "Bad file..."<< std::endl; exit(0); }catch(std::exception){ std::cerr << "No configuration file...done." << std::endl; } ros::TransportHints ti; if (mode == 2){ ti = ros::TransportHints().udp(); std::cerr << "Using UDP" << std::endl; }else if(mode == 1){ ti = ros::TransportHints().tcpNoDelay(); std::cerr << "Using NOD" << std::endl; }else{ ti = ros::TransportHints().tcp(); std::cerr << "Using TCP" << std::endl; } if (sys){ std::cerr << "Acting as system" << std::endl; sub = n.subscribe("u", queue_size, command_callback, ti); pub = n.advertise<ros_profiling_msgs::Controller>("y", queue_size); fd = fopen(out_file.c_str(),"w+"); }else{ std::cerr << "Acting as controller" << std::endl; sub = n.subscribe("y", queue_size, output_callback, ti); pub = n.advertise<ros_profiling_msgs::Controller>("u", queue_size); } ros_profiling_msgs::Controller ctrl; ctrl.data.resize(size); ctrl.u = ctrl.y = 0; ctrl.serial = 1; double begin = now(); bool finished = false; while (ros::ok()){ if (sys){ if (feedback){ if (republish>1.0 && now() - last > republish*Ts){ std::cerr << "Got Stuck -> republishing 'y'" << std::endl; pub.publish(last_published); last = now(); // command_callback(last_ctrl); } }else{ if (now() - begin > 1.0){ pub.publish(ctrl); begin = now(); } } if (elapsed(begin) > duration) { finished = true; break; } } ros::spinOnce(); usleep(1000); } if (sys){ fclose(fd); } if (!plot || !finished){ exit(0); } std::cerr << "Simulating ("<< duration << " seconds)" << std::endl; simulate(duration); std::cerr << "Done." << std::endl; if (sys){ Gnuplot gp; gp << "plot '-' with lines title 'Raw','-' with lines title 'Adjusted','-' with lines title 'Local'\n"; gp.send1d(data1); gp.send1d(data2); gp.send1d(data3); } return 0; }
void TailDrawable::Simulation::update(float dt) { reset(); solve(); simulate(dt); }
static void test_stp_main(int argc, char *argv[]) { struct test_case *tc; FILE *input_file; int i; vlog_set_pattern(VLF_CONSOLE, "%c|%p|%m"); vlog_set_levels(NULL, VLF_SYSLOG, VLL_OFF); if (argc != 2) { ovs_fatal(0, "usage: test-stp INPUT.STP\n"); } file_name = argv[1]; input_file = fopen(file_name, "r"); if (!input_file) { ovs_fatal(errno, "error opening \"%s\"", file_name); } tc = new_test_case(); for (i = 0; i < 26; i++) { char name[2]; name[0] = 'a' + i; name[1] = '\0'; new_lan(tc, name); } for (line_number = 1; fgets(line, sizeof line, input_file); line_number++) { char *newline, *hash; newline = strchr(line, '\n'); if (newline) { *newline = '\0'; } hash = strchr(line, '#'); if (hash) { *hash = '\0'; } pos = line; if (!get_token()) { continue; } if (match("bridge")) { struct bridge *bridge; int bridge_no, port_no; bridge_no = must_get_int(); if (bridge_no < tc->n_bridges) { bridge = tc->bridges[bridge_no]; } else if (bridge_no == tc->n_bridges) { bridge = new_bridge(tc, must_get_int()); } else { err("bridges must be numbered consecutively from 0"); } if (match("^")) { stp_set_bridge_priority(bridge->stp, must_get_int()); } if (match("=")) { for (port_no = 0; port_no < STP_MAX_PORTS; port_no++) { struct stp_port *p = stp_get_port(bridge->stp, port_no); if (!token || match("X")) { stp_port_disable(p); } else if (match("_")) { /* Nothing to do. */ } else { struct lan *lan; int path_cost; if (!strcmp(token, "0")) { lan = NULL; } else if (strlen(token) == 1 && islower((unsigned char)*token)) { lan = tc->lans[*token - 'a']; } else { err("%s is not a valid LAN name " "(0 or a lowercase letter)", token); } get_token(); path_cost = match(":") ? must_get_int() : 10; if (port_no < bridge->n_ports) { stp_port_set_path_cost(p, path_cost); stp_port_enable(p); reconnect_port(bridge, port_no, lan); } else if (port_no == bridge->n_ports) { new_port(bridge, lan, path_cost); } else { err("ports must be numbered consecutively"); } if (match("^")) { stp_port_set_priority(p, must_get_int()); } } } } } else if (match("run")) { simulate(tc, must_get_int()); } else if (match("dump")) { dump(tc); } else if (match("tree")) { tree(tc); } else if (match("check")) { struct bridge *b; struct stp *stp; int bridge_no, port_no; bridge_no = must_get_int(); if (bridge_no >= tc->n_bridges) { err("no bridge numbered %d", bridge_no); } b = tc->bridges[bridge_no]; stp = b->stp; must_match("="); if (match("rootid")) { uint64_t rootid; must_match(":"); rootid = must_get_int(); if (match("^")) { rootid |= (uint64_t) must_get_int() << 48; } else { rootid |= UINT64_C(0x8000) << 48; } if (stp_get_designated_root(stp) != rootid) { warn("%s: root %"PRIx64", not %"PRIx64, stp_get_name(stp), stp_get_designated_root(stp), rootid); } } if (match("root")) { if (stp_get_root_path_cost(stp)) { warn("%s: root path cost of root is %u but should be 0", stp_get_name(stp), stp_get_root_path_cost(stp)); } if (!stp_is_root_bridge(stp)) { warn("%s: root is %"PRIx64", not %"PRIx64, stp_get_name(stp), stp_get_designated_root(stp), stp_get_bridge_id(stp)); } for (port_no = 0; port_no < b->n_ports; port_no++) { struct stp_port *p = stp_get_port(stp, port_no); enum stp_state state = stp_port_get_state(p); if (!(state & (STP_DISABLED | STP_FORWARDING))) { warn("%s: root port %d in state %s", stp_get_name(b->stp), port_no, stp_state_name(state)); } } } else { for (port_no = 0; port_no < STP_MAX_PORTS; port_no++) { struct stp_port *p = stp_get_port(stp, port_no); enum stp_state state; if (token == NULL || match("D")) { state = STP_DISABLED; } else if (match("B")) { state = STP_BLOCKING; } else if (match("Li")) { state = STP_LISTENING; } else if (match("Le")) { state = STP_LEARNING; } else if (match("F")) { state = STP_FORWARDING; } else if (match("_")) { continue; } else { err("unknown port state %s", token); } if (stp_port_get_state(p) != state) { warn("%s port %d: state is %s but should be %s", stp_get_name(stp), port_no, stp_state_name(stp_port_get_state(p)), stp_state_name(state)); } if (state == STP_FORWARDING) { struct stp_port *root_port = stp_get_root_port(stp); if (match(":")) { int root_path_cost = must_get_int(); if (p != root_port) { warn("%s: port %d is not the root port", stp_get_name(stp), port_no); if (!root_port) { warn("%s: (there is no root port)", stp_get_name(stp)); } else { warn("%s: (port %d is the root port)", stp_get_name(stp), stp_port_no(root_port)); } } else if (root_path_cost != stp_get_root_path_cost(stp)) { warn("%s: root path cost is %u, should be %d", stp_get_name(stp), stp_get_root_path_cost(stp), root_path_cost); } } else if (p == root_port) { warn("%s: port %d is the root port but " "not expected to be", stp_get_name(stp), port_no); } } } } if (n_warnings) { exit(EXIT_FAILURE); } } if (get_token()) { err("trailing garbage on line"); } } free(token); for (i = 0; i < tc->n_lans; i++) { struct lan *lan = tc->lans[i]; free(CONST_CAST(char *, lan->name)); free(lan); } for (i = 0; i < tc->n_bridges; i++) { struct bridge *bridge = tc->bridges[i]; stp_unref(bridge->stp); free(bridge); } free(tc); fclose(input_file); }
void do_client_simulation() { char buf[256], buf2[256]; int retval; FILE* f; sprintf(buf, "%s%s", infile_prefix, CONFIG_FILE); cc_config.defaults(); read_config_file(true, buf); log_flags.init(); sprintf(buf, "%s%s", outfile_prefix, "log_flags.xml"); f = fopen(buf, "r"); if (f) { MIOFILE mf; mf.init_file(f); XML_PARSER xp(&mf); xp.get_tag(); // skip open tag log_flags.parse(xp); fclose(f); } gstate.add_platform("client simulator"); sprintf(buf, "%s%s", infile_prefix, STATE_FILE_NAME); if (!boinc_file_exists(buf)) { fprintf(stderr, "No client state file\n"); exit(1); } retval = gstate.parse_state_file_aux(buf); if (retval) { fprintf(stderr, "state file parse error %d\n", retval); exit(1); } // if tasks have pending transfers, mark as completed // for (unsigned int i=0; i<gstate.results.size(); i++) { RESULT* rp = gstate.results[i]; if (rp->state() < RESULT_FILES_DOWNLOADED) { rp->set_state(RESULT_FILES_DOWNLOADED, "init"); } else if (rp->state() == RESULT_FILES_UPLOADING) { rp->set_state(RESULT_FILES_UPLOADED, "init"); } } check_app_config(infile_prefix); show_app_config(); cc_config.show(); log_flags.show(); sprintf(buf, "%s%s", infile_prefix, GLOBAL_PREFS_FILE_NAME); sprintf(buf2, "%s%s", infile_prefix, GLOBAL_PREFS_OVERRIDE_FILE); gstate.read_global_prefs(buf, buf2); fprintf(index_file, "<h3>Output files</h3>\n" "<a href=%s>Summary</a>\n" "<br><a href=%s>Log file</a>\n", SUMMARY_FNAME, LOG_FNAME ); // fill in GPU device nums and OpenCL flags // for (int i=0; i<coprocs.n_rsc; i++) { COPROC& cp = coprocs.coprocs[i]; for (int j=0; j<cp.count; j++) { cp.device_nums[j] = j; if (cp.have_opencl) { cp.instance_has_opencl[j] = true; } } } set_no_rsc_config(); process_gpu_exclusions(); get_app_params(); if (!include_empty_projects) { cull_projects(); } fprintf(summary_file, "--------------------------\n"); int j=0; for (unsigned int i=0; i<gstate.projects.size(); i++) { gstate.projects[i]->index = j++; } clear_backoff(); gstate.log_show_projects(); gstate.set_ncpus(); work_fetch.init(); //set_initial_rec(); rec_adjust_period = delta; gstate.request_work_fetch("init"); simulate(); sim_results.compute_figures_of_merit(); sprintf(buf, "%s%s", outfile_prefix, RESULTS_DAT_FNAME); f = fopen(buf, "w"); sim_results.print(f); fclose(f); sprintf(buf, "%s%s", outfile_prefix, RESULTS_TXT_FNAME); f = fopen(buf, "w"); sim_results.print(f, true); fclose(f); fprintf(summary_file, "Simulation done.\n" "-------------------------\n" "Figures of merit:\n" ); sim_results.print(summary_file, true); double cpu_time; boinc_calling_thread_cpu_time(cpu_time); fprintf(summary_file, "-------------------------\n" "Simulator CPU time: %f secs\n" "-------------------------\n" "Peak FLOPS: CPU %.2fG GPU %.2fG\n", cpu_time, cpu_peak_flops()/1e9, gpu_peak_flops()/1e9 ); print_project_results(summary_file); fclose(rec_file); make_graph("REC", "rec", 0); }
Simulation::Simulation(){ init_buckets(); simulate(); }
int UltimateTicTacToeMontecarloAI::realThink(const UltimateTicTacToeMontecarloAI::Board &board, const int previousMove, const int player) const { //printBoard(board); if(maxIterations == 0) { Moves options = movementOptions(board, previousMove); return options.at(qrand() % options.size()); } //qint64 now = QDateTime::currentMSecsSinceEpoch(); //qDebug() << "c: " << c << ", maxIterations: " << maxIterations << ", maxChildren: " <<maxChildren; Nodes nodes; nodes.reserve(maxIterations * maxChildren); nodes.append(Node { 0, 1, board, previousMove, -1, Node::Children() }); int i; for(i = 0; i < maxIterations; ++i) { int leafIndex = select(nodes); Node const& leaf = nodes.at(leafIndex); GameState leafState = gameState(leaf.board, player); if(leafState == GameState::WIN) { /* qDebug() << "---"; printBoard(leaf.board); */ break; } else if(leafState == GameState::LOSE) { backpropagate(leafIndex, nodes, -10); } else if(leafState == GameState::TIE) { backpropagate(leafIndex, nodes, -5); } else if(leafState == GameState::UNRESOLVED) { int nodeIndex = expand(leafIndex, nodes, player); Node const& node = nodes.at(nodeIndex); int score = simulate(node.board, node.previousMove, player); backpropagate(nodeIndex, nodes, score); } } //qDebug() << "Found solution in " << i + 1 << " iterations"; Node const& root = nodes.at(0); int bestChildIndex = pickBestChild(root, nodes, false); Node const& bestChild = nodes.at(bestChildIndex); //qDebug() << "AI took " << (QDateTime::currentMSecsSinceEpoch() - now) << " ms"; /*for(int childIndex : root.children) { Node const& child = nodes.at(childIndex); qDebug() << child.previousMove << ":" << child.v << child.n; }*/ //qDebug() << bestChild.previousMove / 9 << bestChild.previousMove %9; return bestChild.previousMove; }
int main(int argc, char **argv) { enum GameMode gameMode; struct Windows windows; struct MapList mapList; struct Map *map; struct Dialog dialog[MAX_LEVELS]; struct UnitList inmates, guards; struct UnitNode *unitNode; struct Path path; bool progress[MAX_LEVELS]; int level=0; /* Parse map files */ parseMap(argv[1], &mapList, dialog); /* Create nCurses WINDOWs */ uiInit(&windows); /* Present user with main menu */ gameMode = menuMain(&windows); do{ if(gameMode==EXIT){ break; } else if (gameMode!=NEW){ level = levelSelect(&windows, &mapList, progress); } /* Select current map */ map = &(mapList).level[level]; /* Display intro text */ drawText(&windows, dialog[level], gameMode); /* Initialize game elements */ getGuards(&guards, *map); getPath(&path, *map); inmates.count = 0; inmates.head = NULL; inmates.tail = NULL; /* Draw level */ drawLevel(&windows, map, &guards); /* Prompt user for unit selection */ drawInmateSelection(&windows, map, &inmates, &guards); unitNode = getHead(&inmates); for (int i = 0; i < inmates.count; i++) { ((struct Inmate *) unitNode->unit)->position = path.first->location; unitNode = unitNode->next; } /* Simulate unit interactions */ progress[level] = simulate(&windows, &guards, &inmates, &path); if(progress[level]) gameMode=WIN; else gameMode=LOSE; /* Display outro text */ drawText(&windows, dialog[level], gameMode); } while (level!=EXIT); uiFree(&windows); quit("Thanks for playing.\n"); return 0; }
int main(int argc, char * argv []){ srand((unsigned int)time(NULL)); char c; for(int i = 0 ; i < NBPLAYER ; i ++) { scanf("%s %d %d ", input[i].name, &(input[i].nbCrash), &(input[i].Elo)); for(int j = 0 ; j < NBPLAYER ; j ++){ for(int k = 0 ; k < NBGAMES ; k ++){ scanf("%c", &c); input[i].results[(j * NBGAMES) + k] = (int) c; } scanf(" "); } input[i].id = i; if(strlen(input[i].name) > maxNameLength) maxNameLength = strlen(input[i].name); } for(int i = 0 ; i < NBPLAYER ; i ++) participants[i] = input[i]; printf("\n *********************\n"); printf(" * Current standings *\n"); printf(" *********************\n\n"); getScores(1); printf("\nStarting a simulation with %d iterations\n", NBITER); printf("Simulation currently at 0%%"); fflush(stdout); for(int i = 0 ; i < NBITER ; i ++){ simulate(); if((100 * (i + 1) % NBITER == 0)){ int percentage = (100 * (i + 1)) / NBITER; printf("\r"); for(int k = 0 ; k < 80 ; k ++) printf(" "); printf("\rSimulation currently at %d%%", percentage); fflush(stdout); } } printf("\n\n **********************\n"); printf(" * Simulation results *\n"); printf(" **********************\n\n"); for(int i = 0 ; i < NBPLAYER ; i ++){ printf("%s ", input[i].name); for(int j = 0 ; j < (maxNameLength - strlen(input[i].name)) ; j++) printf(" "); switch (input[i].nbQualif){ case NBITER: printf("is qualified\n"); break; case 0: printf("is eliminated\n"); break; default: if((100 * input[i].nbQualif) % NBITER < NBITER / 2) printf("has %d%% chances to qualify\n", (100 * input[i].nbQualif / NBITER)); else printf("has %d%% chances to qualify\n", (100 * input[i].nbQualif / NBITER) + 1); break; } } return 0; }
int main(int argc, char *argv[]) { const char* fmuFileName; char* fmuPath; char* tmpPath; char* xmlPath; char* dllPath; // define default argument values double tEnd = 1.0; double h=0.1; int loggingOn = 0; char csv_separator = ';'; // parse command line arguments if (argc>1) { fmuFileName = argv[1]; } else { printf("error: no fmu file\n"); printHelp(argv[0]); exit(EXIT_FAILURE); } if (argc>2) { if (sscanf(argv[2],"%lf", &tEnd) != 1) { printf("error: The given end time (%s) is not a number\n", argv[2]); exit(EXIT_FAILURE); } } if (argc>3) { if (sscanf(argv[3],"%lf", &h) != 1) { printf("error: The given stepsize (%s) is not a number\n", argv[3]); exit(EXIT_FAILURE); } } if (argc>4) { if (sscanf(argv[4],"%d", &loggingOn) != 1 || loggingOn<0 || loggingOn>1) { printf("error: The given logging flag (%s) is not boolean\n", argv[4]); exit(EXIT_FAILURE); } } if (argc>5) { if (strlen(argv[5]) != 1) { printf("error: The given CSV separator char (%s) is not valid\n", argv[5]); exit(EXIT_FAILURE); } csv_separator = argv[5][0]; } if (argc>6) { printf("warning: Ignoring %d additional arguments: %s ...\n", argc-6, argv[6]); printHelp(argv[0]); } // get absolute path to FMU, NULL if not found fmuPath = getFmuPath(fmuFileName); if (!fmuPath) exit(EXIT_FAILURE); // unzip the FMU to the tmpPath directory tmpPath = getTmpPath(); if (!unzip(fmuPath, tmpPath)) exit(EXIT_FAILURE); // parse tmpPath\modelDescription.xml xmlPath = calloc(sizeof(char), strlen(tmpPath) + strlen(XML_FILE) + 1); sprintf(xmlPath, "%s%s", tmpPath, XML_FILE); fmu.modelDescription = parse(xmlPath); free(xmlPath); if (!fmu.modelDescription) exit(EXIT_FAILURE); // load the FMU dll dllPath = calloc(sizeof(char), strlen(tmpPath) + strlen(DLL_DIR) + strlen( getModelIdentifier(fmu.modelDescription)) + strlen(".dll") + 1); sprintf(dllPath,"%s%s%s.dll", tmpPath, DLL_DIR, getModelIdentifier(fmu.modelDescription)); if (!loadDll(dllPath, &fmu)) exit(EXIT_FAILURE); free(dllPath); free(fmuPath); free(tmpPath); // run the simulation printf("FMU Simulator: run '%s' from t=0..%g with step size h=%g, loggingOn=%d, csv separator='%c'\n", fmuFileName, tEnd, h, loggingOn, csv_separator); simulate(&fmu, tEnd, h, loggingOn, csv_separator); printf("CSV file '%s' written", RESULT_FILE); // release FMU FreeLibrary(fmu.dllHandle); freeElement(fmu.modelDescription); return EXIT_SUCCESS; }
void TransIcelandicExpress::eventLoop() { while (1) { SDL_Event event; /* Grab all the events off the queue. */ while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_MOUSEMOTION: mouseMotion( event.motion.xrel, event.motion.yrel ); break; case SDL_KEYDOWN: switch( event.key.keysym.sym ) { case SDLK_ESCAPE: do_quit(); break; case SDLK_SPACE: printf("space\n"); break; case SDLK_1: sfx_chan[0] = Mix_PlayChannel(-1, sfx[0], 0); break; case SDLK_2: sfx_chan[1] = Mix_PlayChannel(-1, sfx[1], 0); break; case SDLK_3: sfx_chan[2] = Mix_PlayChannel(-1, sfx[2], 0); break; case SDLK_HOME: ilutGLScreenie(); break; case SDLK_h: showHelp = !showHelp; break; case SDLK_m: if (!musicOn) { printf("Playing\n"); Mix_PlayMusic( music, -1 ); musicOn = 1; } else { printf("Halting\n"); Mix_HaltMusic(); musicOn = 0; } default: break; } break; case SDL_QUIT: /* Handle quit requests (like Ctrl-c). */ do_quit(); break; } } // check non-instant keys cf_moveForward = 0.0; cf_moveSideways = 0.0; Uint8 *keys; keys = SDL_GetKeyState(NULL); if (keys[SDLK_w] && !keys[SDLK_s]) { cf_moveForward = 1.0; } if (!keys[SDLK_w] && keys[SDLK_s]) { cf_moveForward = -1.0; } if (keys[SDLK_a] && !keys[SDLK_d]) { cf_moveSideways = -1.0; } if (!keys[SDLK_a] && keys[SDLK_d]) { cf_moveSideways = 1.0; } computeTimeDelta(); simulate(); redraw(); } }
int main(int argc, char** argv) { setvbuf(stdout, 0, _IONBF, 0); char* run_name = new char[200]; am_making_movie = true; crash_movie_file_name_global = new char[1000]; double runtime = 0; if (am_debugging_onebound) { printf("turning off am_only_writing_on_crash for onebound-debugging mode\n"); am_only_writing_on_crash = false; } set_input_variables(argc, argv, run_name, &am_making_movie, &runtime); if (runtime == 0 and am_making_movie and not am_only_writing_on_crash) { printf("error,value of am_only_writing: %d\n", (int)am_only_writing_on_crash); printf("Error: run settings would cause indefinite movie data printing and fill up the disk!\n"); exit(EXIT_FAILURE); } if (am_only_writing_on_crash) { struct sigaction new_action; new_action.sa_handler = sig_handler_print_movie_buffer; sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; sigaction(SIGUSR1, &new_action, NULL); } char *stepping_data_fname = new char[200]; char *stepping_config_fname = new char[200]; char *movie_data_fname = new char[200]; char *movie_config_fname = new char[200]; sprintf(stepping_data_fname, "data/stepping_data_%s.txt", run_name); sprintf(stepping_config_fname, "data/stepping_config_%s.txt", run_name); sprintf(movie_data_fname, "data/stepping_movie_data_%s.txt", run_name); sprintf(movie_config_fname, "data/stepping_movie_config_%s.txt", run_name); //technically only need this if am_only_writing_on_crash is on, but do it just in case we turn it on later on_crash_old_movie_data_global_ptr = new movie_data_struct[MOVIE_BUFFER_SIZE]; on_crash_new_movie_data_global_ptr = new movie_data_struct[MOVIE_BUFFER_SIZE]; zero_movie_struct(on_crash_old_movie_data_global_ptr); sprintf(crash_movie_file_name_global, "data/stepping_movie_data_%s.txt", run_name); write_movie_config(movie_config_fname, iterations*dt); write_config_file(stepping_config_fname, 0, ""); printf("fake_radius_t: %g\n", fake_radius_t); printf("gt should be : %g\n", fake_radius_t*6*M_PI*water_viscosity_mu); printf("gt: %g\n\n", gt); printf("fake_radius_m: %g\n", fake_radius_m); printf("gm should be : %g\n", fake_radius_m*6*M_PI*water_viscosity_mu); printf("gm: %g\n\n", gm); printf("fake_radius_b: %g\n", fake_radius_b); printf("gb should be : %g\n", fake_radius_b*6*M_PI*water_viscosity_mu); printf("gb: %g\n\n", gb); job_msg_t job_msg; job_msg.max_iteration = 0; job_msg.start_time = clock(); job_msg.run_msg = run_name; job_msg.stepping_data_file = fopen(stepping_data_fname, "w"); job_msg.movie_data_file = 0; if (am_making_movie or am_debugging_onebound) { job_msg.movie_data_file = fopen(movie_data_fname, "w"); if (!job_msg.movie_data_file) { printf("Error opening %s!\n", movie_data_fname); exit(1); } setvbuf(job_msg.movie_data_file, NULL, _IOLBF, 0); // turn on line-buffering fprintf(job_msg.movie_data_file, "#State\ttime\tPE_b1\tPE_m1\tPE_t\tPE_m2\tPE_b2\t" "x1\ty1\tx2\ty2\tx3\ty3\tx4\ty4\tx5\ty5\t" "fx1\tfy1\tfx2\tfy2\tfx3\tfy3\tfx4\tfy4\tfx5\tfy5\n"); } fprintf(job_msg.stepping_data_file, "# command line:"); for (int i=0; i<argc; i++) { fprintf(job_msg.stepping_data_file, " %s", argv[i]); } printf("\n\n\n*********%s*********\n", run_name); fprintf(job_msg.stepping_data_file, "\n\n\n\n#********%s********\n", run_name); if (angle_logging_mode) fprintf(job_msg.stepping_data_file, "#state, time, tx displacement, ty displacement, recently bound motor angle, recently bound binding angle\n"); else fprintf(job_msg.stepping_data_file, "#time_unbind, time_bind, nbx_bind, fbx_bind, nmx_unbind, fmx_unbind, nmx_bind, fmx_bind\n"); if (errno) { perror("Error opening stepping data or movie file.\n"); exit(errno); } onebound_equilibrium_angles eq = onebound_post_powerstroke_internal_angles; double init_position[] = {eq.bba, eq.bma - M_PI + eq.bba, eq.ta + eq.bma - M_PI + eq.bba + 0.00001, eq.ta + eq.bma + eq.bba - eq.uma, 0.0, 0.0}; printf("Initial conditions: %g %g %g %g\n", init_position[0], init_position[1], init_position[2], init_position[3]); simulate(runtime, RAND_INIT_SEED, NEARBOUND, init_position, stepping_data_callback, &job_msg, NULL); fclose(job_msg.stepping_data_file); if (job_msg.movie_data_file) fclose(job_msg.movie_data_file); delete[] on_crash_old_movie_data_global_ptr; delete[] on_crash_new_movie_data_global_ptr; return EXIT_SUCCESS; }
// // Virtual platform construction and simulation // int main(int argc, const char **argv) { // Check arguments if(!cmdParser(argc, argv)) { icmMessage("E", PLATFORM, "Command Line parser error"); return 1; } // initialize OVPsim unsigned int icmAttrs = ICM_STOP_ON_CTRLC | ICM_GDB_CONSOLE; icmInitPlatform(ICM_VERSION, icmAttrs, 0, 0, PLATFORM); const char *modelFile = "model." IMPERAS_SHRSUF; const char *semihostFile = icmGetVlnvString(NULL, "ovpworld.org", "modelSupport", "imperasExit", "1.0", "model"); // create a processor instance icmProcessorP processor = icmNewProcessor( "cpu1", // CPU name "or1k", // CPU type 0, // CPU cpuId 0, // CPU model flags 32, // address bits modelFile, // model file "modelAttrs", // morpher attributes MODEL_FLAGS, // attributes 0, // user-defined attributes semihostFile, // semi-hosting file "modelAttrs" // semi-hosting attributes ); // create the processor bus icmBusP bus = icmNewBus("bus", 32); // connect the processors onto the busses icmConnectProcessorBusses(processor, bus, bus); // create memory icmMemoryP local = icmNewMemory("local", ICM_PRIV_RWX, 0xffffffff); // connect the memory onto the busses icmConnectMemoryToBus(bus, "mp1", local, 0x00000000); icmSimulationStarting(); // query processor registers, execeptions and modes queryRegisters(processor); queryExceptions(processor); queryModes(processor); // run processor until done (no instruction limit) while(simulate(processor, -1)) { // keep going while processor is still running } // report the total number of instructions executed icmPrintf( "processor has executed " FMT_64u " instructions\n", icmGetProcessorICount(processor) ); icmTerminate(); return 0; }
int Gameboard::play(int position) { Gameboard finalState; int taking = simulate(position, finalState); operator =(finalState); return taking; }
US_EquilTime::US_EquilTime() : US_Widgets( true ) { astfem_rsa = new US_Astfem_RSA( model, simparams ); connect( astfem_rsa, SIGNAL( new_scan ( QVector< double >*, double* ) ), SLOT( check_equil( QVector< double >*, double* ) ) ); connect( astfem_rsa, SIGNAL( new_time( double ) ), SLOT( set_time( double ) ) ); setWindowTitle( tr( "Equilibrium Time Prediction" ) ); setPalette( US_GuiSettings::frameColor() ); init_simparams(); QBoxLayout* main = new QHBoxLayout( this ); main->setSpacing ( 2 ); main->setContentsMargins ( 2, 2, 2, 2 ); // Left Column QGridLayout* left = new QGridLayout; int row = 0; QLabel* lb_sample = us_banner( tr( "Model Settings" ) ); left->addWidget( lb_sample, row++, 0, 1, 2 ); QGridLayout* buttons1 = new QGridLayout; int b_row = 0; pb_changeModel = us_pushbutton( tr( "Set / Change / Review Model") ); connect ( pb_changeModel, SIGNAL( clicked() ) , SLOT( change_model() ) ); buttons1->addWidget( pb_changeModel, b_row++, 0, 1, 2 ); left->addLayout( buttons1, row, 0, 3, 2 ); row += 3; QPalette p; p.setColor( QPalette::WindowText, Qt::white ); p.setColor( QPalette::Shadow , Qt::white ); QFont font( US_GuiSettings::fontFamily(), US_GuiSettings::fontSize(), QFont::Bold ); // Radius Info QLabel* lb_radius = us_banner( tr( "Radius Settings" ) ); left->addWidget( lb_radius, row++, 0, 1, 2 ); QGroupBox* channelGroupBox = new QGroupBox( tr( "Channel Type" ) ); channelGroupBox->setContentsMargins ( 2, 2, 2, 2 ); channelGroupBox->setPalette( p ); channelGroupBox->setFont ( font ); QRadioButton* rb_inner; QRadioButton* rb_outer; QRadioButton* rb_center; QRadioButton* rb_custom; QGridLayout* rb5 = us_radiobutton( tr( "Inner Channel" ), rb_inner, true ); QGridLayout* rb6 = us_radiobutton( tr( "Outer Channel" ), rb_outer ); QGridLayout* rb7 = us_radiobutton( tr( "Center Channel" ), rb_center ); QGridLayout* rb8 = us_radiobutton( tr( "Custom" ), rb_custom ); // Group the buttons QButtonGroup* channelGroup = new QButtonGroup; channelGroup->addButton( rb_inner , INNER ); channelGroup->addButton( rb_outer , OUTER ); channelGroup->addButton( rb_center, CENTER ); channelGroup->addButton( rb_custom, CUSTOM ); connect( channelGroup, SIGNAL( buttonClicked( int ) ), SLOT ( new_channel ( int ) ) ); current_position = INNER; QGridLayout* channel = new QGridLayout; channel->setContentsMargins ( 2, 2, 2, 2 ); channel->setSpacing( 0 ); channel->addLayout( rb5, 0, 0 ); channel->addLayout( rb6, 0, 1 ); channel->addLayout( rb7, 1, 0 ); channel->addLayout( rb8, 1, 1 ); channelGroupBox->setLayout( channel ); left->addWidget( channelGroupBox, row, 0, 2, 2 ); row += 2; // Top Radius QLabel* lb_top = us_label( tr( "Top Radius:" ) ); left->addWidget( lb_top, row, 0 ); cnt_top = us_counter( 3, 5.8, 7.3, 5.9 ); cnt_top->setSingleStep( 0.01 ); cnt_top->setEnabled ( false ); left->addWidget( cnt_top, row++, 1 ); // Bottom Radius QLabel* lb_bottom = us_label( tr( "Bottom Radius:" ) ); left->addWidget( lb_bottom, row, 0 ); cnt_bottom = us_counter( 3, 5.8, 7.3, 6.2 ); cnt_bottom->setSingleStep ( 0.01 ); cnt_bottom->setEnabled ( false ); left->addWidget( cnt_bottom, row++, 1 ); // Rotorspeed Info QLabel* lb_rotor = us_banner( tr( "Rotorspeed Settings" ) ); left->addWidget( lb_rotor, row++, 0, 1, 2 ); // Speed type buttons QGroupBox* rotor = new QGroupBox( tr( "Speed Type" ) ); rotor->setContentsMargins ( 2, 10, 2, 2 ); rotor->setPalette( p ); rotor->setFont ( font ); QRadioButton* rb_sigma; QRadioButton* rb_rpm; QGridLayout* rb9 = us_radiobutton( "Use Sigma", rb_sigma, true ); QGridLayout* rb10 = us_radiobutton( "Use RPM" , rb_rpm ); speed_type = SIGMA; sigma_start = 1; sigma_stop = 4; rpm_start = 18000; rpm_stop = 36000; speed_count = 5; QButtonGroup* speedGroup = new QButtonGroup; speedGroup->addButton( rb_sigma, SIGMA ); speedGroup->addButton( rb_rpm , RPM ); connect( speedGroup, SIGNAL( buttonClicked( int ) ), SLOT ( update_speeds( int ) ) ); QGridLayout* speedType = new QGridLayout; speedType->setContentsMargins( 2, 2, 2, 2 ); speedType->setSpacing ( 0 ); speedType->addLayout( rb9, 0, 0 ); speedType->addLayout( rb10, 0, 1 ); rotor->setLayout( speedType ); left->addWidget( rotor, row++, 0, 1, 2 ); // Low speed lb_lowspeed = us_label( tr( "Low Speed (sigma):" ) ); left->addWidget( lb_lowspeed, row, 0 ); cnt_lowspeed = us_counter( 3, 0.01, 10.0, sigma_start ); cnt_lowspeed->setSingleStep( 0.01 ); left->addWidget( cnt_lowspeed, row++, 1 ); connect( cnt_lowspeed, SIGNAL( valueChanged( double ) ), SLOT ( new_lowspeed( double ) ) ); // High speed lb_highspeed = us_label( tr( "High Speed (sigma):" ) ); left->addWidget( lb_highspeed, row, 0 ); cnt_highspeed = us_counter( 3, 0.01, 10.0, sigma_stop ); cnt_highspeed->setSingleStep( 0.01 ); left->addWidget( cnt_highspeed, row++, 1 ); connect( cnt_highspeed, SIGNAL( valueChanged ( double ) ), SLOT ( new_highspeed( double ) ) ); // Speed steps QLabel* lb_speedsteps = us_label( tr( "Speed Steps:" ) ); left->addWidget( lb_speedsteps, row, 0 ); cnt_speedsteps = us_counter( 3, 1.0, 100.0, speed_count ); cnt_speedsteps->setSingleStep( 1.0 ); left->addWidget( cnt_speedsteps, row++, 1 ); connect( cnt_speedsteps, SIGNAL( valueChanged ( double ) ), SLOT ( new_speedstep( double ) ) ); // Speed list QLabel* lb_speedlist = us_label( tr( "Current Speed List:" ) ); left->addWidget( lb_speedlist, row, 0 ); te_speedlist = us_textedit(); te_speedlist->setReadOnly( true ); left->addWidget( te_speedlist, row, 1, 3, 1 ); left->setRowStretch ( row + 1, 99 ); row += 3; // Misc Info QLabel* lb_sim2 = us_banner( tr( "Simulation Settings" ) ); left->addWidget( lb_sim2, row++, 0, 1, 2 ); // Tolerance QLabel* lb_tolerance = us_label( tr( "Tolerance:" ) ); left->addWidget( lb_tolerance, row, 0 ); cnt_tolerance = us_counter( 3, 1.0e-5, 0.01, 0.0005 ); cnt_tolerance->setSingleStep( 1.0e-5 ); left->addWidget( cnt_tolerance, row++, 1 ); // Time increment QLabel* lb_time = us_label( tr( "Time Increment (min):" ) ); left->addWidget( lb_time, row, 0 ); cnt_timeIncrement = us_counter( 3, 1.0, 1000.0, 15.0 ); cnt_timeIncrement->setSingleStep( 1.0 ); left->addWidget( cnt_timeIncrement, row++, 1 ); QGridLayout* buttons2 = new QGridLayout; b_row = 0; pb_estimate = us_pushbutton( tr( "Estimate Times" ) ); pb_estimate->setEnabled( false ); connect( pb_estimate, SIGNAL( clicked() ), SLOT( simulate() ) ); buttons2->addWidget( pb_estimate, b_row++, 0, 1, 2 ); QPushButton* pb_help = us_pushbutton( tr( "Help" ) ); connect( pb_help, SIGNAL( clicked() ), SLOT( help() ) ); buttons2->addWidget( pb_help, b_row, 0 ); QPushButton* pb_close = us_pushbutton( tr( "Close" ) ); connect( pb_close, SIGNAL( clicked() ), SLOT( close() ) ); buttons2->addWidget( pb_close, b_row++, 1 ); left->addLayout( buttons2, row, 0, 2, 2 ); main->addLayout( left ); // Right Column // Simulation plot QBoxLayout* right = new QVBoxLayout; QBoxLayout* plot = new US_Plot( equilibrium_plot, tr( "Approach to Equilibrium Simulation" ), tr( "Radius" ), tr( "Concentration" ) ); us_grid( equilibrium_plot ); equilibrium_plot->setMinimumSize( 600, 400 ); equilibrium_plot->setAxisScale( QwtPlot::yLeft , 0.0, 1.5 ); equilibrium_plot->setAxisScale( QwtPlot::xBottom, 5.9, 6.2 ); right->addLayout( plot ); te_info = new US_Editor( 0, true ); QFontMetrics fm( te_info->font() ); te_info->setFixedHeight( fm.height() * 15 ); right->addWidget( te_info ); right->setStretchFactor( plot , 10 ); right->setStretchFactor( te_info, 2 ); main->addLayout( right ); model.components.clear(); update_speeds( speed_type ); }
int main(int argc, char **argv) { snp_rate = def_snp_rate; err_rate = def_err_rate; coverage = def_coverage; snp_file = (char*)malloc(sizeof(char)*200); indel_file = (char*)malloc(sizeof(char)*200); // override parameters if(argc>1) { int param = 1; int snp_ck = 0, err_ck = 0, max_ck = 0, min_ck = 0, cov_ck = 0, ref_ck = 0, snf_ck = 0, ind_ck = 0, cel_ck = 0, out_ck = 0, reg_ck = 0; for(param=1;param<argc;param++) { char *token[2]; token[0] = strtok(argv[param], "="); if(token[0]==NULL) { printf("Ignoring incorrect parameter #%d\n", param); } else if((token[1] = strtok(NULL, "=")) == NULL) { printf("Ignoring incorrect parameter #%d\n", param); } else { if(strcmp(token[0],"-snp_rate")==0) { if(snp_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { snp_ck++; snp_rate = atof((const char *)token[1]); } } else if(strcmp(token[0],"-err_rate")==0) { if(err_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { err_ck++; err_rate = atof((const char *)token[1]); } } else if(strcmp(token[0],"-min_read_len")==0) { if(min_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { min_ck++; min_read_len = atoi((const char *)token[1]); } } else if(strcmp(token[0],"-max_read_len")==0) { if(max_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { max_ck++; max_read_len = atoi((const char *)token[1]); } } else if(strcmp(token[0],"-coverage")==0) { if(cov_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { cov_ck++; coverage = atoi((const char *)token[1]); if(coverage<2) { printf ("Insufficient coverage %dX provided. Ignoring..\n",coverage); coverage = def_coverage; } } } else if(strcmp(token[0],"-ref_file")==0) { if(ref_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { ref_ck++; ref_file = token[1]; } } else if(strcmp(token[0],"-snp_file")==0) { if(snf_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { snf_ck++; snp_file = token[1]; } } else if(strcmp(token[0],"-indel_file")==0) { if(ind_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { ind_ck++; indel_file = token[1]; } } else if(strcmp(token[0],"-ncells")==0) { if(cel_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { cel_ck++; ncells = atoi((const char *)token[1]); } } else if(strcmp(token[0],"-out_base")==0) { if(out_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { out_ck++; file_base = token[1]; } } else if(strcmp(token[0],"-region")==0) { if(reg_ck>0) { printf("Duplicate parameter %s=%s, ignoring..\n", token[0],token[1]); } else { reg_ck++; region = atoi((const char *)token[1]); } } else { printf("Invalid parameter %s=%s. Ignoring..\n", token[0],token[1]); } } } if(snp_rate>err_rate) { printf("SNP rate (default 0.01) should be lower than error rate (default 0.04). Using default values now...\n"); snp_rate = def_snp_rate; err_rate = def_err_rate; } } int chrnum; char file_name[200]; char log_file_name[200]; char *ext = ".fq"; char *log = ".log"; sprintf(file_name, "%s%s", file_base, ext); sprintf(log_file_name, "%s%s", file_base, log); fq_file = fopen(file_name, "w"); //log_file = fopen(log_file_name, "w"); if (fq_file == NULL) printf("Error opening output file [%s]\n", (const char *) file_name); if (log_file == NULL) printf("Error opening output file [%s]\n", (const char *) log_file_name); simulate(region); fclose(fq_file); }
UserSessionsWidget::UserSessionsWidget(QTabFramework& tabFramework, QSettings& settings, Entity::Manager& entityManager, DataService& dataService) : QWidget(&tabFramework), tabFramework(tabFramework), entityManager(entityManager), dataService(dataService), sessionsModel(entityManager), /*ordersModel(entityManager), transactionModel(entityManager), */selectedSessionId(0) { entityManager.registerListener<EConnection>(*this); setWindowTitle(tr("Bot Sessions")); QToolBar* toolBar = new QToolBar(this); toolBar->setStyleSheet("QToolBar { border: 0px }"); toolBar->setIconSize(QSize(16, 16)); toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); addAction = toolBar->addAction(QIcon(":/Icons/user_gray_add.png"), tr("&Add")); addAction->setEnabled(false); connect(addAction, SIGNAL(triggered()), this, SLOT(addBot())); //optimizeAction = toolBar->addAction(QIcon(":/Icons/chart_curve.png"), tr("&Optimize")); //optimizeAction->setEnabled(false); //connect(optimizeAction, SIGNAL(triggered()), this, SLOT(optimize())); simulateAction = toolBar->addAction(QIcon(":/Icons/user_gray_go_gray.png"), tr("&Simulate")); simulateAction->setEnabled(false); connect(simulateAction, SIGNAL(triggered()), this, SLOT(simulate())); activateAction = toolBar->addAction(QIcon(":/Icons/user_gray_go.png"), tr("&Activate")); activateAction->setEnabled(false); connect(activateAction, SIGNAL(triggered()), this, SLOT(activate())); cancelAction = toolBar->addAction(QIcon(":/Icons/cancel2.png"), tr("&Cancel")); cancelAction->setEnabled(false); connect(cancelAction, SIGNAL(triggered()), this, SLOT(cancelBot())); sessionView = new QTreeView(this); sessionView->setUniformRowHeights(true); proxyModel = new QSortFilterProxyModel(this); proxyModel->setDynamicSortFilter(true); proxyModel->setSourceModel(&sessionsModel); sessionView->setModel(proxyModel); sessionView->setSortingEnabled(true); sessionView->setRootIsDecorated(false); sessionView->setAlternatingRowColors(true); connect(sessionView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(sessionSelectionChanged())); connect(&sessionsModel, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(sessionDataChanged(const QModelIndex&, const QModelIndex&))); connect(&sessionsModel, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, SLOT(sessionDataRemoved(const QModelIndex&, int, int))); connect(&sessionsModel, SIGNAL(modelReset()), this, SLOT(sessionDataReset())); connect(&sessionsModel, SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, SLOT(sessionDataAdded(const QModelIndex&, int, int))); QVBoxLayout* layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); layout->addWidget(toolBar); layout->addWidget(sessionView); setLayout(layout); QHeaderView* headerView = sessionView->header(); //headerView->resizeSection(0, 300); settings.beginGroup("BotSessions"); headerView->restoreState(settings.value("HeaderState").toByteArray()); selectedSessionId = settings.value("SelectedSessionId").toUInt(); settings.endGroup(); headerView->setStretchLastSection(false); headerView->setResizeMode(0, QHeaderView::Stretch); }
int main(int argc, char *argv[]) { double *old, *current, *next; int t_max, i_max, num_threads; double time; /* Parse commandline args: i_max t_max num_threads */ if (argc < 4) { printf("Usage: %s i_max t_max num_threads [initial_data]\n", argv[0]); printf(" - i_max: number of discrete amplitude points, should be >2\n"); printf(" - t_max: number of discrete timesteps, should be >=1\n"); printf(" - num_threads: number of threads to use for simulation, " "should be >=1\n"); printf(" - initial_data: select what data should be used for the first " "two generation.\n"); printf(" Available options are:\n"); printf(" * sin: one period of the sinus function at the start.\n"); printf(" * sinfull: entire data is filled with the sinus.\n"); printf(" * gauss: a single gauss-function at the start.\n"); printf(" * file <2 filenames>: allows you to specify a file with on " "each line a float for both generations.\n"); return EXIT_FAILURE; } i_max = atoi(argv[1]); t_max = atoi(argv[2]); num_threads = atoi(argv[3]); if (i_max < 3) { printf("argument error: i_max should be >2.\n"); return EXIT_FAILURE; } if (t_max < 1) { printf("argument error: t_max should be >=1.\n"); return EXIT_FAILURE; } if (num_threads < 1) { printf("argument error: num_threads should be >=1.\n"); return EXIT_FAILURE; } /* Allocate and initialize buffers. */ old = malloc(i_max * sizeof(double)); current = malloc(i_max * sizeof(double)); next = malloc(i_max * sizeof(double)); if (old == NULL || current == NULL || next == NULL) { fprintf(stderr, "Could not allocate enough memory, aborting.\n"); return EXIT_FAILURE; } memset(old, 0, i_max * sizeof(double)); memset(current, 0, i_max * sizeof(double)); memset(next, 0, i_max * sizeof(double)); /* How should we will our first two generations? */ if (argc > 4) { if (strcmp(argv[4], "sin") == 0) { fill(old, 1, i_max/4, 0, 2*3.14, sin); fill(current, 2, i_max/4, 0, 2*3.14, sin); } else if (strcmp(argv[4], "sinfull") == 0) { fill(old, 1, i_max-2, 0, 10*3.14, sin); fill(current, 2, i_max-3, 0, 10*3.14, sin); } else if (strcmp(argv[4], "gauss") == 0) { fill(old, 1, i_max/4, -3, 3, gauss); fill(current, 2, i_max/4, -3, 3, gauss); } else if (strcmp(argv[4], "file") == 0) { if (argc < 7) { printf("No files specified!\n"); return EXIT_FAILURE; } file_read_double_array(argv[5], old, i_max); file_read_double_array(argv[6], current, i_max); } else { printf("Unknown initial mode: %s.\n", argv[4]); return EXIT_FAILURE; } } else { /* Default to sinus. */ fill(old, 1, i_max/4, 0, 2*3.14, sin); fill(current, 2, i_max/4, 0, 2*3.14, sin); } timer_start(); /* Call the actual simulation that should be implemented in simulate.c. */ simulate(i_max, t_max, num_threads, old, current, next); time = timer_end(); printf("Took %g seconds\n", time); printf("Normalized: %g seconds\n", time / (i_max * t_max)); file_write_double_array("result.txt", current, i_max); free(old); free(current); free(next); return EXIT_SUCCESS; }
///////////////////////////File operations/////////////////////// ssize_t simulate_file_write(struct file* filp, const char __user *buf, size_t count, loff_t* f_pos) { return simulate((void*)0x12345) ? -EINVAL : count; }
bool test_interaction(SimulationTest testID){ std::vector<Particle> startState; //starting situation as drawn below std::vector<Particle> endState; //state we are supposed to end up in sim::time simulationtime; //how long the simulation should take int ID = 0; //make creating particles less confusing auto makeParticle = [&ID](std::pair<double, double> pos, std::pair<double, double> vel){ return Particle{ ID++, 0, pos.first, pos.second, 1, vel.first, vel.second, 0 }; }; //check for invalid cases assert(testID != SimulationTest::end); assert(int(testID) >= int(SimulationTest::singleDirectCollision) && int(testID) < int(SimulationTest::end)); switch (testID){ case SimulationTest::singleDirectCollision: /* single simple direct collision 0: *-> <-* 1: <-**-> 2: <-* *-> */ startState.emplace_back(makeParticle({ 1, 1 }, { 1, 0 })); startState.emplace_back(makeParticle({ 3, 1 }, { -1, 0 })); ID = 0; endState.emplace_back(makeParticle({ 1, 1 }, { -1, 0 })); endState.emplace_back(makeParticle({ 3, 1 }, { 1, 0 })); simulationtime = 2; break; case SimulationTest::doubleDirectCollision: /* 2 simple direct collisions at the same time 0: *-> <-* *-> <-* 1: <-**-> <-**-> 2: <-* *-> <-* *-> */ startState.emplace_back(makeParticle({ 1, 1 }, { 1, 0 })); startState.emplace_back(makeParticle({ 3, 1 }, { -1, 0 })); startState.emplace_back(makeParticle({ 1, 2 }, { 1, 0 })); startState.emplace_back(makeParticle({ 3, 2 }, { -1, 0 })); ID = 0; endState.emplace_back(makeParticle({ 1, 1 }, { -1, 0 })); endState.emplace_back(makeParticle({ 3, 1 }, { 1, 0 })); endState.emplace_back(makeParticle({ 1, 2 }, { -1, 0 })); endState.emplace_back(makeParticle({ 3, 2 }, { 1, 0 })); simulationtime = 2; break; case SimulationTest::angledCollision: /* 0: * | v *--> 1: *--> * | v 2: *--> * | v */ startState.emplace_back(makeParticle({ 3, 1 }, { 0, 1 })); startState.emplace_back(makeParticle({ 1, 3 }, { 1, 0 })); ID = 0; //this one is difficult to calculate... We wrote a program for that endState.emplace_back(makeParticle({ 3, 1 }, { 0, 1 })); //TODO endState.emplace_back(makeParticle({ 1, 3 }, { 1, 0 })); //TODO simulationtime = 2; //TODO break; case SimulationTest::multiCollision: /* 0: *-> *-> *-> <-* <-* <-* 3: *-> *-><-**-><-* <-* 5: *-><-**-><-**-><-* 7: <-**-><-**-><-**-> 9: <-* <-**-><-**-> *-> 11: <-* <-* <-**-> *-> *-> 13: <-* <-* <-* *-> *-> *-> */ startState.emplace_back(makeParticle({ 1, 1 }, { 1, 0 })); startState.emplace_back(makeParticle({ 3, 1 }, { 1, 0 })); startState.emplace_back(makeParticle({ 5, 1 }, { 1, 0 })); startState.emplace_back(makeParticle({ 7, 1 }, { -1, 0 })); startState.emplace_back(makeParticle({ 9, 1 }, { -1, 0 })); startState.emplace_back(makeParticle({ 11, 1 }, { -1, 0 })); ID = 0; endState.emplace_back(makeParticle({ 1, 1 }, { -1, 0 })); endState.emplace_back(makeParticle({ 3, 1 }, { -1, 0 })); endState.emplace_back(makeParticle({ 5, 1 }, { -1, 0 })); endState.emplace_back(makeParticle({ 7, 1 }, { 1, 0 })); endState.emplace_back(makeParticle({ 9, 1 }, { 1, 0 })); endState.emplace_back(makeParticle({ 11, 1 }, { 1, 0 })); simulationtime = 6; //not completely sure it takes 6 timeunits break; case SimulationTest::wallbounce: /* 0: *-> | 1: <-*| 2: <-* | */ startState.emplace_back(makeParticle({ 1, 1 }, { -1, 0 })); ID = 0; endState.emplace_back(makeParticle({ 1, 1 }, { 1, 0 })); simulationtime = 1; break; case SimulationTest::speedCollision: /* 0: *--> <-* 1: *--><-* 2: **---> ??? 3: * *---> ??? */ startState.emplace_back(makeParticle({ 1, 1 }, { 2, 0 })); startState.emplace_back(makeParticle({ 3, 1 }, { -1, 0 })); ID = 0; //Also hard to figure out from just looking at it... Physician help endState.emplace_back(makeParticle({ 3, 1 }, { -1, 0 })); endState.emplace_back(makeParticle({ 3, 1 }, { -1, 0 })); simulationtime = 1; break; case SimulationTest::nudge: /* Is this how physics works? 0: *--> *-> 1: *--> *-> 2: *-->*-> 3: *--*-> 4: *-*-> 5: **--> 6: *-*--> 7: *->*--> 8: *-> *--> */ startState.emplace_back(makeParticle({ 1, 1 }, { 2, 0 })); startState.emplace_back(makeParticle({ 3, 1 }, { 1, 0 })); ID = 0; endState.emplace_back(makeParticle({ 4, 1 }, { 1, 0 })); endState.emplace_back(makeParticle({ 6, 1 }, { 2, 0 })); simulationtime = 2; default: assert(false); //forgot a case } //TODO: //make simulate quit when encountering a terminateSimulation Interaction Interaction terminateSimulation{ simulationtime, -1, -1 }; //get interactions std::vector<Interaction> interactions = make_list(startState, 100, .5); //add termination Interaction interactions.push_back(std::move(terminateSimulation)); //simulate simulate(startState, interactions); if (startState == endState){ //TODO: also check if passed time == simulationtime return true; } else{ std::cout << "\nTest " << int(testID) << " failed\n"; std::cout << "State is:\n"; for (const auto &p : startState){ std::cout << p << ' '; } std::cout << "\nState should be:\n"; for (const auto &p : endState){ std::cout << p << ' '; } return false; } }
/** * \copydoc Simulation::simulate() */ void StatisticsSimulation::simulate() { return simulate(false); }
/** * \copydoc Simulation::simulate(bool) */ void MetropolisHastingsSimulation::simulate(bool withSeeds) { assert(withSeeds == false); // No finite difference available simulate(); }
void DGSM::doSA() { int k = m_InputList->size(); /* number of input factors */ /* 1. Allocates input/output data */ std::unique_ptr<DMatrix> X(nullptr); std::unique_ptr<ResultMatrix> y(nullptr); if (m_SaveInput) { m_InputData.reset(new DMatrix(N_*(k+1), k)); X = std::move(m_InputData->subMatrix(0, N_)); } else { X.reset(new DMatrix(N_, k)); } if (m_SaveOutput) { m_OutputData.reset(new ResultMatrix(N_*(k+1), m_NumOutputs)); y = std::move(m_OutputData->subMatrix(0, N_)); } else { y.reset(new ResultMatrix(N_, m_NumOutputs)); } std::unique_ptr<DMatrix> x(new DMatrix(N_, k)); /* 2. Generates the first N samples */ m_RNG.LHS(*x); /* Copies then converts to target distributions */ x->copy(*X); m_RNG.convert(*X, m_InputList); /* 3. Runs simulation for the first N samples */ simulate(*X, *y); /* 4. Allocates xdiff, ydiff if needs * xdiff is the 1-column different from X and ydiff is its corresponding * output * */ std::unique_ptr<DMatrix> xdiff(nullptr); if (!m_SaveInput) { xdiff.reset(new DMatrix(N_, k)); } std::unique_ptr<ResultMatrix> ydiff(nullptr); if (!m_SaveOutput) { ydiff.reset(new ResultMatrix(N_, m_NumOutputs)); } std::unique_ptr<DMatrix> stats(new DMatrix(3, m_NumOutputs)); const int* labels = y->getLabels(); /* 5. Estimate sensitivity indices for each input factor */ for (int iK=0; iK<k; ++iK) { /* Makes xdiff, ydiff refer to their correct location if needs */ if (m_SaveInput) { xdiff = std::move(m_InputData->subMatrix((iK+1)*N_, N_)); } if (m_SaveOutput) { ydiff = std::move(m_OutputData->subMatrix((iK+1)*N_, N_)); } /* Copy the first N samples to xdiff and diffs the column iK*/ x->copy(*xdiff); for (int iRow=0; iRow<N_; ++iRow) { /* Changes values in column iK */ double* row = xdiff->getRow(iRow); if (row[iK] + delta_ >= 1) row[iK] -= delta_; else row[iK] += delta_; } /* Converts xdiff to target distributions */ m_RNG.convert(*xdiff, m_InputList); /* Runs simulation */ simulate(*xdiff, *ydiff); /* Estimates sensitivity indices */ const int* labelsdiff = ydiff->getLabels(); double* sens = m_Sens->getRow(iK); for (int iOut=0; iOut< m_NumOutputs; ++iOut) { double mean=0, absmean=0, std=0; double derivative = 0; int cnt = 0; for (int iRow = 0; iRow < N_; ++iRow) { if (labels[iRow] == SIM_SUCCESS && labelsdiff[iRow] == SIM_SUCCESS) { derivative = (ydiff->getRow(iRow)[iOut] - y->getRow(iRow)[iOut]) / (X->getRow(iRow)[iK] - xdiff->getRow(iRow)[iK]); cnt++; mean += derivative; absmean += derivative > 0 ? derivative : -derivative; std += derivative*derivative; } } if (cnt < N_ * (1-m_FailureRate)) throw SAException(ERROR_EXCEEDING_FAILURE_RATE); mean /= cnt; absmean /= cnt; std = sqrt(std/cnt - mean*mean); sens[iOut*iK] = mean; sens[iOut*iK+1] = absmean; sens[iOut*iK+2] = std; } } }
stateStruct Mechanism::initAndSim(stateStruct& startState,std::vector<double>& action){ initialize(startState); return simulate(action); }
int main(int argc, char *argv[]) { progname = argv[0]; int show_usage = 0; int outrate = 1, timesteps = 17; char *infile = NULL, *prefix = NULL; int optc; while ((optc = getopt_long(argc, argv, GETOPTS, long_opts, NULL)) != -1) { switch (optc) { case 'i': if (infile != NULL) { free(infile); } infile = strdup(optarg); break; case 'p': if (prefix != NULL) { free(prefix); } prefix = strdup(optarg); break; case 'r': outrate = atoi(optarg); break; case 't': timesteps = atoi(optarg); if (timesteps < 1) { fprintf(stderr, "Invalid value for timesteps: %s, must be a number greater than 1.\n", optarg); show_usage = 1; } break; default: show_usage = 1; } } if (show_usage == 1 || optind < argc || infile == NULL || prefix == NULL) { print_usage(); return EXIT_FAILURE; } // READ FILE hsize_t dims[2]; hid_t file_id; if ((file_id = H5Fopen(infile, H5F_ACC_RDONLY, H5P_DEFAULT)) < 0) { print_usage(); return EXIT_FAILURE; } if (H5LTget_dataset_info(file_id, CCILK_DATASET, dims, NULL, NULL) < 0) { print_usage(); return EXIT_FAILURE; } size_t rows = dims[0]; size_t cols = dims[1]; double *data = malloc(rows * cols * sizeof(double)); double *next = malloc(rows * cols * sizeof(double)); double width, depth, nu, sigma; if (H5LTread_dataset_double(file_id, CCILK_DATASET, data) < 0 || H5LTget_attribute_double(file_id, "/domain/", "width", &width) < 0 || H5LTget_attribute_double(file_id, "/domain/", "depth", &depth) < 0 || H5LTget_attribute_double(file_id, "/properties/", "nu", &nu) < 0 || H5LTget_attribute_double(file_id, "/properties/", "sigma", &sigma) < 0) { fprintf(stderr, "Encountered an issue reading the dataset\n"); return EXIT_FAILURE; }; printf("Width: %f dept %f\n", width, depth); simulate(data, next, rows, cols, width, depth, nu, sigma, outrate, timesteps, prefix); free(data); H5Fclose(file_id); return EXIT_SUCCESS; }
int main(int argc, char **argv) { char input; char *target; // Target input file name. char *alg; // fcfs or multi. int memsize; // Given virtual memsize. if (argc != 7) { print_usage(argv[0]); return -1; } // Getting the options for program execution. while ((input = getopt(argc, argv, "f:a:m:")) != EOF) { switch ( input ) { case 'f': // Ascertaining which file to read the input from. target = optarg; break; case 'a': // Ascertaining which algorithm to use. if(strcmp(optarg, FCFS) == 0) alg = optarg; else if(strcmp(optarg, MULTI) == 0) alg = optarg; else { // Exit if optarg unknown fprintf(stderr, "Invalid scheduling option %s\n", optarg); print_usage(argv[0]); exit(1); } break; case 'm': // Ascertaining total memory size. memsize = atoi(optarg); break; default: // Should not get here. print_usage(argv[0]); return -1; } } /* ** Here we read processes into disk. Throughout the life of the ** simulation, this disk linked list will hold both processes that ** haven't yet been started (future processes whose start times are ** greater than the current simulation time) as well as processes ** that have been swapped back to disk because memory was too full. */ int num_processes = 0; Process *disk_head = read_processes(target, memsize, &num_processes); if (disk_head == NULL) { fprintf(stderr, "%s couldn't be read properly, exiting...\n", target); return -1; } Memory *memory = create_memory(memsize); simulate(disk_head, num_processes, memory, alg); return 0; }
static gmx_bool xhwCallBack(struct t_x11 *x11, XEvent *event, Window wd, void *data) { t_xhighway *xhw; t_windata *win; float sx; int i; static int nyy = 0; static int *yy; xhw = (t_xhighway *)data; win = &(xhw->win); if (nyy == 0) { nyy = 2*xhw->ir.nlane+1; snew(yy, nyy); } for (i = 0; (i < nyy); i++) { yy[i] = ((float) i*win->height)/(nyy-1); } switch (event->type) { case Expose: { if (wd == win->self) { sx = (float)win->width / xhw->ir.metres; XClearWindow(x11->disp, win->self); XSetForeground(x11->disp, x11->gc, WHITE); for (i = 2; (i < nyy-1); i += 2) { XDrawLine(x11->disp, win->self, x11->gc, 0, yy[i], win->width-1, yy[i]); } for (i = 0; (i < xhw->ncars); i++) { t_car *car = &(xhw->cars[i]); int w1 = car->x*sx; int h1 = yy[1+2*(xhw->ir.nlane-1-car->lane)]; draw_car(x11->disp, win->self, x11->gc, car, w1, h1); } if (xhw->bDriving) { simulate(x11, xhw, xhw->ncars, xhw->cars, &xhw->ir); } } break; } case ConfigureNotify: if (wd == xhw->main.self) { xhw->main.width = event->xconfigure.width; xhw->main.height = event->xconfigure.height; Configure(xhw); for (i = 0; (i < NBUT); i++) { XMoveResizeWindow(x11->disp, xhw->but[i].self, xhw->but[i].x, xhw->but[i].y, xhw->but[i].width, xhw->but[i].height); } XMoveResizeWindow(x11->disp, win->self, win->x, win->y, win->width, win->height); } else if (wd == win->self) { win->width = event->xconfigure.width; win->height = event->xconfigure.height; } break; case ButtonPress: return TRUE; default: break; } return FALSE; }
int main() { simulate(); return 0; }