Ejemplo n.º 1
46
void testJacobian(std::string group_name, std::string base_link, std::string tip_link)
{
 SCOPED_TRACE(group_name + ": " + base_link + " to " + tip_link);
 
 srand ( time(NULL) ); // initialize random seed:
 rdf_loader::RDFLoader model_loader("robot_description");
 robot_model::RobotModelPtr kinematic_model;
 kinematic_model.reset(new robot_model::RobotModel(model_loader.getURDF(),model_loader.getSRDF()));

 robot_state::RobotStatePtr kinematic_state;
 kinematic_state.reset(new robot_state::RobotState(kinematic_model));
 kinematic_state->setToDefaultValues();

 const moveit::core::JointModelGroup* joint_state_group = kinematic_state->getRobotModel()->getJointModelGroup(group_name);

 std::string link_name = tip_link;
 std::vector<double> joint_angles(7,0.0);
 geometry_msgs::Point ref_position;
 Eigen::MatrixXd jacobian;
 Eigen::Vector3d point(0.0,0.0,0.0);
 kinematic_state->setJointGroupPositions(joint_state_group, &joint_angles[0]);
 ASSERT_TRUE(kinematic_state->getJacobian(joint_state_group, kinematic_state->getRobotModel()->getLinkModel(link_name),point,jacobian));

 KDL::Tree tree;
 if (!kdl_parser::treeFromUrdfModel(*model_loader.getURDF(), tree))
 {
   ROS_ERROR("Could not initialize tree object");
 }
 KDL::Chain kdl_chain;
 std::string base_frame(base_link);
 std::string tip_frame(tip_link);
 if (!tree.getChain(base_frame, tip_frame, kdl_chain))
 {
   ROS_ERROR("Could not initialize chain object");
 }
 KDL::ChainJntToJacSolver kdl_solver(kdl_chain);
 KDL::Jacobian jacobian_kdl(7);
 KDL::JntArray q_in(7);
 EXPECT_TRUE(kdl_solver.JntToJac(q_in,jacobian_kdl) >= 0);

 unsigned int NUM_TESTS = 10000;
 for(unsigned int i=0; i < NUM_TESTS; i++)
 {
   for(int j=0; j < 7; j++)
   {
     q_in(j) = gen_rand(-M_PI,M_PI);
     joint_angles[j] = q_in(j);
   }
   EXPECT_TRUE(kdl_solver.JntToJac(q_in,jacobian_kdl) >= 0);
   kinematic_state->setJointGroupPositions(joint_state_group, &joint_angles[0]);
   EXPECT_TRUE(kinematic_state->getJacobian(joint_state_group, kinematic_state->getRobotModel()->getLinkModel(link_name), point, jacobian));
   for(unsigned int k=0; k < 6; k++)
   {
     for(unsigned int m=0; m < 7; m++)
     {
       EXPECT_FALSE(NOT_NEAR(jacobian_kdl(k,m),jacobian(k,m),1e-10));
     }
   }
 }
}
Ejemplo n.º 2
0
/*
 * key generator
 */
static void 
gen_key(char *key)
{
	unsigned int temp;

	/* generate a rand key consisting of 95 ascii values, ' ' to '~' */
	temp = gen_rand();
	/* filter out lower order bits */
	temp /= 52;
	key[3] = ' ' + (temp % 95);
	temp /= 95;
	key[2] = ' ' + (temp % 95);       
	temp /= 95;
	key[1] = ' ' + (temp % 95);
	temp /= 95;
	key[0] = ' ' + (temp % 95);

	temp = gen_rand();
	temp /= 52;
	key[7] = ' ' + (temp % 95);
	temp /= 95;
	key[6] = ' ' + (temp % 95);
	temp /= 95;
	key[5] = ' ' + (temp % 95);
	temp /= 95;
	key[4] = ' ' + (temp % 95);

	temp = gen_rand();
	temp /= 52 * 95 * 95;
	key[9] = ' ' + (temp % 95);
	temp /= 95;
	key[8] = ' ' + (temp % 95);
}
Ejemplo n.º 3
0
int main(int argc, char *argv[]) {
	gcry_mpi_t g,p,M,N,pw,t1,t2;
	size_t scanned;
	int iterations, keySize;

	g = gcry_mpi_new(0);
	p = gcry_mpi_new(0);
	M = gcry_mpi_new(0);
	N = gcry_mpi_new(0);
	pw = gcry_mpi_new(0);
	t1 = gcry_mpi_new(0);
	t2 = gcry_mpi_new(0);

	/* MODP_2048 */
	const char* pString = "00FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF";
	const char* gString = "2";

	/* password */
	const char* pwd = "My$Very=Secure;Password";
	const char* salt = "abcdefghijklmno";
	iterations = 1000;
	keySize = 32;	
	
	/* read p and g */
	gcry_mpi_scan(&g, GCRYMPI_FMT_HEX, gString, 0, &scanned);
	gcry_mpi_scan(&p, GCRYMPI_FMT_HEX, pString, 0, &scanned);

	/* hash password */
	char* result = calloc(keySize, sizeof(char));
	gcry_kdf_derive(pwd, strlen(pwd), GCRY_KDF_PBKDF2, GCRY_MD_SHA256, salt, strlen(salt), iterations, keySize, result);
	gcry_mpi_scan(&pw, GCRYMPI_FMT_STD, result, strlen((const char*)result), &scanned);

	/* create M and N */
	gen_rand(t1, p);
	gen_rand(t2, p);
	gcry_mpi_powm(M, g, t1, p);
	gcry_mpi_powm(N, g, t2, p);

	/* run test ... */
	struct spake_session client = spake_init(0, g, p, M, N, pw, keySize); /* client */
	struct spake_session server = spake_init(1, g, p, M, N, pw, keySize); /* server */

	spake_next(&client, server.X);
	spake_next(&server, client.X);

	print_key(client.k, keySize, "k1");
	print_key(server.k, keySize, "k2");

	if (strncmp(client.k, server.k, keySize) == 0)
		printf("Successful SPAKE session :)\n");
	else
		printf("Sorry, error in SPAKE session :(\n");
	
	return 0;
}
Ejemplo n.º 4
0
int main()
{
	//Part 1. Evaluating Hash Functions
	int bloomsize = 100;
	int x;
	bloom_filter_t bloomfilter;
	bloom_init(&bloomfilter, bloomsize);


	printf ("Hash1: %i %i %i %i %i %i\n",hash1(&bloomfilter, 0),hash1(&bloomfilter, 1),
		hash1(&bloomfilter, 2),hash1(&bloomfilter, 3),hash1(&bloomfilter, 13),
		hash1(&bloomfilter, 97));

	printf ("Hash2: %i %i %i %i %i %i\n",hash2(&bloomfilter, 0),hash2(&bloomfilter, 1),
		hash2(&bloomfilter, 2),hash2(&bloomfilter, 3),hash2(&bloomfilter, 13),
		hash2(&bloomfilter, 97));

	bloom_destroy(&bloomfilter);

	//Part 2: 
	printf("\nDoing Smoke Test.\n");
	bloomsize = 1000;
	bloom_init(&bloomfilter, bloomsize);


	for (x= 0; x< 70; x++)
	{
		bloom_add(&bloomfilter, x);
	}

	int totalbits = 0;
	for (x = 0; x< bloomsize; x++)
	{
		totalbits += get_bit(&bloomfilter, x);
	}
	printf("Total bits set: %i\n",totalbits);	
	bloom_destroy(&bloomfilter);

	//Part 3
	printf("\nDoing N_HASHES Test.\n");

	int array1[100];
	int array2[100];
	gen_rand(array1, 100, 1000000);
	gen_rand(array2, 100, 1000000);
	run_test3(array1, array2, 100);

}
Ejemplo n.º 5
0
int main () {

    int i = 0;
    int arr_0 [ LEN ];

    endurance_size = 3;

    printf ( "\nExample of selection sort_bubble algoritm.\n\n" );
    printf ( "Here is array, fulled randomly:\n\n" );
    
    for ( i = 0; i < LEN; i ++ ) {
//        arr_0 [ i ] = rand () % 101;
        arr_0 [ i ] = gen_rand ( RLEN );
        printf ( "arr_0 [ %d ] = %d;\n", i, arr_0 [ i ] );
    }

    printf ( "\n\nAnd here is sorting function working:\n\n");

    sort_bubble ( arr_0 );
    printf ( "\n\nAfter sorting function array seems so:\n\n");

    for ( i = 0; i < LEN; i ++ ) {
        printf ( "arr_0 [ %d ] = %d;\n", i, arr_0 [ i ] );
    }

    printf ( "\nThe end:)\n\n" );
    
    return 0;
}
std::vector<double> generateRandomValues(std::vector<double> min_values,
                                         std::vector<double> max_values) {
  std::vector<double> ret_vec;
  for(unsigned int i = 0; i < min_values.size(); i++) {
    ret_vec.push_back(gen_rand(min_values[i], max_values[i]));
  }
  return ret_vec;
}
Ejemplo n.º 7
0
TEST(JacobianSolver, solver)
{
 srand ( time(NULL) ); // initialize random seed: 
 rdf_loader::RDFLoader model_loader("robot_description");
 robot_model::RobotModelPtr kinematic_model;
 kinematic_model.reset(new robot_model::RobotModel(model_loader.getURDF(),model_loader.getSRDF()));

 robot_state::RobotStatePtr kinematic_state;
 kinematic_state.reset(new robot_state::RobotState(kinematic_model));
 kinematic_state->setToDefaultValues();

 robot_state::JointStateGroup* joint_state_group = kinematic_state->getJointStateGroup("right_arm");
 
 std::string link_name = "r_wrist_roll_link";
 std::vector<double> joint_angles(7,0.0); 
 geometry_msgs::Point ref_position;
 Eigen::MatrixXd jacobian;
 Eigen::Vector3d point(0.0,0.0,0.0);
 joint_state_group->setVariableValues(joint_angles);
 ASSERT_TRUE(joint_state_group->getJacobian(link_name,point,jacobian));

 KDL::Tree tree;
 if (!kdl_parser::treeFromUrdfModel(*model_loader.getURDF(), tree)) 
 {
   ROS_ERROR("Could not initialize tree object");
 }
 KDL::Chain kdl_chain;
 std::string base_frame("torso_lift_link");
 std::string tip_frame("r_wrist_roll_link");
 if (!tree.getChain(base_frame, tip_frame, kdl_chain)) 
 {
   ROS_ERROR("Could not initialize chain object");
 }
 KDL::ChainJntToJacSolver kdl_solver(kdl_chain);
 KDL::Jacobian jacobian_kdl(7);
 KDL::JntArray q_in(7);
 EXPECT_TRUE(kdl_solver.JntToJac(q_in,jacobian_kdl) >= 0);

 unsigned int NUM_TESTS = 1000000;
 for(unsigned int i=0; i < NUM_TESTS; i++)
 {
   for(int j=0; j < 7; j++)
   {
     q_in(j) = gen_rand(-M_PI,M_PI);
     joint_angles[j] = q_in(j);
   }
   EXPECT_TRUE(kdl_solver.JntToJac(q_in,jacobian_kdl) >= 0);
   joint_state_group->setVariableValues(joint_angles);
   EXPECT_TRUE(joint_state_group->getJacobian(link_name,point,jacobian));
   for(unsigned int k=0; k < 6; k++)
   {
     for(unsigned int m=0; m < 7; m++)
     {
       EXPECT_FALSE(NOT_NEAR(jacobian_kdl(k,m),jacobian(k,m),1e-10));
     }
   }
 }
}
Ejemplo n.º 8
0
const char* genGcryptRand(unsigned char* x){
	size_t scanned;
	unsigned char *result;
	gcry_mpi_t a = gcry_mpi_new(0);
	gcry_mpi_t r = gcry_mpi_new(0);
	gcry_mpi_scan(&a, GCRYMPI_FMT_HEX, x, 0, &scanned);
	gen_rand(r, a);
	gcry_mpi_aprint(GCRYMPI_FMT_HEX, &result, NULL, r);
	return result;
}
Ejemplo n.º 9
0
main()
{
    /** Set the seed of random number generator
     *  to the current time. */
    srand( (unsigned)time( NULL ) );
    printf("key size:");
    double arr[SAMPLE_SIZE] = {};
    for (int i = 0; i < SAMPLE_SIZE; i++) {
        arr[i] = key_gev(gen_rand());
    }
    quicksort(arr, 0, SAMPLE_SIZE - 1);
    print_list(arr);
    printf("\n\n\n");
}
Ejemplo n.º 10
0
int main()
{
	srand(time(NULL));

	T = MAXT;
	printf("%d\n", T);

	while (T) {
		int r = rand() % 3;

		if (r == 0) gen_close();
		else if (r == 1) gen_rand();
		else gen();
	}

	return 0;
}
Ejemplo n.º 11
0
int main()
{
    printf("Enter n\n");
    int n, i;
    scanf("%d", &n);
    printf("type 0 to generate points randomly else type otherwise");
    scanf("%d", &i);
    if(i == 0) {
        gen_rand(n);
    }
    else {
        printf("Enter all points (x y)\n"); 
        for(i=0;i<n;++i)
            scanf("%f%f", &arr[i].x, &arr[i].y);
    }
    qsort(arr, n, sizeof(point), cmpX);
    printf("Minimum distance is:\n%f\n", _do(0, n - 1));
    return 0;
}
Ejemplo n.º 12
0
int main(int argc, char **argv){
    int N = 12;
    double* rand_array = calloc(N,sizeof(double *));
    srand(time(NULL));
    for(int i = 1; i<7;i++){
        double X_m = 0.0;
        for(int j =0; j< 10000; j++){
            gen_rand(rand_array,N);
            double sum = 0.0;
            for(int k=0;k<N;k++){
                sum+= (rand_array[k]-0.5);
            }
            X_m += pow(sum,i);
        }
        X_m = X_m/1000.0;
        printf("<X^%d>=%f\n",i,X_m);
    }
    
    return 0;

}
Ejemplo n.º 13
0
// since the generator does not take any inputs from other modules we
// can do all our work in here:
void ocin_gen_bitrev::update() {

  unsigned src_count = srcs.size();
  unsigned dst_idx, src_idx;
/*  
  // First figure out how many packets we will generate
  double selfrand1 = gen_rand(1);
  unsigned packet_count = (unsigned)((selfrand1*param_adj_inj_bw*(double)src_count*2.0) +.5);
  
  // Iterate over each packet and create it
  for (int x = 0; x <packet_count;x++) {  
    src_idx = random()%src_count;
*/
  for (src_idx=0; src_idx < src_count; src_idx++) {

    // Roll the dice. 
    double dice = gen_rand(1);
    if (dice > param_adj_inj_bw)
      continue;
      
#ifdef DEBUG
    {
      stringstream tmp;
      tmp  << "Injecting packet from node :" <<srcs[src_idx].c_str();
      ocin_name_debug(name,tmp.str());
    }
#endif
    
    // generate packet
    ocin_msg * new_msg = gen_packet(srcs[src_idx], src_to_dst[srcs[src_idx]]);
    
    // push each flit into the iu's vector
    int flit_cnt = new_msg->flits.size();
    for (int y= 0; y < flit_cnt; y++) {
      
      local_iu_ptrs[src_idx]->push_flit(new_msg->flits[y]);
    }
    
  }    
}
Ejemplo n.º 14
0
void SimAnn(Simulated_Annealing_Param_t *param, const char *filename) {

    bool pingpong = 0;
    int i =0;
    int j =0;
    double delta =0;
    FILE *file;
    file = fopen(filename,"a+");
    if(file == NULL) {
        fprintf(stderr, "Could not open File!\n");
        exit(EXIT_FAILURE);
    }

    for(j=0; j < param->optim->n; j++) {
        printf("limit[%d]: %lf  --  %lf\n",j,param->optim->min[j] ,param->optim->max[j] );
    }

    if(param->temp == 0) param->temp = generateInitialTemp(10, param);

    enum {SAinit, SAnewDPoint, SAMetropolisCrit, SAReduceTemp, SAStop} state;

    state = SAinit;


    while(state != SAStop)
    {
        switch(state) {
        case SAinit:
            param->dP[pingpong].x = (double *) calloc(param->optim->n, sizeof(double));
            param->dP[!pingpong].x = (double *) calloc(param->optim->n, sizeof(double));
            if(param->dP[pingpong].x == NULL) {
                state = SAStop;
                printf("Error: Could not allocate Memory!");
                break;
            }

            fillRandom( param->optim->n , param->optim->min , param->optim->max , param->dP[pingpong].x );
            param->dP[pingpong].temp = param->optim->f( param->optim , param->dP[pingpong].x );

            printf("Starttemperatur = %lf\n", param->temp);
            state = SAnewDPoint;
            i=1;
            pingpong = 1;
            break;
        case SAnewDPoint:

            for(j=0; j < param->optim->n; j++) {
                param->dP[pingpong].x[j] = limit(param->optim->min[j], param->optim->max[j], 										param->dP[!pingpong].x[j]+(((double)gen_rand())/1000000.00*2.0*param->vicinity)-param->vicinity );

                if(param->dP[pingpong].x[j] > param->optim->max[j]) printf("Heep %lf\n", param->dP[pingpong].x[j]);

            }
            param->dP[pingpong].temp = param->optim->f(param->optim,param->dP[pingpong].x);

            delta = param->dP[pingpong].temp - param->dP[!pingpong].temp;


            if(delta > 0) { /* higher temp then before */
                if(pow(2.71828182845,-delta/param->temp) < ((double)gen_rand())/1000000.00)
                    break;
            }

            for (j=0; j<param->optim->n; j++) fprintf (file, "%lf, ",param->dP[pingpong].x[j]);

            fprintf(file,"%lf \n",param->dP[pingpong].temp);
            //printf("%lf %lf %lf\n", designPoints[index-1].x, designPoints[index-1].y, designPoints[index-1].res);
            pingpong =!pingpong;
            i++;
            if( i > param->iterations ) state = SAReduceTemp;
            break;
        case SAReduceTemp:
            param->temp *= param->tempCoeff;
            if(param->temp < param->stopTemp) {
                printf("Stoptemperatur = %lf\n",param->temp);
                state = SAStop;
                break;
            }
            i=1;
            state = SAnewDPoint;
            break;

        default:
            break;
        }


    }
    fclose(file);
    free(param->dP[pingpong].x);
    free(param->dP[!pingpong].x);
}
Ejemplo n.º 15
0
 static void random_vector( std::vector<double>& x, double maxval = 1.0) {
   range = maxval;
   std::generate_n(x.begin(), x.size(), gen_rand());
 }
Ejemplo n.º 16
0
static int
sys_gen_rand(sys_data_t *lan, void *data, int len)
{
    gen_rand(NULL, data, len);
    return 0;
}
void * Pattern_Completion_worker(void * arg){

    //cast input args to data structure
    THREAD_3_2_DAT * IN = arg;

    //********************** INITIALIZE PARAMS!!! *************************

    // Initialize random seed
    int randseed = time(NULL);
    srand( randseed );
    printf("Thread %d seeded with %d\n", IN->id, randseed);

    // Simulation Params
    int tr, st, i, j, k, l, t, pat, gr;  //counters
    double pat_score;
    double withresh = 0.8;
    int n_s = 5000;  //timesteps in each step
    int n_perc = 10000;  //timesteps in simulation for calculating perc correct
    double dt = 1e-4;   //timestep duration
    int no = 5; //number of oscillators
    int g = 2*no;   //number of neuron groups
    double R_s[n_s][g]; //Rate vectors for step
    double R_perc[n_perc][g]; //Rate vectors for finding perccorr
    double gamma[g];
        for ( i=0; i<g; i+=2 ){
            gamma[i] = 10;      //E cells
            gamma[i+1] = -10;   //I cells
        }
    double tau[g];
        for ( i=0; i<g; i+=2 ){
            tau[i] = 2e-3;      //E cells (AMPA syn time constant)
            tau[i+1] = 10e-3;   //I cells (GABA_A syn time constant)
        }
    
    //Weights
    double wee=2, wei=2.873, wie=-2.873, wii=-2;  //Within-oscillator weights
        double wW[2][2];
        wW[0][0]=wee;   wW[0][1]=wei;   //EE    EI
        wW[1][0]=wie;   wW[1][1]=wii;   //IE    II
    double W_0[g][g];
        //double xee=0.2, xei=0.3, xie=-0.5, xii=0;  //Init Between-osc weights
        double wf = 2/((double) no);
        double xee=0.2*wf, xei=0.3*wf, xie=-0.5*wf, xii=0*wf;  //Init Between-osc weights
        //double xee=0.2, xei=0.3, xie=-0.5, xii=0;  //Init Between-osc weights
        assignPingW(no, W_0, wee, wei, wie, wii, xee, xei, xie, xii);
    int step = 10; //step for recording plasticity
    double W_t[n_s/step][g][g];
    int W_c[g][g];  //Which synapses have plasticity?
        for (i=0; i<g; i++){ 
            for (j=0; j<g; j++){ 
                if (i%2==0 && j%2==0){
                    W_c[i][j]=1; //only xEE synapses change
                } else {
                    W_c[i][j]=0;
                }
            }
        }

    //Get init rates
    double R_i[g];
    int p=1000;
    double rates[p][2];
    get_last_period(&p, rates, wW);

    //Trial parameters
    int numtr = IN->numtr;     //number of trials
    int numsteps = IN->numsteps;  //number of stdp measurements within each trial
    double W_tr[g][g]; //weights for this trial
    //phasediff trial params
    int percres = IN->percres;    //resolution of phdiff measurements per step
    double perc_sum;
    double pds[g][g];

    //Randomness/heterogeinity
    double w_ran = 0.001;
    //double w_ran = 0.005;
    //double r_ran = 0.02;
    double r_ran = 0.02;
    double r_noise = 0.01;

    //filenames
    char * fname_cum_w = "cum_w.dat";
        FILE * cum_w_file_n = fopen(fname_cum_w, "w");
        fclose(cum_w_file_n);
        FILE * cum_w_file;
    /*
    char * fname_cum_r = "cum_r.dat";
        FILE * cum_r_file_n = fopen(fname_cum_r, "w");
        fclose(cum_r_file_n);
        FILE * cum_r_file;
    */
    char * fname_cum_r_t = "cum_r_t.dat";
        FILE * cum_r_t_file_n = fopen(fname_cum_r_t, "w");
        fclose(cum_r_t_file_n);
        FILE * cum_r_t_file;
    
    //Patterns
    int numpats = 2;
    int p_ind;
    double pats[numpats][no];
        //First pattern (1, 2, 3)
        pats[0][0] = 0;
        pats[0][1] = 0;
        pats[0][2] = 0;
        pats[0][3] = M_PI;
        pats[0][4] = M_PI;
        //Second pattern (3, 4, 5)
        pats[1][0] = M_PI;
        pats[1][1] = M_PI;
        pats[1][2] = 0;
        pats[1][3] = 0;
        pats[1][4] = 0;
    double t_pat[no];
        t_pat[0] = 0; 
        t_pat[1] = M_PI; 
        t_pat[2] = 0; 
        t_pat[3] = M_PI; 
        t_pat[4] = M_PI; 

    //declare array for storing weights
    double weights[numsteps*numpats][no-1];

    //********************* SIMULATE STARTING IN-PHASE!!! ********************

    for (tr=IN->a; tr<IN->b; tr++){
        
        //set init weights with a *little* randomness
        for (i=0;i<g;i++){ 
            for (j=0;j<g;j++){ 
                W_tr[i][j]=W_0[i][j]+w_ran*gen_randn(); 
            }
        }

        //Simulate in steps
        for (st=0; st<numsteps; st++){

            printf("Trial %d of %d, Step %d of %d\n", tr, numtr, st, numsteps);

            //Present each pattern + update weights
            for (pat=0; pat<numpats; pat++){
                
                //Set init rates
                for (gr=0; gr<no; gr++){
                    p_ind = ( (int) (
                            p + 
                            (((double) p)*pats[pat][gr]/2/M_PI) + //plus pattern phase
                            (((double) p)*r_ran*gen_randn()/M_PI) // +/- r_ran phase
                        ))
                        %p;
                    //printf("train: p_ind for patt:%d gr:%d = %d\n", pat, gr, p_ind);
                    R_i[gr*2] = rates[p_ind][0]+r_noise*gen_rand(); //E
                    R_i[gr*2+1] = rates[p_ind][1]+r_noise*gen_rand(); //I
                    //if (IN->id==0){ printf("\tpats[%d][%d]=%f\tp_ind=%d    \trates[%d]=%f\n", pat, gr, pats[pat][gr], p_ind, gr*2, rates[p_ind][0]); }
                }

                //Simulate w/ pattern
                rateN(g, n_s, R_s, R_i, W_tr, gamma, tau, dt);

                //append to file for rates + weights
                if (IN->id==0 && st%10==0 && (st>100 || st<2) ){
                    printf("saving rates\n");
                    cum_r_t_file = fopen(fname_cum_r_t, "a");
                    for (t=0; t<n_s-1; t++){
                        for (gr=0; gr<no; gr++){
                            fprintf(cum_r_t_file, "%f \t", R_s[t][gr*2]);
                        }
                        fprintf(cum_r_t_file, "\n");
                    }
                    fclose(cum_r_t_file);
                }

                //Apply STDP
                rateSTDP(n_s, g, dt, R_s, W_t, W_tr, W_c); 

                //Update weights
                for (i=0;i<g;i++){ 
                    for (j=0;j<g;j++){ 
                        if (W_t[n_s/step-1][i][j]>0){
                            W_tr[i][j] = W_t[n_s/step-1][i][j]; 
                        }
                    }
                }

                //append to file for rates + weights
                /*
                if (IN->id==0 && i==0 && (st>100 || st==1) ){
                    //append weights
                    printf("Saving weights...\n");
                    cum_w_file = fopen(fname_cum_w,"a");
                    for (i=0; i<n_s/step-1; i++){
                        for (j=1; j<no; j++){
                            fprintf(cum_w_file, "%f \t", W_t[i][0][j*2]);
                        }
                        fprintf(cum_w_file, "\n");
                    }
                    fclose(cum_w_file);
                    //append rates
                    printf("Saving rates...\n");
                    cum_r_file = fopen(fname_cum_r,"a");
                    for (i=0; i<n_s-1; i++){
                        for (j=0; j<no; j++){
                            fprintf(cum_r_file, "%f \t", R_s[i][j*2]);
                        }
                        fprintf(cum_r_file, "\n");
                    }
                    fclose(cum_r_file);



                    printf("done...\n");
                }
                */

            }

            

            //find perc correct over lots of trials on TEST PATTERN
            perc_sum= 0;
            for (i=0; i<percres; i++){
                    
                //set init rates for test pattern w/ randomness
                for (gr=0; gr<no; gr++){
                    p_ind = ( (int) (
                            p + 
                            (((double) p)*t_pat[gr]/2/M_PI) + //plus pattern phase
                            (((double) p)*r_ran*gen_randn()/M_PI) // +/- r_ran phase
                        ))
                        %p;
                    R_i[gr*2] = rates[p_ind][0]+r_noise*gen_rand(); //E
                    R_i[gr*2+1] = rates[p_ind][1]+r_noise*gen_rand(); //I
                }

                //simulate
                rateN(g, n_perc, R_perc, R_i, W_tr, gamma, tau, dt);

                //is the SS pattern correct? (use alpha-score?)
                phdiff2(n_perc, g, R_perc, pds);
                pat_score = 0;
                for (gr=0; gr<no; gr++){
                    if (WITHN(ABS(pds[0][0]-pds[0][2*gr]), ABS(pats[0][0]-pats[0][gr]), withresh)){
                        pat_score++;
                    }
                }

                //if match, add this perc correct score to sum
                if (pat_score==no){
                    perc_sum++;
                }

                //append to file for rates + weights
                /*
                if (IN->id==0 && i==0 && st%10==0 && (st>100 || st<2) ){
                    printf("saving rates\n");
                    cum_r_file = fopen(fname_cum_r, "a");
                    for (t=0; t<n_perc-1; t++){
                        for (gr=0; gr<no; gr++){
                            fprintf(cum_r_file, "%f \t", R_perc[t][gr*2]);
                        }
                        fprintf(cum_r_file, "\n");
                    }
                    fclose(cum_r_file);
                }
                */

            }

            //Add this avg perc correct to array
            IN->perccorr[tr*numsteps+st] = perc_sum/((double) percres);
            printf("percscore=%f\n", perc_sum/((double) percres));


            //Performance gets terrible as weights get too high
            //and performance goes-> zero quickly, so just assign zero
            /*
            if ( perc_sum/((double) percres) < 0.7 ){
                for (i=st; i<numsteps; i++){
                    IN->perccorr[tr*numsteps+i] = 0;
                }
                break;
            }
            */
        }

    }

}
int main(int argc, char** argv)
{
  ros::init(argc, argv, "collision_proximity_test");
 
  ros::NodeHandle nh;

  std::string robot_description_name = nh.resolveName("robot_description", true);

  srand ( time(NULL) ); // initialize random seed
  ros::service::waitForService(ARM_QUERY_NAME);

  ros::ServiceClient query_client = nh.serviceClient<kinematics_msgs::GetKinematicSolverInfo>(ARM_QUERY_NAME);

  kinematics_msgs::GetKinematicSolverInfo::Request request;
  kinematics_msgs::GetKinematicSolverInfo::Response response;

  query_client.call(request, response);
  int num_joints;
  std::vector<double> min_limits, max_limits;
  num_joints = (int) response.kinematic_solver_info.joint_names.size();
  std::vector<std::string> joint_state_names = response.kinematic_solver_info.joint_names;
  std::map<std::string, double> joint_state_map;
  for(int i=0; i< num_joints; i++)
  {
    joint_state_map[joint_state_names[i]] = 0.0;
    min_limits.push_back(response.kinematic_solver_info.limits[i].min_position);
    max_limits.push_back(response.kinematic_solver_info.limits[i].max_position);
  }
  
  std::vector<std::vector<double> > valid_joint_states;
  valid_joint_states.resize(TEST_NUM);
  for(unsigned int i = 0; i < TEST_NUM; i++) {
    std::vector<double> jv(7,0.0);
    for(unsigned int j=0; j < min_limits.size(); j++)
    {
      jv[j] = gen_rand(std::max(min_limits[j],-M_PI),std::min(max_limits[j],M_PI));
    } 
    valid_joint_states[i] = jv;
  }

  collision_proximity::CollisionProximitySpace* cps = new collision_proximity::CollisionProximitySpace(robot_description_name);
  ros::ServiceClient planning_scene_client = nh.serviceClient<arm_navigation_msgs::GetPlanningScene>(planning_scene_name, true);      
  ros::service::waitForService(planning_scene_name);

  arm_navigation_msgs::GetPlanningScene::Request ps_req;
  arm_navigation_msgs::GetPlanningScene::Response ps_res;

  arm_navigation_msgs::CollisionObject obj1;
  obj1.header.stamp = ros::Time::now();
  obj1.header.frame_id = "odom_combined";
  obj1.id = "obj1";
  obj1.operation.operation = arm_navigation_msgs::CollisionObjectOperation::ADD;
  obj1.shapes.resize(1);
  obj1.shapes[0].type = arm_navigation_msgs::Shape::BOX;
  obj1.shapes[0].dimensions.resize(3);
  obj1.shapes[0].dimensions[0] = .1;
  obj1.shapes[0].dimensions[1] = .1;
  obj1.shapes[0].dimensions[2] = .75;
  obj1.poses.resize(1);
  obj1.poses[0].position.x = .6;
  obj1.poses[0].position.y = -.6;
  obj1.poses[0].position.z = .375;
  obj1.poses[0].orientation.w = 1.0;

  arm_navigation_msgs::AttachedCollisionObject att_obj;
  att_obj.object = obj1;
  att_obj.object.header.stamp = ros::Time::now();
  att_obj.object.header.frame_id = "r_gripper_palm_link";
  att_obj.link_name = "r_gripper_palm_link";
  att_obj.touch_links.push_back("r_gripper_palm_link");
  att_obj.touch_links.push_back("r_gripper_r_finger_link");
  att_obj.touch_links.push_back("r_gripper_l_finger_link");
  att_obj.touch_links.push_back("r_gripper_r_finger_tip_link");
  att_obj.touch_links.push_back("r_gripper_l_finger_tip_link");
  att_obj.touch_links.push_back("r_wrist_roll_link");
  att_obj.touch_links.push_back("r_wrist_flex_link");
  att_obj.touch_links.push_back("r_forearm_link");
  att_obj.touch_links.push_back("r_gripper_motor_accelerometer_link");
  att_obj.object.id = "obj2";
  att_obj.object.shapes[0].type = arm_navigation_msgs::Shape::CYLINDER;
  att_obj.object.shapes[0].dimensions.resize(2);
  att_obj.object.shapes[0].dimensions[0] = .025;
  att_obj.object.shapes[0].dimensions[1] = .5;
  att_obj.object.poses.resize(1);
  att_obj.object.poses[0].position.x = .12;
  att_obj.object.poses[0].position.y = 0.0;
  att_obj.object.poses[0].position.z = 0.0;
  att_obj.object.poses[0].orientation.w = 1.0;

  ps_req.collision_object_diffs.push_back(obj1);
  ps_req.attached_collision_object_diffs.push_back(att_obj);

  arm_navigation_msgs::GetRobotState::Request rob_state_req;
  arm_navigation_msgs::GetRobotState::Response rob_state_res;

  ros::Rate slow_wait(1.0);
  while(1) {
    if(!nh.ok()) {
      ros::shutdown();
      exit(0);
    }
    planning_scene_client.call(ps_req,ps_res);
    ROS_INFO_STREAM("Num coll " << ps_res.all_collision_objects.size() << " att " << ps_res.all_attached_collision_objects.size());
    if(ps_res.all_collision_objects.size() > 0
       && ps_res.all_attached_collision_objects.size() > 0) break;
    slow_wait.sleep();
  }

  ROS_INFO("After test");
  
  ros::ServiceClient robot_state_service = nh.serviceClient<arm_navigation_msgs::GetRobotState>(robot_state_name, true);      
  ros::service::waitForService(robot_state_name);

  planning_models::KinematicState* state = cps->setupForGroupQueries("right_arm_and_end_effector",
                                                                     ps_res.complete_robot_state,
                                                                     ps_res.allowed_collision_matrix,
                                                                     ps_res.transformed_allowed_contacts,
                                                                     ps_res.all_link_padding,
                                                                     ps_res.all_collision_objects,
                                                                     ps_res.all_attached_collision_objects,
                                                                     ps_res.unmasked_collision_map);

  ros::WallDuration tot_ode, tot_prox;
  ros::WallDuration min_ode(1000.0,1000.0);
  ros::WallDuration min_prox(1000.0, 1000.0);
  ros::WallDuration max_ode;
  ros::WallDuration max_prox;

  std::vector<double> link_distances;
  std::vector<std::vector<double> > distances;
  std::vector<std::vector<tf::Vector3> > gradients;
  std::vector<std::string> link_names;
  std::vector<std::string> attached_body_names;
  std::vector<collision_proximity::CollisionType> collisions;
  unsigned int prox_num_in_collision = 0;
  unsigned int ode_num_in_collision = 0;

  ros::WallTime n1, n2;

  for(unsigned int i = 0; i < TEST_NUM; i++) {
    for(unsigned int j = 0; j < joint_state_names.size(); j++) {
      joint_state_map[joint_state_names[j]] = valid_joint_states[i][j];
    }
    state->setKinematicState(joint_state_map);
    n1 = ros::WallTime::now();
    cps->setCurrentGroupState(*state);
    bool in_prox_collision = cps->isStateInCollision();
    n2 = ros::WallTime::now();
    if(in_prox_collision) {
      prox_num_in_collision++;
    }
    ros::WallDuration prox_dur(n2-n1);
    if(prox_dur > max_prox) {
      max_prox = prox_dur;
    } else if (prox_dur < min_prox) {
      min_prox = prox_dur;
    }
    tot_prox += prox_dur;
    n1 = ros::WallTime::now();
    bool ode_in_collision = cps->getCollisionModels()->isKinematicStateInCollision(*state);
    n2 = ros::WallTime::now();
    if(ode_in_collision) {
      ode_num_in_collision++;
    }
    if(0){//in_prox_collision && !ode_in_collision) {
      ros::Rate r(1.0);
      while(nh.ok()) {
        cps->getStateCollisions(link_names, attached_body_names, in_prox_collision, collisions);
        ROS_INFO("Prox not ode");
        cps->visualizeDistanceField();
        cps->visualizeCollisions(link_names, attached_body_names, collisions);
        cps->visualizeConvexMeshes(cps->getCollisionModels()->getGroupLinkUnion());
        std::vector<std::string> objs = link_names;
        objs.insert(objs.end(), attached_body_names.begin(), attached_body_names.end());
        cps->visualizeObjectSpheres(objs);
        //cps->visualizeVoxelizedLinks(collision_models->getGroupLinkUnion());
        r.sleep();
      }
      exit(0);
    }
    if(0 && !in_prox_collision && ode_in_collision) {
      ros::Rate r(1.0);
      while(nh.ok()) {
        ROS_INFO("Ode not prox");
        cps->visualizeDistanceField();
        cps->getStateCollisions(link_names, attached_body_names, in_prox_collision, collisions);
        cps->visualizeCollisions(link_names, attached_body_names, collisions);
        cps->visualizeConvexMeshes(cps->getCollisionModels()->getGroupLinkUnion());
        std::vector<std::string> objs = link_names;
        objs.insert(objs.end(), attached_body_names.begin(), attached_body_names.end());
        cps->visualizeObjectSpheres(objs);
        r.sleep();
      }
      //cps->visualizeVoxelizedLinks(collision_models->getGroupLinkUnion());
      std::vector<collision_space::EnvironmentModel::AllowedContact> allowed_contacts;
      std::vector<collision_space::EnvironmentModel::Contact> contact;
      cps->getCollisionModels()->getCollisionSpace()->getCollisionContacts(allowed_contacts, contact, 10);   
      for(unsigned int i = 0; i < contact.size(); i++) {
        std::string name1;
        std::string name2;
        if(contact[i].link1 != NULL) {
          if(contact[i].link1_attached_body_index != 0) {
            name1 = contact[i].link1->getAttachedBodyModels()[contact[i].link1_attached_body_index-1]->getName();
          } else {
            name1 = contact[i].link1->getName();
          }
        }
        if(contact[i].link2 != NULL) {
          if(contact[i].link2_attached_body_index != 0) {
            name2 = contact[i].link2->getAttachedBodyModels()[contact[i].link2_attached_body_index-1]->getName();
          } else {
            name2 = contact[i].link2->getName();
          }
        } else if (!contact[i].object_name.empty()) {
          name2 = contact[i].object_name;
        }
        ROS_INFO_STREAM("Contact " << i << " between " << name1 << " and " << name2);
      }
      exit(0);
      if(0) {
        std::vector<double> prox_link_distances;
        std::vector<std::vector<double> > prox_distances;
        std::vector<std::vector<tf::Vector3> > prox_gradients;
        std::vector<std::string> prox_link_names;
        std::vector<std::string> prox_attached_body_names;
        cps->getStateGradients(prox_link_names, prox_attached_body_names, prox_link_distances, prox_distances, prox_gradients);
        ROS_INFO_STREAM("Link size " << prox_link_names.size());
        for(unsigned int i = 0; i < prox_link_names.size(); i++) {
          ROS_INFO_STREAM("Link " << prox_link_names[i] << " closest distance " << prox_link_distances[i]);
        }
        for(unsigned int i = 0; i < prox_attached_body_names.size(); i++) {
          ROS_INFO_STREAM("Attached body names " << prox_attached_body_names[i] << " closest distance " << prox_link_distances[i+prox_link_names.size()]);
        }
        exit(0);
      }
    }
    ros::WallDuration ode_dur(n2-n1);
    if(ode_dur > max_ode) {
      max_ode = ode_dur;
    } else if (ode_dur < min_ode) {
      min_ode = ode_dur;
    }
    tot_ode += ode_dur;
    
  }
//ROS_INFO_STREAM("Setup prox " << tot_prox_setup.toSec()/(TEST_NUM*1.0) << " ode " << tot_ode_setup.toSec()/(TEST_NUM*1.0));
  ROS_INFO_STREAM("Av prox time " << (tot_prox.toSec()/(TEST_NUM*1.0)) << " min " << min_prox.toSec() << " max " << max_prox.toSec()
                  << " percent in coll " << (prox_num_in_collision*1.0)/(TEST_NUM*1.0));
  ROS_INFO_STREAM("Av ode time " << (tot_ode.toSec()/(TEST_NUM*1.0)) << " min " << min_ode.toSec() << " max " << max_ode.toSec()
                  << " percent in coll " << (ode_num_in_collision*1.0)/(TEST_NUM*1.0));

  ros::shutdown();

  delete cps;

}
Ejemplo n.º 19
0
//filename of parent , buffer new neur is put into
void new_neur(char *fn, char** buffer, int *new_buff_size) {
    int len=0;
    //printf("  --- newneur_desc_file ---\n");
    FILE *file;
    char* desc_raw;
    file = fopen(fn,"rb");
    if(file != NULL) {
        fseek(file,0L,SEEK_END);
        long int size = ftell(file);
        //printf("  Info: File size: %ld\n",size);
        fseek(file,0L,SEEK_SET);
        desc_raw=(char*)malloc(size+1);
        if(!desc_raw) {
            fprintf(stderr,"  Error: new_neur: Cant read to buffer!.\n");
            free(desc_raw);
            fclose(file);
            return;
        }
        fread(desc_raw,size,1,file);
        fclose(file);
        //printf("  Info: Read file size: %ld\n",size);
        //Reader header info
        unsigned int non=0;
        unsigned int noc=0;//number of connections
        /* Header */
        memcpy(&non,&desc_raw[0],sizeof(unsigned int));//number of neurs
        memcpy(&noc,&desc_raw[sizeof(unsigned int)],sizeof(unsigned int));//number of cons
        int head_end=sizeof(unsigned int)*2;

        //printf("  Info: Num of Neurons: %u  Number of Cons: %u  Head end: %u\n", non,noc,head_end);

        if((neur_desc_bytesize* non)+head_end!=size) {
            printf("  new_neur Error: !!!!! OBJ file does not match expected size !!!!!\n");
            printf("          Expected %u    Received %ld \n", (neur_desc_bytesize* non)+head_end,size);
            printf("          NON:%u   neur_desc_bytesize:%d    head_end:%d\n", non, neur_desc_bytesize, head_end);
            free(desc_raw);
            return;
        }
        else {
            //printf("  Status: File matched expected size.\n");
        }
        //END HEADER
        //BEGIN PARSING NEURS
        len = (neur_desc_bytesize* ((non)+1))+head_end;//new buffer size
        *buffer=(char*)malloc(len);//allocae enough size for 1 more neur
        *new_buff_size=len;
        memcpy(*buffer,&desc_raw[0],size);//copy old buffer to new buffer
        non++;//increase num of neurs by 1
        //write new non to begining of new buffer
        memcpy(*buffer,&non,sizeof(unsigned int));

        int offset=size;
        /* new neur data */
        unsigned int id = non-1;//non is number and id is index, non is naturally 1 plus last index
        double thresh =gen_rand(0,20);
        double var = gen_rand(0,20);
        unsigned int bd[5];
        bd[0]=rand()%(num_behav_pre+1);
        bd[1]=rand()%(num_behav_weight+1);
        bd[2]=rand()%(num_behav_thresh+1);
        bd[3]=rand()%(num_behav_fire+1);
        bd[4]=rand()%(num_behav_post+1);
        bool mapped = false;
        unsigned int out_index=-1;
        /* end new neur data */
        //printf("     mut.cpp :::: bd[3]: %u\n",bd[4]);


        //append data to end of buffe
        //neur id
        memcpy(&(*buffer)[offset],&id,sizeof(unsigned int));
        //printf("NEW NEUR ID: %u",id);
        offset+=sizeof(unsigned int);
        //thresh
        memcpy(&(*buffer)[offset],&thresh,sizeof(double));
        offset+=sizeof(double);
        memcpy(&(*buffer)[offset],&var,sizeof(double)); //unused var
        offset+=sizeof(double);
        //printf(" new_neur: behav_d[4]: %u",bd[4]);
        memcpy(&(*buffer)[offset],&bd[0],sizeof(unsigned int)*5);
        offset+=sizeof(unsigned int)*5;
        memcpy(&(*buffer)[offset],&mapped,sizeof(bool));
        offset+=sizeof(bool);
        memcpy(&(*buffer)[offset],&out_index,sizeof(unsigned int));
        offset+=sizeof(unsigned int);

    } else {
        cout <<"  New neur: Error: Cant open file\n";
        return;
    }
    //printf("  ---end new_neur---\n");

    free(desc_raw);
}
int main(void){

    /*********** INITIALIZE STUFF *************/
    /* Initialize random seed */
    time_t randseed = time(NULL);
    srand(randseed);
    printf("Seeded with %lld\n", (long long) randseed);

    int n=10000; //timesteps per plastic trial
    int no=5; //number of oscillators
    int plasticTrials = 10;
    int g=2*no; //number of groups
    double dt = 0.0001;
    int t,i,j,k,l;  //counters
    double Re[n][no], R_i[no][2]; //Excitatory rate vector and initial rate vec
    double R[n][g]; //All groups rate vec

    //Init weights
    int rw = 100;  //how often to record syn weights
    double W_t[n/rw][g][g]; //Weight matrix over time
    double wW[2][2];    //Within-oscillator synaptic weights
        wW[0][0]=2;         wW[0][1]=2.873; //EE    EI
        wW[1][0]=-2.873;    wW[1][1]=-2;    //IE    II
    double scl = 2/((double)no);
    double xW[2][2];    //Initial x-group synaptic strengths
        xW[0][0]=0.2*scl;   xW[0][1]=0.3*scl;   //xEE   xEI
        xW[1][0]=-0.5*scl;  xW[1][1]=0*scl;     //xIE   xII
    double W[g][g];    //All weights
    for (i=0;i<g;i++){ for (j=0;j<g;j++){
        if (i/2==j/2){ //within-group block
            W[i][j]=wW[i%2][j%2];
        } else { //cross-group
            W[i][j]=xW[i%2][j%2];
        }
    }}
    double W_1D[g*g];
    for (i=0;i<g;i++){
        for (j=0;j<g;j++){
            W_1D[g*i+j] = W[i][j];
        }
    }
    //TODO: debugger
    for (i=0;i<g;i++){
        for (j=0;j<g;j++){
            printf("%f\t", W[i][j]);
        }
        printf("\n");
    }
    

    //Weights alowed to change?
    int W_c[g][g];
    for (i=0;i<g;i++){ for (j=0;j<g;j++){
        if (i%2==0 && j%2==0 && i!=j){ //if we're @ an xEE weight,
            W_c[i][j]=1;
        } else {
            W_c[i][j]=0;
        }
    }}

    //Weight bounds?
    int W_b[g][g];
    for (i=0;i<g;i++){ for (j=0;j<g;j++){
        if (i%2==0 && j%2==0 && i!=j){ //if we're @ an xEE weight,
            W_b[i][j]=0.3;
        } else {
            W_b[i][j]=0;
        }
    }}

    //Plasticity time constants
    double t_w = 5000;
    double t_th = 500;

    double th[g][g];
    for (i=0;i<g;i++){ for (j=0;j<g;j++){
        if (i%2==0 && j%2==0 && i!=j){ //if we're @ an xEE weight,
            th[i][j]=15;
        } else {
            th[i][j]=0;
        }
    }}

    //Gamma and tau
    double gamma[g];
    for (i=0;i<g;i+=2){
        gamma[i] = 10;      //Excitatory
        gamma[i+1] = -10;   //Inhibitory
    }
    double tau[g];
    for (i=0;i<g;i+=2){
        tau[i] = 0.002; //AMPA (Excitatory - 2ms)
        tau[i+1] = 0.01; //GABA_A (Inhibitory - 10ms)
    }

    //Find initial rate vector
    int p=1000;
    double lp_rates[p][2];
    get_last_period(&p, lp_rates, wW);

    double R_i_A1[no][2];
            R_i_A1[0][0] = lp_rates[0][0]+gen_rand(); //O1, 2, and 3 are IN-phase,
            R_i_A1[0][1] = lp_rates[0][1]+gen_rand();
            R_i_A1[1][0] = lp_rates[0][0]+gen_rand();
            R_i_A1[1][1] = lp_rates[0][1]+gen_rand();
            R_i_A1[2][0] = lp_rates[0][0]+gen_rand();
            R_i_A1[2][1] = lp_rates[0][1]+gen_rand();
            R_i_A1[3][0] = lp_rates[p/2][0]+gen_rand(); //O4, 5 are OUT-phase
            R_i_A1[3][1] = lp_rates[p/2][1]+gen_rand();
            R_i_A1[4][0] = lp_rates[p/2][0]+gen_rand();
            R_i_A1[4][1] = lp_rates[p/2][1]+gen_rand();

    //Plastic runs
    int pd_res = 1000; //How many phase diff trials to do per plastic run
    int pl_res = 2; //How many plastic runs to do
    double o2_vec[pd_res], o3_vec[pd_res], o4_vec[pd_res], o5_vec[pd_res]; 
    double avgphdiffs[pl_res][4];
    double stdphdiffs[pl_res][4];

    //Multithreading stuff
    double phdiffs[4*pd_res];
    pthread_t threads[NUM_THREADS];
    THREAD_DAT_1D t_args[NUM_THREADS];
    int t_divs[NUM_THREADS+1];
    segment_threads(NUM_THREADS, 0, pd_res, t_divs);


    
    //put data in thread args
    for (i=0;i<NUM_THREADS;i++){
        t_args[i].id = i;
        t_args[i].a = t_divs[i];
        t_args[i].b = t_divs[i+1];
        t_args[i].res = pd_res;
        t_args[i].DATA = (double *)&phdiffs;
        t_args[i].DATA_IN = (double *)&W_1D;
    }


    /*********** TESTER RUN OF 5 GROUPS w/ RANDOM START ***********/
/*
    double Rees[n][no];
    int nn = 20000, phaseInd;
    double R_i_rand[no][2];
            R_i_rand[0][0] = lp_rates[0][0];
            R_i_rand[0][1] = lp_rates[0][1];
            R_i_rand[1][0] = lp_rates[0][0];
            R_i_rand[1][1] = lp_rates[0][1];
        for (i=2;i<no;i++){
            phaseInd = rand() % p;
            R_i_rand[i][0] = lp_rates[phaseInd][0];
            R_i_rand[i][1] = lp_rates[phaseInd][1];
        }
    pingRateN(nn,no,Rees,R_i_rand,W[0]*2/5,W[1]*2/5,W[2]*2/5,W[3]*2/5,wW,dt);
    char * fn_prnt = "Learned_group_synchrony_5grouptester.dat";
    asave(n, no, Rees, fn_prnt);
    printf("Done with pingRateN 5-group tester - data saved as %s\n", fn_prnt);
 */   



/******************************* LOOP THROUGH PLASTIC RUNS *****************/

    //Create new file to store weights
    char * fn_plas_w = "Learned_group_synchrony_plas_w.dat";
    FILE * pFile_w = fopen(fn_plas_w,"w"); 
    //fprintf(pFile_wn, "\n"); fclose(pFile_wn);
    //FILE * pFile_w = fopen(fn_plas_w,"a"); //now open it for appending

    //Create new file to store weights
    char * fn_plas_r = "Learned_group_synchrony_plas_r.dat";
    FILE * pFile_r = fopen(fn_plas_r,"w"); 
    //fprintf(pFile_rn, "\n"); fclose(pFile_rn);
    //FILE * pFile_r = fopen(fn_plas_r,"a"); //now open it for appending


int pr; //plastic loops
for (pr=0; pr<pl_res;pr++){

    /*********** BEFORE PLASTICITY AVG PHDIFFS *************/
    //Run threads
    for (i=0;i<NUM_THREADS;i++){
        pthread_create(&threads[i],NULL,Learned_group_synchrony_worker,(void*)&t_args[i]);
    }

    //Wait for threads to finish
    waitfor_threads(NUM_THREADS, threads);

    //Find avg phdiffs
    for (i=0;i<pd_res;i++){
        o2_vec[i] = phdiffs[i*4];
        o3_vec[i] = phdiffs[i*4+1];
        o4_vec[i] = phdiffs[i*4+2];
        o5_vec[i] = phdiffs[i*4+3];
    }
    avgphdiffs[pr][0] = mean(pd_res, o2_vec);    
    avgphdiffs[pr][1] = mean(pd_res, o3_vec);    
    avgphdiffs[pr][2] = mean(pd_res, o4_vec);    
    avgphdiffs[pr][3] = mean(pd_res, o5_vec);    

    stdphdiffs[pr][0] = std(pd_res, o2_vec);    
    stdphdiffs[pr][1] = std(pd_res, o3_vec);    
    stdphdiffs[pr][2] = std(pd_res, o4_vec);    
    stdphdiffs[pr][3] = std(pd_res, o5_vec);    

    printf("%d: Avg ph diff between O1 and O2: %f +/- %f\n", pr, avgphdiffs[pr][0], stdphdiffs[pr][0]);
    printf("%d: Avg ph diff between O1 and O3: %f +/- %f\n", pr, avgphdiffs[pr][1], stdphdiffs[pr][1]);
    printf("%d: Avg ph diff between O1 and O4: %f +/- %f\n", pr, avgphdiffs[pr][2], stdphdiffs[pr][2]);
    printf("%d: Avg ph diff between O1 and O5: %f +/- %f\n", pr, avgphdiffs[pr][3], stdphdiffs[pr][3]);




    /*********** DO PLASTIC RUNS WHERE A1 IS IN-PHASE ******************/
    printf("STARTING PLASTIC RUN %d\n", pr);

    //Simulate
    //for (l=0; l<plasticTrials; l++){ //alternate A1, A2
    //ASSEMBLY 1

    //plasticRateN_recW call
    plasticRateN_recW(g,n,R,R_i_A1,W_t,W_c,W,W_b,t_w,th,t_th,gamma,tau,dt);
    //Set 2D matrix returned as W -> W_1D for doing above step
    for (i=0;i<g;i++){ for (j=0;j<g;j++){
        W_1D[g*i+j] = W[i][j];
    }}
    //Append to file for weights
    for (t=0;t<n/rw;t++){
        for (i=0;i<g;i++){ for (j=0;j<g;j++){
            if (i%2==0 && j%2==0 && i!=j){ //if we're @ an xEE weight,
                fprintf(pFile_w, "%f\t", W_t[t][i][j]);
                //printf("%f\t", W_t[t][i][j]);
            }
        }}
        fprintf(pFile_w, "\n"); //new timestep
        //printf("\n"); //new timestep
    }
    //Append to file for rates
    for (t=0; t<n; t++){ 
        for (i=0;i<no;i++){
            fprintf(pFile_r, "%f\t", Re[t][i]);
        }
        fprintf(pFile_r, "\n");
    }

    printf("DONE WITH PLASTIC RUN %d\n", pr);

/*
        //ASSEMBLY 2
        plasticPingRateN_recW(n,no,Re,R_i_A2,W[0],W[1],W[2],W[3],
                            xEE_c,xEI_c,xIE_c,xII_c,wW,dt,W_t);    
        W[0] = (W_t[n/rw-1][0][2]+W_t[n/rw-1][0][2])/2; //set new xEE weight for next run
        printf("xEE weight after plastic run %d (A1): %f\n",i,W_t[n/rw-1][0][2]);
        //Append to file for weights
        for (t=0;t<n/rw;t++){
            for (i=0;i<g;i++){ for (j=0;j<g;j++){
                if (i%2==0 && j%2==0 && i!=j){ //if we're @ an xEE weight,
                    fprintf(pFile_w, "%f\t", W_t[t][i][j]);
                }
            }}
            fprintf(pFile_w, "\n"); //new timestep
        }
        //Append to file for rates
        for (t=0; t<n; t++){ 
            for (i=0;i<no;i++){
                fprintf(pFile_r, "%f\t", Re[t][i]);
            }
            fprintf(pFile_r, "\n");
        }
    }
*/

    }

    fclose(pFile_w);
    fclose(pFile_r);

    printf("Done!\n");

    return 0;

}
Ejemplo n.º 21
0
csr_matrix rand_csr(const unsigned int N,const unsigned int density, const double normal_stddev,unsigned long* seed,FILE* log)
{
    unsigned int i,j,nnz_ith_row,nnz,update_interval,rand_col;
    double nnz_ith_row_double,nz_error,nz_per_row_doubled,high_bound;
    int kn[128];
    float fn[128],wn[128];
    char* used_cols;
    csr_matrix csr;

    csr.num_rows = N;
    csr.num_cols = N;
    csr.density_perc = (((double)(density))/10000.0);
    csr.nz_per_row = (((double)N)*((double)density))/1000000.0;
    csr.num_nonzeros = round(csr.nz_per_row*N);
    csr.stddev = normal_stddev * csr.nz_per_row; //scale normalized standard deviation by average NZ/row

    fprintf(log,"Average NZ/Row: %-8.3f\n",csr.nz_per_row);
    fprintf(log,"Standard Deviation: %-8.3f\n",csr.stddev);
    fprintf(log,"Target Density: %u ppm = %g%%\n",density,csr.density_perc);
    fprintf(log,"Approximate NUM_nonzeros: %d\n",csr.num_nonzeros);

    csr.Ap = (unsigned int *) int_new_array(csr.num_rows+1,"rand_csr() - Heap Overflow! Cannot Allocate Space for csr.Ap");
    csr.Aj = (unsigned int *) int_new_array(csr.num_nonzeros,"rand_csr() - Heap Overflow! Cannot Allocate Space for csr.Aj");

    csr.Ap[0] = 0;
    nnz = 0;
    nz_per_row_doubled = 2*csr.nz_per_row; //limit nnz_ith_row to double the average because negative values are rounded up to 0. This
    high_bound = MINIMUM(csr.num_cols,nz_per_row_doubled); //limitation ensures the distribution will be symmetric about the mean, albeit not truly normal.
    used_cols = (char *) malloc(csr.num_cols*sizeof(char));
    check(used_cols != NULL,"rand_csr() - Heap Overflow! Cannot allocate space for used_cols");

    r4_nor_setup(kn,fn,wn);
    srand(*seed);

    update_interval = round(csr.num_rows / 10.0);
    if(!update_interval) update_interval = csr.num_rows;

    for(i=0; i<csr.num_rows; i++)
    {
        if(i % update_interval == 0) fprintf(log,"\t%d of %d (%5.1f%%) Rows Generated. Continuing...\n",i,csr.num_rows,((double)(i))/csr.num_rows*100);

        nnz_ith_row_double = r4_nor(seed,kn,fn,wn); //random, normally-distributed value for # of nz elements in ith row, NORMALIZED
        nnz_ith_row_double *= csr.stddev; //scale by standard deviation
        nnz_ith_row_double += csr.nz_per_row; //add average nz/row
        if(nnz_ith_row_double < 0)
            nnz_ith_row = 0;
        else if(nnz_ith_row_double > high_bound)
            nnz_ith_row = high_bound;
        else
            nnz_ith_row = (unsigned int) round(nnz_ith_row_double);

        csr.Ap[i+1] = csr.Ap[i] + nnz_ith_row;
        if(csr.Ap[i+1] > csr.num_nonzeros)
            csr.Aj = (unsigned int *) realloc(csr.Aj,sizeof(unsigned int)*csr.Ap[i+1]);

        for(j=0; j<csr.num_cols; j++)
            used_cols[j] = 0;

        for(j=0; j<nnz_ith_row; j++)
        {
            rand_col = abs(gen_rand(0,csr.num_cols - 1)); //unsigned long is always non-negative
            if(used_cols[rand_col]) {
                j--;
            }
            else {
                csr.Aj[csr.Ap[i]+j] = rand_col;
                used_cols[rand_col] = 1;
            }
        }
        qsort((&(csr.Aj[csr.Ap[i]])),nnz_ith_row,sizeof(unsigned int),unsigned_int_comparator);
    }

    nz_error = ((double)abs((signed int)(csr.num_nonzeros - csr.Ap[csr.num_rows]))) / ((double)csr.num_nonzeros);
    if(nz_error >= .05)
        fprintf(stderr,"WARNING: Actual NNZ differs from Theoretical NNZ by %5.2f%%!\n",nz_error*100);
    csr.num_nonzeros = csr.Ap[csr.num_rows];
    fprintf(log,"Actual NUM_nonzeros: %d\n",csr.num_nonzeros);
    csr.density_perc = (((double)csr.num_nonzeros)*100.0)/((double)csr.num_cols)/((double)csr.num_rows);
    csr.density_ppm = (unsigned int)round(csr.density_perc * 10000.0);
    fprintf(log,"Actual Density: %u ppm = %g%%\n",csr.density_ppm,csr.density_perc);

    free(used_cols);
    csr.Ax = (float *) float_new_array(csr.num_nonzeros,"rand_csr() - Heap Overflow! Cannot Allocate Space for csr.Ax");
    for(i=0; i<csr.num_nonzeros; i++)
    {
        csr.Ax[i] = 1.0 - 2.0 * common_randJS();
        while(csr.Ax[i] == 0.0)
            csr.Ax[i] = 1.0 - 2.0 * common_randJS();
    }

    return csr;
}
Ejemplo n.º 22
0
void *search(void *unused) {
  // Various size constants for convenience
  const size_t prelen = strlen(PREFIX_STRING);
  const size_t sufflen = strlen(SUFFIX_STRING);
  const size_t suffstart = LEN - sufflen;

  // Buffer used to store candidate string, extra for null terminator.
  char str[LEN + 1];
  str[LEN] = 0;

  // Put in our hardcoded prefix/suffix strings
  strcpy(str, PREFIX_STRING);
  strcpy(str + suffstart, SUFFIX_STRING);

  // Track how many hashes we've tried, for throughput estimate.
  uint64_t count = 0;
  char counting = 1;

  // Thread-local best score achieved, used to avoid
  // unnecessary accesses to shared global_best in the common case.
  int best = INT_MAX;

  // Buffer for storing computed hash bytes
  char hash[128];

start:
  // Fill the middle of the string with random data
  // (not including prefix, suffix, or portion we'll exhaustively search)
  gen_rand(str + prelen, LEN - prelen - sufflen - SEARCH_CHARS);

  // Iteration index array
  // Indirection used to keep character set flexible.
  unsigned idx[SEARCH_CHARS];
  memset(idx, 0, sizeof(idx));

  // Initialize enumeration part of string to first letter in charset
  char *iterstr = str + suffstart - SEARCH_CHARS;
  memset(iterstr, CHARSET[0], SEARCH_CHARS);

  while (1) {
    // Try string in current form
    Hash(1024, (BitSequence *)str, LEN * 8, (BitSequence *)hash);

    // How'd we do?
    int d = hamming_dist(hash, GOAL_BITS, 128);

    // If this is the best we've seen, print it and update best.
    if (d < best) {
      best = d;

      lock();
      if (d < global_best) {
        global_best = d;
        printf("%d - '%s'\n", d, str);
        fflush(stdout);
      }
      unlock();
    }

    // Increment string index array, updating str as we go
    // aaaaaa
    // baaaaa
    // caaaaa
    // ...
    // abaaaa
    // bbaaaa
    // cbaaaa
    // ...
    // (etc)
    int cur = 0;
    while (++idx[cur] >= CHARSET_SIZE) {
      idx[cur] = 0;
      iterstr[cur] = CHARSET[idx[cur]];

      // Advance to next position.
      // If we've used all of our search characters,
      // time to start over with new random prefix.
      if (++cur == SEARCH_CHARS)
        goto start;
    }
    iterstr[cur] = CHARSET[idx[cur]];

    // Throughput calculation.
    // Once this thread hits a limit, increment global_done
    // and print throughput estimate if we're the last thread to do so.
    const uint64_t iters = 1 << 24; // ~16M
    if (counting && ++count == iters) {
      counting = 0;

      time_t end = time(NULL);
      int elapsed = end - global_start;

      lock();
      global_count += count;
      assert(global_count >= count && "counter overflow");
      if (++global_done == num_threads) {
        printf("\n*** Total throughput ~= %f hash/S\n\n",
               ((double)(global_count)) / elapsed);
      }
      unlock();
    }
  }
}
Ejemplo n.º 23
0
void fillRandom(int n /*dimension*/, double *min, double *max, double *x) {
    int i =0;
    for(i=0; i < n /*dimension*/; i++) {
        x[i] =min[i] + (( max[i] - min[i] ) * ((double)gen_rand())/1000000.00); /* generating a random point in the domain */
    }
}
Ejemplo n.º 24
0
int main()
{
  srand(time(NULL));
  int i, retval, j;
  pthread_t tid;
  time_t  t0, t1; /* time_t is defined on <time.h> and <sys/types.h> as long */
  clock_t c0, c1; /* clock_t is defined on <time.h> and <sys/types.h> as int */

  pthread_attr_init(&attr);
  pthread_mutex_init(&my_mutex, NULL);
  
/*  generate values for the M-by-N matrix*/
  for (i=0; i<M; i++)
  {
    for (j=0; j<N; j++)
    {
      matrix_A[i][j] = gen_rand();
    }
  }
  
/*  generate values for the N-by-K matrix*/
  for (i=0; i<N; i++)
  {
    for (j=0; j<K; j++)
    {
      matrix_B[i][j] = gen_rand();
    }
  }
  
/*  initialize all values of the result_matrix to 0's*/
  for (i=0; i<M; i++)
  {
    for (j=0; j<K; j++)
    {
      result_matrix[i][j] = 0;
    }
  }
  
/*  generate values for the N-by-1 vector*/
  for (i=0; i<N; i++)
  {
    vvector[i] = gen_rand();
  }
  
/*  initialize result_vector to all 0's*/
  for (i=0; i<M; i++)
  {
    result_vector[i] = 0;
  }
  
/*  start timing, create threads */
  printf("Main: threads to be created.");
  t0 = time(NULL);
  c0 = clock();
  for (i=0; i< THREAD_COUNT; i++)
  {
          pt_index[i] = i;
          retval = pthread_create(&tid, &attr, Function, (void *)pt_index[i]);
          printf("Main: creating i=%d, tid=%d, retval=%d\n", i, tid, retval);
          thread_id[i] = tid;
  }
  
  printf("\n\n\nJOINING\n\n\n");
  
/*  join threads, stop timing*/
  for (i=0; i< THREAD_COUNT; i++)
  {
          printf("Main: waiting for thread=%d to join\n", thread_id[i]);
          retval = pthread_join(thread_id[i], NULL);
          printf("Main: back from join, thread=%d, retval=%d\n", thread_id[i], retval);
  }
  t1 = time(NULL);
  c1 = clock();
  printf("Main: threads completed.");
  
/*  printf("Matrix A:\n");*/

/*//  print out the M-by-N matrix*/
/*  for (i=0; i<M; i++)*/
/*  {*/
/*    for (j=0; j<N; j++)*/
/*    {*/
/*      if (j == 0)*/
/*      {*/
/*        printf("[");*/
/*      }*/
/*      printf(" %d ", matrix_A[i][j]);*/
/*      if (j == (N-1))*/
/*      {*/
/*        printf("]\n");*/
/*      }*/
/*    }*/
/*  }*/

/*  printf("Matrix B:\n");*/

/*//  print out the N-by-K matrix*/
/*  for (i=0; i<N; i++)*/
/*  {*/
/*    for (j=0; j<K; j++)*/
/*    {*/
/*      if (j == 0)*/
/*      {*/
/*        printf("[");*/
/*      }*/
/*      printf(" %d ", matrix_B[i][j]);*/
/*      if (j == (K-1))*/
/*      {*/
/*        printf("]\n");*/
/*      }*/
/*    }*/
/*  }*/

/*  printf("\n\nResult Matrix:\n");*/

/*//  print out the M-by-K result matrix*/
/*  for (i=0; i<M; i++)*/
/*  {*/
/*    for (j=0; j<K; j++)*/
/*    {*/
/*      if (j == 0)*/
/*      {*/
/*        printf("[");*/
/*      }*/
/*      printf(" %d ", result_matrix[i][j]);*/
/*      if (j == (K-1))*/
/*      {*/
/*        printf("]\n");*/
/*      }*/
/*    }*/
/*  }*/

/*  printf("Vector:\n");*/

/*//  print out the N-by-1 vector*/
/*  for (i=0; i<N; i++)*/
/*  {*/
/*    if (i == 0)*/
/*    {*/
/*      printf("[");*/
/*    }*/
/*    printf(" %d ", vvector[i]);*/
/*    if (i == (N-1))*/
/*    {*/
/*      printf("]\n");*/
/*    }*/
/*  }*/

/*  printf("\n\nResult Vector:\n");*/

/*//  print out the M-by-1 result vector*/
/*  for (i=0; i<M; i++)*/
/*  {*/
/*    if (i == 0)*/
/*    {*/
/*      printf("[");*/
/*    }*/
/*    printf(" %d ", result_vector[i]);*/
/*    if (i == (M-1))*/
/*    {*/
/*      printf("]\n");*/
/*    }*/
/*  }*/

/*  display elapsed time*/
  printf ("elapsed wall clock time: %ld\n", (long) (t1 - t0));
  printf ("elapsed CPU time:        %f\n", (float) (c1-c0));
  return(0);
}
Ejemplo n.º 25
0
int main(int argc, char ** argv)
{
	msg r;
	int i, res;
	int j;
	
	printf("[RECEIVER] Starting.\n");
	init(HOST, PORT);
	int state = get_state(argv[1]);

	for (i = 0; i < COUNT; i++) {
		/* wait for message */

		switch (state) {
		case NONE_STATE:
		{
			printf("STATE = NONE \n");

			recv_message(&r);
			printf("Message = %s\n", r.payload);
			memset(r.payload, 0, MSGSIZE);
			sprintf(r.payload, "%s", "Hello");
			send_message(&r);

			recv_message(&r);
			printf("%s\n", r.payload);
			memset(r.payload, 0, MSGSIZE);
			recv_message(&r);
			printf("%s\n", r.payload);

			memset(r.payload, 0, MSGSIZE);
			sprintf(r.payload, "%s", "YEY");
			send_message(&r);

			memset(r.payload, 0, MSGSIZE);
			sprintf(r.payload, "%s", "OK");
			send_message(&r);

			memset(r.payload, 0, MSGSIZE);
			//recv_message(&r);
			printf("%s\n", r.payload);

			int low = 0;
			int high = 1000;
			int random = gen_rand(low, high);
			int result;
			int middle;
			int found = 0;

			memset(r.payload, 0, MSGSIZE);
			sprintf(r.payload, "%d", random);

			/*
			for (j = 0; j < 10; ++j) {

				send_message(&r);
				recv_message(&r);
				result = process_rand(r.payload);
				middle = (high-low)/2;

				switch(result) {
				case LESS_RAND:
				{
					memset(r.payload, 0, MSGSIZE);
					random = gen_rand(low, middle);
					sprintf(r.payload, "%d", random);
				}
				case MORE_RAND:
				{
					memset(r.payload, 0, MSGSIZE);
					random = gen_rand(middle, high);
					sprintf(r.payload, "%d", random);
				}
				case SUCCESS_RAND:
				{
					found = 1;
					break;
				}
				case NONE_RAND:
				{
				}
				default:
					break;
				}

				if (found)
					break;
			}*/

			break;
		}
		case ACK_STATE:
		{
			printf("STATE = ACK_STATE \n");
			break;
		}
		case PARITY_STATE:
		{
			printf("STATE = PARITY_STATE \n");
			break;
		}
		case HAMMING_STATE:
		{
			printf("STATE = HAMMING_STATE \n");
			break;
		}
		default:
			break;
		}
		res = recv_message(&r);
		if (res < 0) {
			perror("[RECEIVER] Receive error. Exiting.\n");
			return -1;
		}
		
		/* send dummy ACK */
		res = send_message(&r);
		if (res < 0) {
			perror("[RECEIVER] Send ACK error. Exiting.\n");
			return -1;
		}
	}

	printf("[RECEIVER] Finished receiving..\n");
	return 0;
}
Ejemplo n.º 26
0
static void CreateParticles()
{
	int i;
	srand((unsigned)(time(0))); 
	for (i = 0; i < PARTICLES_NUMBER; i++)
	{
		int size = BOX_SIZE;
		particles[i].x = (gen_rand(size)-(size/2))/1.0;
		particles[i].y = (gen_rand(size)-(size/2))/1.0;
		particles[i].z = (gen_rand(size)-(size/2))/1.0;
		while (existsParticleInPos(i, particles[i].x, particles[i].y, particles[i].z))
		{
			particles[i].x = (gen_rand(size)-(size/2))/1.0;
			particles[i].y = (gen_rand(size)-(size/2))/1.0;
			particles[i].z = (gen_rand(size)-(size/2))/1.0;
		}
		particles[i].radius = PARTICLE_RADIUS;
		particles[i].slices = 20;
		particles[i].stacks = 20;
		particles[i].r = (gen_rand(10))/10.0;
		particles[i].g = (gen_rand(10))/10.0;
		particles[i].b = (gen_rand(10))/10.0;
		particles[i].vx = (gen_rand(10)-5)/10.0;
		particles[i].vy = (gen_rand(10)-5)/10.0;
		particles[i].vz = (gen_rand(10)-5)/10.0;
	}
}
Ejemplo n.º 27
0
Archivo: main.c Proyecto: MORDVA/muffin
void translate(char* destinationPath)
{

    int i;    /* Loop counting variables */
    int g;
    int z;
    int j = 0;
    int u;

    /* The binary instruction array */
    char* binaryInstruction[4] = {"XXXX","XXXX","XXXX","XXXX"};

    /* The converted binary line */
    char bufferForLine[20];
    char* lineInBinary = bufferForLine;

    /* Used for splitting the current assembly line into tokens */

    char* tokenPointer;
    char* eachToken[4];

    /* A temporary buffer. Use when nessacary but remember to clear afterwords */

    char tempBuffer[4];

    /* Two parallel arrays used for setting up labels */

    char* labelNames[9999];
    int* labelEncodings = (int*) malloc(sizeof(int) * 1);

    /* Open and set up the file output will be written to */

    FILE *dest;
    dest = fopen(destinationPath, "w");

    printf("\nWriting to %s\n",destinationPath);

    /* Scan through each line of assembly */

    for(i = 0; i < numberOfLines; i++)
    {

        g = 0;

        /** Begin by splitting the current command into tokens */

        tokenPointer = strtok(eachInputLine[i]," ,;");

        while (tokenPointer != NULL)
        {
            eachToken[g] = tokenPointer;
            tokenPointer = strtok (NULL, ", ;");
            g++;
        }

        /* print out the tokens */

        printf("\n==================================\nThe tokens for line %d:\n", i + 1);
        for(z = 0; z < 4; z++)
        {
            printf("\t%s\n",eachToken[z]);
        }

        /** First determine the command and encode it */

        if(strstr(eachToken[0],"mov") != NULL)
        {
            printf("Found a MOV command.\n");
            binaryInstruction[0] = "0002";

            /* Determine the register destination to encode*/

            if(strstr(eachToken[1],"%") != NULL)
            {

                char tempEncoding[20] = "0000";
                char* ptrtempEncoding = tempEncoding;

                sprintf(ptrtempEncoding, "00%d",(int)toupper(*(strstr(eachToken[1],"%") + 1)));
                binaryInstruction[1] = ptrtempEncoding;

                /* Determine the register source */

                char tempEncoding2[20] = "0000";
                char* ptrtempEncoding2 = tempEncoding2;

                sprintf(ptrtempEncoding2, "00%d",(int)toupper(*(strstr(eachToken[2],"%") + 1)));
                binaryInstruction[2] = ptrtempEncoding2;

            }
            else
            {
                fprintf(stderr, "Error on line %d. No register present.", i);
                exit(0);
            }

        }

        else if(strstr(eachToken[0],"halt") != NULL)
        {
            printf("Found a HALT command.\n");
            binaryInstruction[0] = "0000";
        }

        else if(strstr(eachToken[0],"lbl") != NULL)
        {
            printf("Found a LBL command.\n");

            /* Encode the label */
            gen_rand();
            int numberGenerated = gen_rand();
            *labelEncodings = numberGenerated;

            /* Record the label name */
            labelNames[j] = eachToken[1];

            printf("Just found label: %s",labelNames[j]);

            /* Push the label */

            char strToPush[20] = "0000";
            sprintf(strToPush,"%d",*labelEncodings);

            binaryInstruction[0] = "0005";
            binaryInstruction[1] = strToPush;

            /* Increment and reallocate memory */

            j++;
            labelEncodings = (int*) realloc (labelEncodings, sizeof(int) * (j + 1));
            labelEncodings += j;


        }

        else if(strstr(eachToken[0],"jmp") != NULL)
        {
            printf("Found a JMP command.\n");
            printf("Just found jump point: %s", eachToken[1]);

            /* Find the jump name */
            /*for(u = 0; u < j; u++)
            {
                if(eachToken[1]){
                    printf("\nLegal Jump\n");
                    break;
                }
            }*/

            binaryInstruction[0] = "0004";
        }

        else if(strstr(eachToken[0],"load") != NULL)
        {
            printf("Found a LOAD command.\n");
            binaryInstruction[0] = "0001";

            /* Determine the register to load to */

            if(strstr(eachToken[1],"%") != NULL)
            {

                /* Encode the register */

                char tempEncoding3[20] = "0000";
                char* ptrtempEncoding3 = tempEncoding3;

                sprintf(ptrtempEncoding3, "00%d",(int)toupper(*(strstr(eachToken[1],"%") + 1)));

                printf("%c register is being loaded\n",toupper(*(strstr(eachToken[1],"%") + 1)));
                binaryInstruction[1] = ptrtempEncoding3;

                /* Encode the scaler value if present */

                if(strstr(eachToken[2],"#") != NULL)
                {

                    extractScaler(eachToken[2],binaryInstruction);

                }


            }
            else
            {
                fprintf(stderr, "Error on line %d. No register present.", i);
                exit(0);
            }
        }
        /** Push the binary instruction */

        sprintf(lineInBinary, "%s%s%s%s\n", binaryInstruction[0],binaryInstruction[1],binaryInstruction[2],binaryInstruction[3]);

        printf("\nHere is the binary instruction pushed: %s",lineInBinary);

        /* Write the line */

        fprintf(dest,"%s",lineInBinary);

        /* Flush the binary instruction */

        binaryInstruction[0] = "XXXX";
        binaryInstruction[1] = "XXXX";
        binaryInstruction[2] = "XXXX";
        binaryInstruction[3] = "XXXX";

        /* Flush the tokens for the line */

        eachToken[0] = "";
        eachToken[1] = "";
        eachToken[2] = "";
        eachToken[3] = "";

    }

    /* Close the output file */
    fclose(dest);

}
Ejemplo n.º 28
0
int main(int argc, char *argv[]) {
    int opt = 0;
    int longIndex = 0;

    /* Initialize globalArgs before we get to work. */
    globalArgs.version = NULL;    /* false */

	//prepare i18n
	setlocale(LC_ALL, "");
	bindtextdomain("4digits", LOCALE_PATH);
	textdomain("4digits");

    // Process the arguments with getopt_long(), then populate globalArgs
    opt = getopt_long(argc, argv, optString, longOpts, &longIndex);
    while(opt != -1) {
        switch(opt) {
            case 'v':
                globalArgs.version = VERSION_STRING;
                printf("%s\n%s\n%s", VERSION, _(COPYRIGHT), _(AUTHOR));
                exit(1);
            case 'h': 
                err_exit(_(HELP));
                break;
            case '?': /* fall-through is intentional */
                err_exit(_("Usage: 4digits [OPTION]...\n"
                        "Try `4digits --help' for more information."));
                break; 
            case 0:    /* long option without a short arg */
                if(strcmp("version", longOpts[longIndex].name) == 0)
                    break; 
                break;
            default:
                /* You won't actually get here. */
                break;
        }
        opt = getopt_long(argc, argv, optString, longOpts, &longIndex);
    }

    int ans_digits[4];
    gen_rand(ans_digits); /* array for the 4 digits of n*/
    time_t temp = time(NULL);
    time_t tic = temp;
    int guessed[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    int i;
    bool dup = false;

    for (int num_guess = 0; num_guess < 8; num_guess++) {
        int A = 0, B = 0;
        int input = enter_number();

        for(int i=0; i < num_guess; i++)
            // duplicated input
            if (input == guessed[i]) {
                fprintf(stderr, _("You've already guessed it.\n"));
                --num_guess;
                dup = true;
                break;
            }

        if (dup == true) {
            dup = false;
            continue;
        }

        int in_digits[4]; /* arrays for the 4 digits of input*/
        for(i=0; i<4; i++) {
            in_digits[i]=(int) (input / tenpow(3-i) )%10;
        }

        compare(in_digits, ans_digits, &A, &B);
        printf("%dA%dB    ", A, B);
        if (num_guess != 7)
            printf(ngettext("\t %d time left.\n", "\t %d times left.\n", 7-num_guess), 7-num_guess);
        guessed[num_guess] = input;

        if(A == 4) {
            time_t toc = time(NULL);
            int score = (int)(toc-tic);
            printf(_("You win! :) Used %d sec.\n"), score);
            save_score(score); /* save score in the score file */
            return 0;
        }
    }
    printf(_("\nHaha, you lose. It is "));
    for(int i = 0; i < 4; i++)
        printf("%d", ans_digits[i]);
    printf(".\n");
    return 0;
}
Ejemplo n.º 29
0
int main(int argc, char *argv[])
{
//////////////////////////////////////////////////////////////////
//													//
//				VARIABLE DECLARATION SECTION				//
//													//
//////////////////////////////////////////////////////////////////
	int n = atoi(argv[1]); //number of cities
	int numtasks, 	// number of tasks
	taskid, 	// a task identifier
	numworkers, // number of worker tasks
	mtype, 	//Message type
	source, 	// task id of message source
	dest, 	// task id of message destination
	cost, // Least cost
	i, j; //Loop counters
	int c[n][n]; // Cost matrix
	int tour[n]; // Tour matrix
	
	
	double t; // Timer
	struct timeval start, stop;	
	//Initialize
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &taskid);
	MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
	numworkers = numtasks-1;
	
	
	

//////////////////////////////////////////////////////////////////
//													//
//						MASTER SECTION					//
//													//
//////////////////////////////////////////////////////////////////
if(taskid == MASTER){
	//Fill cost matrix
	for (i=1; i<=n; i++)
		for (j=0; j<n; j++)
			c[i][j] = c[j][i] = gen_rand();
	//Set up the first path/pathlength and set the diagonal to 0
	//signifying a move from a city to itself.
	for (i=0; i<n; i++)
	{
		tour[i] = i;
		c[i][i] = 0;
		cost = cost + c[0][i];
	}
		
		
	//Print to user all information being worked on
	printf ("Minimum cost: %d.\nTour: ", cost);
	for (i=0; i<n; i++)
		printf ("%d ", tour[i]);
	printf ("1\n");
		
	//Start timer
	gettimeofday(&start,0);
	t = MPI_Wtime();
	
	
	mtype= FROM_MASTER;
	for(dest = 1; dest <= numworkers; dest++)
	{
		
		
	}
	
	
	/* waiting for results */
	mtype = FROM_WORKER;
	for( i = 1; i <= numworkers; i++)
	{
		
	}
	
	
	
	gettimeofday(&stop, 0);
	//Print elapsed time
	printf("Time = %.6f\n", (stop.tv_sec+stop.tv_usec*1e-6) - (start.tv_sec+start.tv_usec*1e-6));
	}
	
	
//////////////////////////////////////////////////////////////////
//													//
//						MASTER SECTION					//
//													//
//////////////////////////////////////////////////////////////////
if( taskid > MASTER){
		mtype = FROM_MASTER;
		source = MASTER;	
	}
	
	MPI_Finalize();
}