//! average information from another MoreProfiles void Pulsar::PhaseResolvedHistogram::average (const MoreProfiles* more) { const PhaseResolvedHistogram* hist = dynamic_cast<const PhaseResolvedHistogram*> (more); if (!hist) return; const unsigned nprof = profile.size(); for (unsigned iprof=0; iprof < nprof; iprof++) weighted_average (get_Profile(iprof), more->get_Profile(iprof), true); }
pair<double, double> CopulaLatentMarkovNet::metropolis_hasting(int node, double s_iv, double s_h) { double m = s_h/s_iv; double msigma = gmn_marginal_scale_[node]; boost::math::normal nd(0.0, msigma); double c2 = -0.5*(s_iv - 1.0/(msigma*msigma)); double mnew; double vnew; if (observed_labels_[node] != 0) { // labeled node, sample from the marginals double lower = 0.0; double upper = 1.0; if (observed_labels_[node] == -1) upper = cut_[node]; else lower = cut_[node]; boost::scoped_array<double> t(new double[FLAGS_num_mh_samples]); boost::scoped_array<double> logweights(new double[FLAGS_num_mh_samples]); for (int sample = 0; sample < FLAGS_num_mh_samples; ++sample) { double u = random_->Random(); u = u * (upper - lower) + lower; double ts = quantile(nd, u); t[sample] = ts; logweights[sample] = c2*ts*ts + s_h*ts; } mnew = weighted_average(logweights.get(), t.get(), FLAGS_num_mh_samples); for (int sample = 0; sample < FLAGS_num_mh_samples; ++sample) t[sample] *= t[sample]; vnew = weighted_average(logweights.get(), t.get(), FLAGS_num_mh_samples) - mnew*mnew; } else { // unlabeled node, sample from the estimated Gaussian double epsilon = FLAGS_epsilon_mh; double epsilon2 = sqrt(1.0-epsilon*epsilon); mnew = 0.0; vnew = 0.0; double nacc = 0.0; int count = 0; double oldlikelihood = -1e100; boost::math::normal qnd(m, 1.0/sqrt(s_iv)); double oldt; while (nacc < FLAGS_min_mh_samples) { double u = random_->Random(); double g = quantile(qnd, u); double newt = g; if (count > 0) newt = epsilon*g + epsilon2*oldt; double newlikelihood = compute_loglikelihoodpart(newt, nd, msigma); if (log(random_->Random()) < newlikelihood-oldlikelihood) { oldt = newt; mnew += newt; vnew += newt*newt; nacc += 1; oldlikelihood = newlikelihood; } count += 1; if ((count > 100) and (nacc < 0.1*count)) { epsilon = epsilon*0.8; epsilon2 = sqrt(1.0-epsilon*epsilon); // LOG(WARNING) << "acceptance rate < 10%, restart markov chain with epsilon " << epsilon; if (epsilon < 1e-10) { LOG(WARNING) << "epsilon < 1e-10, " << nacc << " samples obtained, giving up"; return make_pair(0.0, 0.0); } oldlikelihood = -1e100; nacc = 0.0; count = 0; mnew = 0.0; vnew = 0.0; } } mnew /= nacc; vnew = vnew/nacc - mnew*mnew; } return make_pair(mnew, vnew); }
int main(int argc, char **argv) { /* the times recorded are: start of programm, start of chain generation, end of chain generation, end of programm */ double time[4]; time[0] = time_of_day(); //----------------------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------------------- // open all neccessary files // general output file, contains basically everything which was written to the terminal FILE * output_file; output_file = fopen("output_file.dat", "w+"); FILE * conv_obs_file; conv_obs_file = fopen("convergence_obs.dat", "w+"); // pair correlation function can be weighted with potentials FILE * pair_correl_file; pair_correl_file = fopen("pair_correlation_function.dat", "w+"); //------------------------------------------------------------------------------ // all files connected to intramolecular interactions FILE * intra_pot_file; intra_pot_file = fopen("intramolecular_obs.dat", "w+"); FILE * intra_boltzman_factors_hist; intra_boltzman_factors_hist = fopen("intramolecular_factors_hist.dat", "w+"); FILE * intra_interactions_file; intra_interactions_file = fopen("intramolecular_interactions_hist.dat", "w+"); // FILE * intra_interactions_testfile; // intra_interactions_testfile = fopen("intramolecular_interactions_testhist.dat", "w+"); FILE * convergence_intraweights; convergence_intraweights = fopen("intramolecular_convergence_Z.dat", "w+"); fprintf(convergence_intraweights, "### convergence_point -- sum-of-boltzman-factors \n"); FILE * conv_intraobs_file; conv_intraobs_file = fopen("intramolecular_convergence_obs.dat", "w+"); //----------------------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------------------- // input and first output // hello message of the programm, always displayed! log_out(output_file, "\n-----------------------------------------------------------------------------------\n"); log_out(output_file, "Roulattice version 1.1, Copyright (C) 2015 Johannes Dietschreit\n"); log_out(output_file, "This program comes with ABSOLUTELY NO WARRANTY; for version details type '-info'.\n"); log_out(output_file, "This is free software, and you are welcome to redistribute it\n"); log_out(output_file, "under certain conditions; type '-license' for details.\n"); log_out(output_file, "\tQuestions and bug reports to: [email protected]\n"); log_out(output_file, "\tPlease include in published work based on Roulattice:\n"); log_out(output_file, "\t\tDietschreit, J. C. B.; Diestler, D. J.; Knapp, E. W.,\n"); log_out(output_file, "\t\tModels for Self-Avoiding Polymer Chains on the Tetrahedral Lattice.\n"); log_out(output_file, "\t\tMacromol. Theory Simul. 2014, 23, 452-463\n"); log_out(output_file, "-----------------------------------------------------------------------------------\n"); /* get the arguments from the comand line */ getArgs(output_file, argc, argv); //------------------------------------------------------------------------------------ // for reading DCD-files // this has to be early in the code, because it sets the variables ARG_numberofbeads and ARG_numberofframes! // variables concerning reading dcd molfile_timestep_t timestep; void *v; dcdhandle *dcd; int natoms; float sizeMB =0.0, totalMB = 0.0; // reading the dcd-file and setting global variables accordingly if (ARG_typeofrun==0) { natoms = 0; v = open_dcd_read(dcdFileName, "dcd", &natoms); if (!v) { fprintf(stderr, "ERROR: open_dcd_read failed for file %s\n", dcdFileName); return EXIT_FAILURE; } dcd = (dcdhandle *)v; sizeMB = ((natoms * 3.0) * dcd->nsets * 4.0) / (1024.0 * 1024.0); totalMB += sizeMB; log_out(output_file, "Read DCD: %d atoms, %d frames, size: %6.1fMB\n", natoms, dcd->nsets, sizeMB); timestep.coords = (float *)malloc(3*sizeof(float)*natoms); ARG_numberofbeads=dcd->natoms; ARG_numberofframes=dcd->nsets; } //------------------------------------------------------------------------------------ // print all the options to the screen so one can check whether the right thing gets computed print_set_options(output_file, ARG_typeofrun, ARG_flength, ARG_fflength, ARG_blength, ARG_numberofbeads, ARG_numberofframes, ARG_randomseed, ARG_bondlength, ARG_torsion, ARG_intra_potential, ARG_intra_parameter1, ARG_intra_parameter2); //----------------------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------------------- // physical constants pi = acos(-1.0); //----------------------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------------------- /* Initialize the most important variables */ // stuff with bond lengths const double inv_sqrt3 = 1.0/sqrt(3.0); const double bondlength = ARG_bondlength; double recast_factor; if (ARG_typeofrun<40){// this recasts walk on diamond lattice recast_factor = inv_sqrt3*bondlength; } else {// this is for runs on simple cubic lattice recast_factor = bondlength; } // variables with atom numbers etc const int last_atom = ARG_numberofbeads -1; const unsigned int number_of_torsions = ARG_numberofbeads -3; // number of frag, fragfags, endfrags, fragbricks, endbricks unsigned int numof_frags_bricks[5] = {0}; // fractions of the number of frames const unsigned long permill_frames = ARG_numberofframes / 1000; // used for convergence const unsigned long percent_frames = ARG_numberofframes / 100; // used for ramining time const unsigned long tenth_frames = ARG_numberofframes / 10; // used for error estimation int cent; int tenth; int counter; // counter which can be used at any parts of the main programm, should only be used locally in a loop // basic moves on the tetrahedral lattice, back and forth const int move[2][4][3] = { { {-1, -1, -1}, {1, 1, -1}, {1, -1, 1}, {-1, 1, 1} }, { {1, 1, 1}, {-1, -1, 1}, {-1, 1, -1}, {1, -1, -1} } }; // moves possible in SAW (no walking back) const int sawmoves[4][3] = { {1, 2, 3}, {0, 2, 3}, {0, 1, 3}, {0, 1, 2} }; //----------------------------------------------------------------------- // building bricks are used to put parts together which are pre-checked int ***building_bricks=NULL; int numberofbricks; if (ARG_typeofrun==13 || ARG_typeofrun==14 || ARG_typeofrun==23 || ARG_typeofrun==24 || ARG_typeofrun==33 || ARG_typeofrun==34){ // thise generates the bricks building_bricks = make_bricks_saw(building_bricks, move, sawmoves, ARG_blength, &numberofbricks, ARG_strictness); if (NULL==building_bricks[0][0]){ return EXIT_FAILURE; } log_out(output_file, "%d bricks were generated, with a length of %d \n", numberofbricks, ARG_blength); } //---------------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------------- /* Initialize beads vector and set all values to zero */ int **int_polymer; int_polymer = calloc(ARG_numberofbeads, sizeof(int *)); double **double_polymer; double_polymer = calloc(ARG_numberofbeads, sizeof(double *)); for (int dim1=0; dim1<ARG_numberofbeads;dim1++){ int_polymer[dim1] = calloc(3, sizeof(int *)); double_polymer[dim1] = calloc(3, sizeof(double *)); } //---------------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------------- // observables OBSERVABLE normal_obs; normal_obs.maxee = 0.0; // maximal stretch of polymer OBSERVABLE intra_obs[100]; //------------------------------------------------------- // initialization of all the OBSERVABLE variables //------------------------------------------------------- normal_obs.err_ee2 = (double *) calloc(11, sizeof(double)); if(NULL == normal_obs.err_ee2) { fprintf(stderr, "Allocation of ee2 variable failed! \n"); return EXIT_FAILURE; } normal_obs.err_rgyr = (double *) calloc(11, sizeof(double)); if(NULL == normal_obs.err_rgyr) { fprintf(stderr, "Allocation of rgyr variable failed! \n"); return EXIT_FAILURE; } if (ARG_intra_potential>0) { for (int dim1=0; dim1<100; dim1++) { intra_obs[dim1].err_ee2 =(double *) calloc(11, sizeof(double)); intra_obs[dim1].err_rgyr =(double *) calloc(11, sizeof(double)); if(NULL == intra_obs[dim1].err_ee2 || NULL == intra_obs[dim1].err_rgyr) { fprintf(stderr, "Allocation of ee2 or rgyr variable (intramolecular) failed! \n"); return EXIT_FAILURE; } } } // initializes the observables for torsional analysis (optional) if (ARG_torsion==1) { normal_obs.err_pt = (double *) calloc(11, sizeof(double)); if(NULL == normal_obs.err_pt) { fprintf(stderr, "Allocation of torsion variable failed! \n"); return EXIT_FAILURE; } if (ARG_intra_potential>0) { for (int dim1=0; dim1<100; dim1++) { intra_obs[dim1].pt = 0.0; intra_obs[dim1].err_pt = (double *) calloc(11, sizeof(double)); if(NULL == intra_obs[dim1].err_pt) { fprintf(stderr, "Allocation of torsion variable (intramolecular) failed! \n"); return EXIT_FAILURE; } } } } // initializes the observables for loss of solven accessible surface area analysis (optional) if (ARG_sasa==1){ normal_obs.err_dsasa = (double *) calloc(11, sizeof(double)); if(NULL == normal_obs.err_dsasa) { fprintf(stderr, "Allocation of D-SASA variable failed! \n"); return EXIT_FAILURE; } if (ARG_intra_potential>0) { for (int dim1=0; dim1<100; dim1++) { intra_obs[dim1].dsasa = 0.0; intra_obs[dim1].err_dsasa = (double *) calloc(11, sizeof(double)); if(NULL == intra_obs[dim1].err_dsasa) { fprintf(stderr, "Allocation of D-SASA variable (intramolecular) failed! \n"); return EXIT_FAILURE; } } } } // this is needed for the pair correlation function double *pair_correlation_obs; if (ARG_pair_correlation==1) { pair_correlation_obs = (double*) calloc(2*ARG_numberofbeads, sizeof(double)); if(NULL == pair_correlation_obs) { fprintf(stderr, "Allocation of pair_correlation_obs failed! \n"); return EXIT_FAILURE; } normal_obs.pair_corr = (double *) calloc(2*ARG_numberofbeads, sizeof(double)); if(NULL == normal_obs.pair_corr) { fprintf(stderr, "Allocation of pair_corr failed! \n"); return EXIT_FAILURE; } if (ARG_intra_potential>0) { for (int dim1=0; dim1<100; dim1++) { intra_obs[dim1].pair_corr = (double *) calloc(2*ARG_numberofbeads, sizeof(double)); if(NULL == intra_obs[dim1].pair_corr) { fprintf(stderr, "Allocation of pair_corr (intramolecular) failed! \n"); return EXIT_FAILURE; } } } } //------------------------- // this will provide a measure for entropy loss calculation unsigned long *attempts_successes; double *log_attempts; log_attempts = (double*) calloc(11, sizeof(double)); // set the number of entries in this list, it depends on the typeofrun, but not the saw-type // last entry is the recast number of attempts which provides a measure for the entropy loss //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // calculate variables which depend on the typeofrun switch (ARG_typeofrun) { // normal SAWX case 10: case 20: case 30: attempts_successes = calloc(2, sizeof(unsigned long)); break; // fSAWX case 11: case 21: case 31: attempts_successes = calloc(5, sizeof(unsigned long)); numof_frags_bricks[0] = (ARG_numberofbeads-1)/ARG_flength; break; // bSAWX case 13: case 23: case 33: attempts_successes = calloc(3, sizeof(unsigned long)); numof_frags_bricks[3] = (ARG_numberofbeads-1)/ARG_blength; break; // fb_SAWX case 14: case 24: case 34: attempts_successes = calloc(5, sizeof(unsigned long)); numof_frags_bricks[0] = (ARG_numberofbeads-1)/ARG_flength; numof_frags_bricks[3] = ARG_flength/ARG_blength; numof_frags_bricks[4] = (ARG_numberofbeads-1-ARG_flength*numof_frags_bricks[3])/ARG_blength; break; default: break; } //---------------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------------- // intra molecular interactions // boltzman-factors, the intramolecular energy, the enrgy time the boltzmanfactor (entropy) double *intra_boltzman_factors; double *intra_highest_boltzmanfactor; double *intra_energy; double **intra_sum_of_boltzfactors; double **intra_sum_of_enrgyboltz; int *intra_interactions_hist; // double *intra_interactions_testhist; double intra_max_factor = 0.0; double intra_min_factor = 0.0; // binning the energies of the intra-factors double intra_binmin; double intra_binmax; double intra_binwidth; int **intra_energybin; // these will be the parameter of the intra molecular force double *intra_parameter1; double *intra_parameter2; if (ARG_intra_potential > 0){ switch (ARG_intra_potential) { // 1-10 potential well + torsional potential, given energy values case 1: intra_boltzman_factors = (double*) calloc(1, sizeof(double)); intra_highest_boltzmanfactor = (double*) calloc(1, sizeof(double)); intra_energy = (double*) calloc(1, sizeof(double)); intra_sum_of_boltzfactors = (double**) calloc(1, sizeof(double)); intra_sum_of_enrgyboltz = (double**) calloc(1, sizeof(double*)); intra_sum_of_boltzfactors[0] = (double*) calloc(10, sizeof(double)); intra_sum_of_enrgyboltz[0] = (double*) calloc(10, sizeof(double)); intra_parameter1 = (double*) malloc(1 * sizeof(double)); intra_parameter2 = (double*) malloc(1 * sizeof(double)); intra_interactions_hist = calloc(ARG_numberofbeads, sizeof(int)); // intra_interactions_testhist = calloc(100, sizeof(double)); intra_parameter1[0] = ARG_intra_parameter1[0]; // nearest neighbor potential intra_parameter2[0] = ARG_intra_parameter2[0]; // torsion potential intra_binmin = -100.0; intra_binmax = 100.0; intra_binwidth = 1.0; intra_energybin = (int**) calloc(1, sizeof(int *)); intra_energybin[0] = (int*) calloc(((intra_binmax-intra_binmin)/intra_binwidth), sizeof(int)); break; // 1-10 potential well + torsional potential, given energy value range! 10x10 case 2: intra_boltzman_factors = (double*) calloc(100, sizeof(double)); intra_highest_boltzmanfactor = (double*) calloc(100, sizeof(double)); intra_energy = (double*) calloc(100, sizeof(double)); intra_sum_of_boltzfactors = (double**) calloc(100, sizeof(double)); intra_sum_of_enrgyboltz = (double**) calloc(100, sizeof(double*)); for (int dim1=0; dim1<100; ++dim1) { intra_sum_of_boltzfactors[dim1] = (double*) calloc(10, sizeof(double)); intra_sum_of_enrgyboltz[dim1] = (double*) calloc(10, sizeof(double)); } intra_parameter1 = (double*) malloc(10 * sizeof(double)); intra_parameter2 = (double*) malloc(10 * sizeof(double)); intra_interactions_hist = calloc(ARG_numberofbeads, sizeof(int)); // intra_interactions_testhist = calloc(100, sizeof(double)); for (int dim1=0; dim1<10; dim1++) { intra_parameter1[dim1] = ARG_intra_parameter1[0]+ ARG_intra_parameter1[1]*(double)dim1; // nearest neighbor potential intra_parameter2[dim1] = ARG_intra_parameter2[0]+ ARG_intra_parameter2[1]*(double)dim1; // torsion potential } intra_binmin = -100.0; intra_binmax = 100.0; intra_binwidth = 1.0; intra_energybin = (int**) calloc(100, sizeof(int *)); for (int dim1=0; dim1<100; ++dim1){ intra_energybin[dim1] = (int*) calloc(((intra_binmax-intra_binmin)/intra_binwidth), sizeof(int)); } break; default: fprintf(stderr, "This intramolecular potential doesn't exist! \n"); break; } } //---------------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------------- /* start of chain generation*/ time[1] = time_of_day(); for (unsigned long frame=0; frame<ARG_numberofframes; frame++){ tenth = frame/tenth_frames; switch(ARG_typeofrun){ case 0: dcd_to_polymer(double_polymer, v, natoms, ×tep, dcd, frame, ARG_numberofbeads); break; case 1: tetra_rw(int_polymer, move, ARG_numberofbeads); break; case 2: tetra_fww(int_polymer, move, sawmoves, ARG_numberofbeads); break; case 10: tetra_saw1(int_polymer, move, sawmoves, ARG_numberofbeads, attempts_successes); break; case 11: tetra_fsaw1(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_flength, attempts_successes); break; case 13: tetra_bsaw1(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, attempts_successes); break; // case 14: // here is something awfully wrong, can't find the mistake at the moment! // tetra_fb_saw1(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, ARG_flength, attempts_successes); // break; case 20: tetra_saw2(int_polymer, move, sawmoves, ARG_numberofbeads, attempts_successes); break; case 21: tetra_fsaw2(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_flength, attempts_successes); break; case 23: tetra_bsaw2(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, attempts_successes); break; case 24: tetra_fb_saw2(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, ARG_flength, attempts_successes); break; case 30: tetra_saw3(int_polymer, move, sawmoves, ARG_numberofbeads, attempts_successes); break; case 31: tetra_fsaw3(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_flength, attempts_successes); break; case 33: tetra_bsaw3(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, attempts_successes); break; case 34: tetra_fb_saw3(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, ARG_flength, attempts_successes); break; default: log_out(output_file, "ERROR: ARG_typeofrun = %d isn't recognized by the main part of the programm!\n", ARG_typeofrun); usage_error(); } // end of chain generaiton // copies the lattice polymer into an array with doubles so that the chosen bond length can be used. if (ARG_typeofrun>0) { recast(double_polymer, int_polymer, ARG_numberofbeads, &recast_factor); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // get most important observables // end-to-end distance^2 normal_obs.ee2 = double_distance2(double_polymer[last_atom], double_polymer[0]); normal_obs.err_ee2[tenth] += normal_obs.ee2; // radius of gyration normal_obs.rgyr = radius_of_gyration(double_polymer, ARG_numberofbeads); normal_obs.err_rgyr[tenth] += normal_obs.rgyr; // pT if (ARG_torsion==1){ normal_obs.pt = get_nT(double_polymer, number_of_torsions); normal_obs.err_pt[tenth] += normal_obs.pt; } if (ARG_sasa==1){ //observables[4] = get_asa(double_polymer, ARG_numberofbeads, (sqrt(16.0/3.0)*bondlength/2.0)); normal_obs.dsasa = delta_asa(double_polymer, ARG_numberofbeads, bondlength); normal_obs.err_dsasa[tenth] += normal_obs.dsasa; } if (ARG_pair_correlation==1) { if (false==pair_correlation_fct(pair_correlation_obs, double_polymer, ARG_numberofbeads)){ return EXIT_FAILURE; } for (int pairs=0; pairs<(2*ARG_numberofbeads); pairs++) { normal_obs.pair_corr[pairs] += pair_correlation_obs[pairs]; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // calculate boltzman factors if intramolecular forces are switched on switch (ARG_intra_potential) { // torsion + square well potential case 1: intrapot_torsion_well(intra_boltzman_factors, intra_energy, intra_interactions_hist, intra_highest_boltzmanfactor, intra_parameter1, intra_parameter2, normal_obs.pt, number_of_torsions, int_polymer, ARG_numberofbeads); intra_sum_of_enrgyboltz[0][tenth] += (intra_boltzman_factors[0]*intra_energy[0]); intra_sum_of_boltzfactors[0][tenth] += intra_boltzman_factors[0]; intra_obs[0].err_ee2[tenth] += normal_obs.ee2 * intra_boltzman_factors[0]; intra_obs[0].err_rgyr[tenth] += normal_obs.rgyr * intra_boltzman_factors[0]; intra_obs[0].err_pt[tenth] += normal_obs.pt * intra_boltzman_factors[0]; intra_binenergy(intra_energy[0], intra_binmin, intra_binwidth, intra_energybin[0]); // pair correlation function if (ARG_pair_correlation==1){ for (int pairs=0; pairs<(2*ARG_numberofbeads); pairs++) { intra_obs[0].pair_corr[pairs] += (pair_correlation_obs[pairs]*intra_boltzman_factors[0]); } } break; // torsion + square well potential, range of energy values case 2: intrapot_torsion_well_scan(intra_boltzman_factors, intra_energy, intra_interactions_hist, intra_highest_boltzmanfactor, intra_parameter1, intra_parameter2, normal_obs.pt, number_of_torsions, int_polymer, ARG_numberofbeads); //intrapot_torsion_well_test(intra_boltzman_factors, intra_energy, intra_interactions_hist, intra_interactions_testhist,intra_highest_boltzmanfactor, intra_parameter1, intra_parameter2, normal_obs.pt, number_of_torsions, int_polymer, ARG_numberofbeads); for (int dim1=0; dim1<100; ++dim1) { intra_sum_of_enrgyboltz[dim1][tenth] += (intra_boltzman_factors[dim1]*intra_energy[dim1]); intra_sum_of_boltzfactors[dim1][tenth] += intra_boltzman_factors[dim1]; intra_obs[dim1].err_ee2[tenth] += normal_obs.ee2 * intra_boltzman_factors[dim1]; intra_obs[dim1].err_rgyr[tenth] += normal_obs.rgyr * intra_boltzman_factors[dim1]; intra_obs[dim1].err_pt[tenth] += normal_obs.pt * intra_boltzman_factors[dim1]; intra_binenergy(intra_energy[dim1], intra_binmin, intra_binwidth, intra_energybin[dim1]); // pair correlation function if (ARG_pair_correlation==1){ for (int pairs=0; pairs<(2*ARG_numberofbeads); pairs++) { intra_obs[dim1].pair_corr[pairs] += (pair_correlation_obs[pairs]*intra_boltzman_factors[dim1]); } } } break; default: break; }// boltzman factors and energies have been determined // end of anything related to intramolecular potentials //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- // everything has been calculated, now is the opportunity to look at convergence if ((frame+1)%permill_frames==0) { // convergence of variables with equal weights convergence(&normal_obs, (double)number_of_torsions, (frame+1), conv_obs_file); switch (ARG_intra_potential) { case 1: weighted_convergence(intra_obs, 1,intra_sum_of_boltzfactors, (double)number_of_torsions, (frame+1), conv_intraobs_file); weights_growth(intra_sum_of_boltzfactors, 1, (frame+1), convergence_intraweights); break; // convergence of weighted ensemble case 2: weighted_convergence(intra_obs, 100, intra_sum_of_boltzfactors, (double)number_of_torsions, (frame+1), conv_intraobs_file); weights_growth(intra_sum_of_boltzfactors, 100, (frame+1), convergence_intraweights); break; default: break; } if ((frame+1)%percent_frames==0) { cent = (frame+1)/percent_frames; log_out(output_file, "Finished %i%%\t...remaining time: %f seconds \n", (cent), ((time_of_day()-time[1])*(100-cent)/(cent))); if ((frame+1)%tenth_frames==0) { // every bin after the first will also include the attempts in the previous bin! log_attempts[tenth] = recalc_attempts(attempts_successes, numof_frags_bricks, numberofbricks, ARG_typeofrun); } } } } // end of loop over number of frames //---------------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------------- /* Post-Process */ time[2] = time_of_day(); // Maybe there should be a function, which returns means and errors; it calls these subroutines .... log_attempts[10] = recalc_attempts(attempts_successes, numof_frags_bricks, numberofbricks, ARG_typeofrun); for (int dim1=9; dim1>0; --dim1) { log_attempts[dim1] = log( exp(log_attempts[dim1]) - exp(log_attempts[dim1-1]) ); } // get means and errors normal_obs.ee2 = sqrt( average(normal_obs.err_ee2, ARG_numberofframes) ); normal_obs.err_ee2[10] = error_sq_ten(normal_obs.ee2, normal_obs.err_ee2, ARG_numberofframes); normal_obs.rgyr = sqrt( average(normal_obs.err_rgyr, ARG_numberofframes) ); normal_obs.err_rgyr[10] = error_sq_ten(normal_obs.rgyr, normal_obs.err_rgyr, ARG_numberofframes); normal_obs.S = (log((double)ARG_numberofframes) - log_attempts[10]); if (ARG_torsion==1) { normal_obs.pt = average(normal_obs.err_pt, ARG_numberofframes); normal_obs.err_pt[10] = error_ten(normal_obs.pt, normal_obs.err_pt, ARG_numberofframes); } if (ARG_sasa==1) { normal_obs.dsasa = average(normal_obs.err_dsasa, ARG_numberofframes); normal_obs.err_dsasa[10] = error_ten(normal_obs.dsasa, normal_obs.err_dsasa, ARG_numberofframes); } //---------------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------------- /* Output */ time[3] = time_of_day(); // print the output to screen and to the output_file log_out(output_file, "\n-----------------------------------------------------------------------------------\n"); log_out(output_file, "FINAL OUTPUT\n"); log_out(output_file, "\nEntropic Considerations:\n"); log_out(output_file, "Attempts to Compute the Ensemble: %e \n", exp(log_attempts[10])); log_out(output_file, "\tDelta S / k_B (FWW -> SAWn): %f \n", normal_obs.S); log_out(output_file, "\nChosen Observables:\n"); log_out(output_file, "Flory Radius: %f +- %f \n", normal_obs.ee2, normal_obs.err_ee2[10]); log_out(output_file, "Radius of Gyration: %f +- %f \n", normal_obs.rgyr, normal_obs.err_rgyr[10]); if (ARG_torsion==1) { log_out(output_file, "Probability of trans = %f +- %f\n", (normal_obs.pt/(double)number_of_torsions), (normal_obs.err_pt[10]/(double)number_of_torsions)); } if (ARG_sasa==1) { log_out(output_file, "Delta SASA = %f +- %f\n", normal_obs.dsasa, normal_obs.err_dsasa[10]); } if (ARG_pair_correlation==1) { log_out(output_file, "The pair-correlation function was written to 'pair_correlation_function.dat'.\n"); } log_out(output_file, "\nThis ouput is also written to 'output_file.dat'.\n"); log_out(output_file, "The convergence was written to 'convergence_obs.dat'.\n"); if (ARG_intra_potential>0) { log_out(output_file, "\nThe Boltzmann-weighted observables can be found in 'intramolecular_obs.dat'.\n"); log_out(output_file, "The Boltzmann-weighted convergence was written to 'intramolecular_convergence_obs.dat'.\n"); log_out(output_file, "A histogram of the Boltzmann-factors was written to 'intramolecular_factors_hist.dat'.\n"); log_out(output_file, "The sum of the Boltzmann-factors was written to 'intramolecular_convergence_Z.dat'.\n"); log_out(output_file, "A histogram of the intramolecular contacts was written to 'intramolecular_interactions_hist.dat'.\n"); } //---------------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------------- /* Output to file */ // pair correlation function if (ARG_pair_correlation==1){ if (ARG_intra_potential==0) { fprintf(pair_correl_file,"# r_0-r_1 pair_correlation \n"); for (int dim1=0; dim1<(2*ARG_numberofbeads); dim1++){ fprintf(pair_correl_file, "%i %e \n", dim1, (normal_obs.pair_corr[dim1]/(double)ARG_numberofframes)); } } else if (ARG_intra_potential==2){ fprintf(pair_correl_file,"# r_0-r_1 pair_correlation(unweigthed) pair_correlation(weigthed)\n"); for (int dim1=0; dim1<(2*ARG_numberofbeads); dim1++){ fprintf(pair_correl_file, "%i %e %e \n", dim1, (normal_obs.pair_corr[dim1]/(double)ARG_numberofframes), (intra_obs[46].pair_corr[dim1]/average(intra_sum_of_boltzfactors[46], 1))); } } } switch (ARG_intra_potential) { case 1: // prints the weighted observables to file with error estimate fprintf(intra_pot_file, "### 1-9 well, torsion eps, Rf, Rf_err, Rg, Rg_err, pT, pT_err, DS, DS_err, <exp(-E/kT)>/exp(-Emax/kT) \n" ); intra_obs[0].ee2 = sqrt(weighted_average(intra_obs[0].err_ee2, intra_sum_of_boltzfactors[0])); intra_obs[0].err_ee2[10] = weighted_error_sq_ten(intra_obs[0].ee2, intra_obs[0].err_ee2, intra_sum_of_boltzfactors[0]); intra_obs[0].rgyr = sqrt(weighted_average(intra_obs[0].err_rgyr, intra_sum_of_boltzfactors[0])); intra_obs[0].err_rgyr[10] = weighted_error_sq_ten(intra_obs[0].rgyr, intra_obs[0].err_rgyr, intra_sum_of_boltzfactors[0]); intra_obs[0].pt = weighted_average(intra_obs[0].err_pt, intra_sum_of_boltzfactors[0]); intra_obs[0].err_pt[10] = weighted_error_ten(intra_obs[0].pt, intra_obs[0].err_pt, intra_sum_of_boltzfactors[0]); intra_obs[0].S = intra_entropy(intra_sum_of_boltzfactors[0], intra_sum_of_enrgyboltz[0], log_attempts[10]); intra_obs[0].err_S = intra_entropy_error_ten(intra_obs[0].S, intra_sum_of_boltzfactors[0], intra_sum_of_enrgyboltz[0], log_attempts); fprintf(intra_pot_file, "%f %f %e %e %e %e %e %e %e %e %e \n", intra_parameter1[0], intra_parameter2[0], intra_obs[0].ee2, intra_obs[0].err_ee2[10], intra_obs[0].rgyr, intra_obs[0].err_rgyr[10], (intra_obs[0].pt/(double)number_of_torsions), (intra_obs[0].err_pt[10]/(double)number_of_torsions), intra_obs[0].S, intra_obs[0].err_S, intra_loss_of_conf(intra_sum_of_boltzfactors[0], intra_highest_boltzmanfactor[0], ARG_numberofframes)); // histogram over 1-9 interacitons fprintf(intra_interactions_file, "# number-of-nn-interactions, occurence \n"); for (int dim1=0; dim1<ARG_numberofbeads; ++dim1) { fprintf(intra_interactions_file, "%i %i \n", dim1, intra_interactions_hist[dim1]); } // test histogram // fprintf(intra_interactions_testfile, "# sperating-bonds 0_contacts 1_contacts 2_contacts\n"); // for (int dim1=0; dim1<98; dim1+=3) { // fprintf(intra_interactions_testfile, "%i %e %e %e \n", (dim1/3+4), intra_interactions_testhist[dim1]/average(intra_sum_of_boltzfactors[46], 1), intra_interactions_testhist[dim1+1]/average(intra_sum_of_boltzfactors[46], 1), intra_interactions_testhist[dim1+2]/average(intra_sum_of_boltzfactors[46], 1)); // } // histogram of intra energies fprintf(intra_boltzman_factors_hist, "# energy, bincount-for-these-parameters"); for (int dim1=0; dim1<((intra_binmax-intra_binmin)/intra_binwidth); ++dim1) { fprintf(intra_boltzman_factors_hist, "%f %i \n", (intra_binmin+(double)dim1*intra_binwidth), intra_energybin[0][dim1]); } break; case 2: // prints the weighted observables to file with error estimate fprintf(intra_pot_file, "### 1-9 well, torsion eps, Rf, Rf_err, Rg, Rg_err, pT, pT_err, DS, DS_err, <exp(-E/kT)>/exp(-Emax/kT) \n" ); for (int dim1=0; dim1<10; dim1++) { for (int dim2=0; dim2<10; dim2++) { counter = dim1*10 + dim2; intra_obs[counter].ee2 = sqrt(weighted_average(intra_obs[counter].err_ee2, intra_sum_of_boltzfactors[counter])); intra_obs[counter].err_ee2[10] = weighted_error_sq_ten(intra_obs[counter].ee2, intra_obs[counter].err_ee2, intra_sum_of_boltzfactors[counter]); intra_obs[counter].rgyr = sqrt(weighted_average(intra_obs[counter].err_rgyr, intra_sum_of_boltzfactors[counter])); intra_obs[counter].err_rgyr[10] = weighted_error_sq_ten(intra_obs[counter].rgyr, intra_obs[counter].err_rgyr, intra_sum_of_boltzfactors[counter]); intra_obs[counter].pt = weighted_average(intra_obs[counter].err_pt, intra_sum_of_boltzfactors[counter]); intra_obs[counter].err_pt[10] = weighted_error_ten(intra_obs[counter].pt, intra_obs[counter].err_pt, intra_sum_of_boltzfactors[counter]); intra_obs[counter].S = intra_entropy(intra_sum_of_boltzfactors[counter], intra_sum_of_enrgyboltz[counter], log_attempts[10]); intra_obs[counter].err_S = intra_entropy_error_ten(intra_obs[counter].S, intra_sum_of_boltzfactors[counter], intra_sum_of_enrgyboltz[counter], log_attempts); fprintf(intra_pot_file, "%f %f %e %e %e %e %e %e %e %e %e \n", intra_parameter1[dim1], intra_parameter2[dim2], intra_obs[counter].ee2, intra_obs[counter].err_ee2[10], intra_obs[counter].rgyr, intra_obs[counter].err_rgyr[10], (intra_obs[counter].pt/(double)number_of_torsions), (intra_obs[counter].err_pt[10]/(double)number_of_torsions), intra_obs[counter].S, intra_obs[counter].err_S, intra_loss_of_conf(intra_sum_of_boltzfactors[counter], intra_highest_boltzmanfactor[counter], ARG_numberofframes)); } } // histogram over 1-9 interacitons fprintf(intra_interactions_file, "# number-of-nn-interactions, occurence \n"); for (int dim1=0; dim1<ARG_numberofbeads; ++dim1) { fprintf(intra_interactions_file, "%i %i \n", dim1, intra_interactions_hist[dim1]); } // test histogram // fprintf(intra_interactions_testfile, "# sperating-bonds 0_contacts 1_contacts 2_contacts\n"); // for (int dim1=0; dim1<98; dim1+=3) { // fprintf(intra_interactions_testfile, "%i %e %e %e \n", (dim1/3+4), intra_interactions_testhist[dim1]/average(intra_sum_of_boltzfactors[46], 1), intra_interactions_testhist[dim1+1]/average(intra_sum_of_boltzfactors[46], 1), intra_interactions_testhist[dim1+2]/average(intra_sum_of_boltzfactors[46], 1)); // } // histogram of intra energies fprintf(intra_boltzman_factors_hist, "# energy, bincount-for-these-parameters"); for (int dim1=0; dim1<((intra_binmax-intra_binmin)/intra_binwidth); ++dim1) { fprintf(intra_boltzman_factors_hist, "%f ", (intra_binmin+(double)dim1*intra_binwidth)); for (int dim2=0; dim2<100; ++dim2) { fprintf(intra_boltzman_factors_hist, "%i ", intra_energybin[dim2][dim1]); } fprintf(intra_boltzman_factors_hist, "\n"); } break; default: break; } log_out(output_file, "\nComputation of Chains:\t%f seconds \nTotal Runtime:\t\t%f seconds \n\n", (time[2]-time[1]), (time[3]-time[0])); log_out(output_file, "End of Programm!\n-----------------------------------------------------------------------------------\n"); // make sure everything gets printed fflush(stdout); //---------------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------------- // close every remaining file and free remaining pointers! // cleaning up ;-) //close all files if (ARG_typeofrun==0){// dcd-file close_file_read(v); } fclose(conv_obs_file); fclose(pair_correl_file); fclose(intra_pot_file); fclose(intra_boltzman_factors_hist); fclose(convergence_intraweights); fclose(intra_interactions_file); fclose(conv_intraobs_file); // very last file to close fclose(output_file); //----------------------------- // free pointers // free general variables free(normal_obs.err_ee2); free(normal_obs.err_rgyr); // torsion angles if (ARG_torsion==1) { free(normal_obs.err_pt); if (ARG_intra_potential>0) { for (int dim1=0; dim1<100; dim1++) { free(intra_obs[dim1].err_pt); } } } // D-SASA if (ARG_sasa==1) { free(normal_obs.err_dsasa); if (ARG_intra_potential>0) { for (int dim1=0; dim1<100; dim1++) { free(intra_obs[dim1].err_dsasa); } } } // pair correlation function if (ARG_pair_correlation==1) { free(pair_correlation_obs); free(normal_obs.pair_corr); if (ARG_intra_potential>0) { for (int dim1=0; dim1<100; dim1++) { free(intra_obs[dim1].pair_corr); } } } free(attempts_successes); // free arrays which held polymer coordinates for (int dim1=0; dim1<ARG_numberofbeads;dim1++){ free(int_polymer[dim1]); free(double_polymer[dim1]); } free(int_polymer); free(double_polymer); // free building blocks if (ARG_typeofrun==13 || ARG_typeofrun==14 || ARG_typeofrun==23 || ARG_typeofrun==24 || ARG_typeofrun==33 || ARG_typeofrun==34){ for (int dim1=0; dim1<numberofbricks; ++dim1) { for (int dim2=0; dim2<ARG_blength; ++dim2) { free(building_bricks[dim1][dim2]); } free(building_bricks[dim1]); } free(building_bricks); } // free potential variables if (ARG_intra_potential > 0){ switch (ARG_intra_potential) { case 1: free(intra_sum_of_boltzfactors[0]); break; case 2: for (int dim1=0; dim1<100; dim1++){ free(intra_sum_of_boltzfactors[dim1]); } break; default: break; } free(intra_energy); free(intra_boltzman_factors); free(intra_sum_of_boltzfactors); free(intra_sum_of_enrgyboltz); free(intra_interactions_hist); // free(intra_interactions_testhist); free(intra_parameter1); free(intra_parameter2); } // end of programm return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { /* Settings */ int use_smoothing = 0; int use_flow = 1; int use_multiple_predictions = 0; int use_variance = 0; if (argc < 2) { printf("Please specify: test, train, or preds and data set size"); return -1; } int SIZE_SIFT = atoi(argv[2]); /* Create arrays for measurements */ struct measurement measurements[SIZE_SIFT]; struct measurement measurements_2[SIZE_SIFT]; /* If multiply regressors are used */ struct measurement measurements_3[SIZE_SIFT]; /* If multiply regressors are used */ struct measurement opticalflow[SIZE_SIFT]; char *filename_out; /* For test set */ if (strcmp(argv[1], "test") == 0) { filename_out = "sift_filtered_test_2.csv"; //char filename_in[] = "/home/pold/Documents/Internship/datasets/board_test_pos.csv"; char filename_in[] = "/home/pold/Documents/Internship/datasets/board_test_2_pos.csv"; read_measurements_from_csv(measurements, filename_in, SIZE_SIFT); } /* For training set */ else if (strcmp(argv[1], "train") == 0) { filename_out = "sift_filtered_train_vel.csv"; char filename_in[] = "/home/pold/Documents/Internship/datasets/board_train_pos.csv"; read_measurements_from_csv(measurements, filename_in, SIZE_SIFT); } /* For predictions */ else if (strcmp(argv[1], "preds") == 0) { filename_out = "predictions_filtered_lasso.csv"; char filename_in[] = "/home/pold/Documents/treXton/predictions_cross.csv"; char filename_in_2[] = "/home/pold/Documents/treXton/predictions.csv"; char filename_optical_flow[] = "/home/pold/Documents/trexton_pprz/edgeflow_diff.csv"; //char filename_in_3[] = "/home/pold/Documents/Internship/treXton/predictions_3.csv"; read_predictions_from_csv(measurements, filename_in, SIZE_SIFT, 1); read_predictions_from_csv(measurements_2, filename_in_2, SIZE_SIFT, 0); read_predictions_from_csv(opticalflow, filename_optical_flow, SIZE_SIFT, 0); /* read_predictions_from_csv(measurements_3, filename_in_3, SIZE_SIFT); */ } else { printf("No argument specified"); return -1; } /* Create and initialize particles */ struct particle particles[N]; init_particles(particles); struct particle particles_backward[N]; init_particles(particles_backward); /* Run particle filter for every measurement */ int i = 0, j = 0, k; FILE *fp = fopen(filename_out, "w"); fprintf(fp, "x,y\n"); /* Tables for dynamic programming */ struct particle ps_forward[SIZE_SIFT]; struct particle ps_backward[SIZE_SIFT]; struct particle uncertainties[SIZE_SIFT]; /* Fill in dynamic programming table */ for (i = 0; i < SIZE_SIFT; i++) { printf(" iteration: %d\n", i); fflush(stdout); /* Use predictions form multiple regressors */ if (use_multiple_predictions) { particle_filter_multiple(particles, &measurements[i], &measurements_2[i], use_variance); } else { particle_filter(particles, &measurements[i], &opticalflow[i], use_variance, use_flow); } /* Forward-backward smoothing */ if (use_smoothing) { k = SIZE_SIFT - i; particle_filter(particles_backward, &measurements[k], &opticalflow[i], use_variance, use_flow); struct particle p_backward = weighted_average(particles_backward, N); ps_backward[k] = p_backward; } struct particle p_forward = weighted_average(particles, N); uncertainties[i] = calc_uncertainty(particles, p_forward, N); printf("Uncertainty: x: %f y: %f", uncertainties[i].x, uncertainties[i].y); ps_forward[i] = p_forward; } for (i = 0; i < SIZE_SIFT; i++) { struct particle p; printf("measurement %f %f\n", measurements[i].x, measurements[i].y); if (use_smoothing) p = weight_forward_backward(ps_forward[i], ps_backward[i], i, (SIZE_SIFT - i)); else p = ps_forward[i]; printf("x: %f y: %f", p.x, p.y); fprintf(fp, "%f,%f\n" , p.x, p.y); } fclose(fp); return 0; }
void deblur_image(int image_num, int n, IplImage *result, IplImage *result_luck) { cvSetZero(result); cvSetZero(result_luck); IplImage *trans[MAX_IMAGE];//转换后的结果? IplImage *trans_luck[MAX_IMAGE]; IplImage *blur[MAX_IMAGE]; for (int i = 0; i < image_num; ++i) { trans[i] = cvCreateImage(image_size, IPL_DEPTH_8U, 3); cvWarpPerspective(images[i], trans[i], hom[i][n], CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, cvScalarAll(0)); //对图像进行透视变换得到trans后的图像 trans_luck[i] = cvCreateImage(image_size, IPL_DEPTH_32F, 4); cvWarpPerspective(images_luck[i], trans_luck[i], hom[i][n], CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, cvScalarAll(0)); //images_luck 是每一帧各个点的luckiness指数 blur[i] = cvCreateImage(image_size, IPL_DEPTH_8U, 3); blur_function(trans[i], blur[i], hom[n-1][n], hom[n][n+1]); } for (int i = 0; i < image_num; ++i) { char wname[16]; sprintf(wname, "Homography%d", i); cvNamedWindow(wname, CV_WINDOW_AUTOSIZE); cvMoveWindow(wname, i*50, i*50); cvShowImage(wname, trans[i]); sprintf(wname, "Blurred%d", i); cvNamedWindow(wname, CV_WINDOW_AUTOSIZE); cvMoveWindow(wname, i*50+100, i*50); cvShowImage(wname, blur[i]); } cvWaitKey(0); cvDestroyAllWindows(); int grid_r = (image_size.height-PATCH_SIZE/2-1) / (PATCH_SIZE/2); int grid_c = (image_size.width-PATCH_SIZE/2-1) / (PATCH_SIZE/2); if (grid_r > 0 && grid_c > 0) { CvMat *patch = cvCreateMat(grid_r, grid_c, CV_64FC4); for (int i = 0; i < grid_r; ++i) { int y = (i+1)*(PATCH_SIZE/2); int t1 = clock(); for (int j = 0; j < grid_c; ++j) { CvScalar res; int x = (j+1)*(PATCH_SIZE/2); if (deblur_patch(blur, trans_luck, image_num, n, x, y, &res) != 0) { printf("deblur_patch: %d:%d,%d failed.\n", n, x, y); res.val[0] = n; res.val[1] = x; res.val[2] = y; res.val[3] = 0; //copy_pixel(result, x, y, images[n], x, y); } /* res.val[0] = 2; res.val[1] = x; res.val[2] = y; res.val[3] = 100000;*/ res.val[3] = exp(-res.val[3]/(2*SIGMA_W*SIGMA_W)); CV_MAT_ELEM(*patch, CvScalar, i, j) = res; } int t2 = clock(); printf("y:%d/%d %d ms\n", y, image_size.height, (t2-t1)*1000/CLOCKS_PER_SEC); } cvNamedWindow("origin", CV_WINDOW_AUTOSIZE); cvShowImage("origin", images[n]); cvNamedWindow("result", CV_WINDOW_AUTOSIZE); // 中心部分 for (int i = 1; i < grid_r; ++i) { int miny = i*(PATCH_SIZE/2); for (int j = 1; j < grid_c; ++j) { CvScalar pres1 = CV_MAT_ELEM(*patch, CvScalar, i-1, j-1); CvScalar pres2 = CV_MAT_ELEM(*patch, CvScalar, i-1, j); CvScalar pres3 = CV_MAT_ELEM(*patch, CvScalar, i, j-1); CvScalar pres4 = CV_MAT_ELEM(*patch, CvScalar, i, j); int minx = j*(PATCH_SIZE/2); for (int y = 0; y < PATCH_SIZE/2; ++y) for (int x = 0; x < PATCH_SIZE/2; ++x) { CvScalar v[4]; v[0] = cvGet2D(trans[(int)pres1.val[0]], (int)pres1.val[2]+y, (int)pres1.val[1]+x); v[1] = cvGet2D(trans[(int)pres2.val[0]], (int)pres2.val[2]+y, (int)pres2.val[1]+x-PATCH_SIZE/2); v[2] = cvGet2D(trans[(int)pres3.val[0]], (int)pres3.val[2]+y-PATCH_SIZE/2, (int)pres3.val[1]+x); v[3] = cvGet2D(trans[(int)pres4.val[0]], (int)pres4.val[2]+y-PATCH_SIZE/2, (int)pres4.val[1]+x-PATCH_SIZE/2); double w[4] = {pres1.val[3], pres2.val[3], pres3.val[3], pres4.val[3]}; CvScalar pv = weighted_average(v, w, 4); cvSet2D(result, y+miny, x+minx, pv); /* printf("p %d %d\n", y+miny, x+minx); for (int a = 0; a < 4; ++a) { printf("v%d: %f %f %f w %g\n", a, v[a].val[0], v[a].val[1], v[a].val[2], w[a]); } printf("pv: %f %f %f\n", pv.val[0], pv.val[1], pv.val[2]); */ } } cvShowImage("result", result); cvWaitKey(20); } // 四周特殊情况 for (int y = 0; y < PATCH_SIZE/2; ++y) for (int x = 0; x < PATCH_SIZE/2; ++x) { CvScalar pres = CV_MAT_ELEM(*patch, CvScalar, 0, 0); CvScalar pv = cvGet2D(trans[(int)pres.val[0]], (int)pres.val[2]+y-PATCH_SIZE/2, (int)pres.val[1]+x-PATCH_SIZE/2); cvSet2D(result, y, x, pv); pres = CV_MAT_ELEM(*patch, CvScalar, 0, grid_c-1); pv = cvGet2D(trans[(int)pres.val[0]], (int)pres.val[2]+y-PATCH_SIZE/2, (int)pres.val[1]+x); cvSet2D(result, y, grid_c*(PATCH_SIZE/2)+x, pv); pres = CV_MAT_ELEM(*patch, CvScalar, grid_r-1, 0); pv = cvGet2D(trans[(int)pres.val[0]], (int)pres.val[2]+y, (int)pres.val[1]+x-PATCH_SIZE/2); cvSet2D(result, grid_r*(PATCH_SIZE/2)+y, x, pv); pres = CV_MAT_ELEM(*patch, CvScalar, grid_r-1, grid_c-1); pv = cvGet2D(trans[(int)pres.val[0]], (int)pres.val[2]+y, (int)pres.val[1]+x); cvSet2D(result, grid_r*(PATCH_SIZE/2)+y, grid_c*(PATCH_SIZE/2)+x, pv); } for (int j = 1; j < grid_c; ++j) { CvScalar pres1 = CV_MAT_ELEM(*patch, CvScalar, 0, j-1); CvScalar pres2 = CV_MAT_ELEM(*patch, CvScalar, 0, j); CvScalar pres3 = CV_MAT_ELEM(*patch, CvScalar, grid_r-1, j-1); CvScalar pres4 = CV_MAT_ELEM(*patch, CvScalar, grid_r-1, j); int minx = j*(PATCH_SIZE/2); for (int y = 0; y < PATCH_SIZE/2; ++y) for (int x = 0; x < PATCH_SIZE/2; ++x) { CvScalar v[2]; v[0] = cvGet2D(trans[(int)pres1.val[0]], (int)pres1.val[2]+y-PATCH_SIZE/2, (int)pres1.val[1]+x); v[1] = cvGet2D(trans[(int)pres2.val[0]], (int)pres2.val[2]+y-PATCH_SIZE/2, (int)pres2.val[1]+x-PATCH_SIZE/2); double w[2] = {pres1.val[3], pres2.val[3]}; CvScalar pv = weighted_average(v, w, 2); cvSet2D(result, y, minx+x, pv); v[0] = cvGet2D(trans[(int)pres3.val[0]], (int)pres3.val[2]+y, (int)pres3.val[1]+x); v[1] = cvGet2D(trans[(int)pres4.val[0]], (int)pres4.val[2]+y, (int)pres4.val[1]+x-PATCH_SIZE/2); w[0] = pres3.val[3]; w[0] = pres4.val[3]; pv = weighted_average(v, w, 2); cvSet2D(result, grid_r*(PATCH_SIZE/2)+y, minx+x, pv); } } for (int i = 1; i < grid_r; ++i) { CvScalar pres1 = CV_MAT_ELEM(*patch, CvScalar, i-1, 0); CvScalar pres2 = CV_MAT_ELEM(*patch, CvScalar, i, 0); CvScalar pres3 = CV_MAT_ELEM(*patch, CvScalar, i-1, grid_c-1); CvScalar pres4 = CV_MAT_ELEM(*patch, CvScalar, i, grid_c-1); int miny = i*(PATCH_SIZE/2); for (int y = 0; y < PATCH_SIZE/2; ++y) for (int x = 0; x < PATCH_SIZE/2; ++x) { CvScalar v[2]; v[0] = cvGet2D(trans[(int)pres1.val[0]], (int)pres1.val[2]+y, (int)pres1.val[1]+x-PATCH_SIZE/2); v[1] = cvGet2D(trans[(int)pres2.val[0]], (int)pres2.val[2]+y-PATCH_SIZE/2, (int)pres2.val[1]+x-PATCH_SIZE/2); double w[2] = {pres1.val[3], pres2.val[3]}; CvScalar pv = weighted_average(v, w, 2); cvSet2D(result, miny+y, x, pv); v[0] = cvGet2D(trans[(int)pres3.val[0]], (int)pres3.val[2]+y, (int)pres3.val[1]+x); v[1] = cvGet2D(trans[(int)pres4.val[0]], (int)pres4.val[2]+y-PATCH_SIZE/2, (int)pres4.val[1]+x); w[0] = pres3.val[3]; w[0] = pres4.val[3]; pv = weighted_average(v, w, 2); cvSet2D(result, miny+y, grid_c*(PATCH_SIZE/2)+x, pv); } } cvShowImage("result", result); /* IplImage *res_diff = cvCreateImage(image_size, IPL_DEPTH_8U, 3); cvAbsDiff(result, images[n], res_diff); cvNamedWindow("diff", CV_WINDOW_AUTOSIZE); cvShowImage("diff", res_diff);*/ char name[16]; sprintf(name, "result%d.png", n); cvSaveImage(name, result, NULL); sprintf(name, "origin%d.png", n); cvSaveImage(name, images[n], NULL); cvReleaseMat(&patch); } for (int i = 0; i < image_num; ++i) { cvReleaseImage(&trans[i]); cvReleaseImage(&trans_luck[i]); cvReleaseImage(&blur[i]); } }
void loop_ctr(s4 &game_state) { ISceneNode* empty_node = irrlicht->smgr->addEmptySceneNode(); empty_node->setPosition(vector3df(0,0,0)); ICameraSceneNode* camera = irrlicht->smgr->addCameraSceneNode(); camera->setPosition({0,-250,-100}); camera->setUpVector({0,0,-1}); camera->setTarget({0,0,0}); camera->setParent(empty_node); camera->setFOV(70); irrlicht->device->getCursorControl()->setVisible(false); irrlicht->smgr->setAmbientLight(SColorf(1,1,1,1)); irrlicht->hud = irrlicht->smgr->createNewSceneManager(false); ICameraSceneNode* hud_camera = irrlicht->hud->addCameraSceneNode(); matrix4 ortho; ortho.buildProjectionMatrixOrthoLH( irrlicht->driver->getScreenSize().Width/ortho_scale, irrlicht->driver->getScreenSize().Height/ortho_scale,-1.0,1000.0); hud_camera->setProjectionMatrix(ortho); hud_camera->setPosition({0,0,-100}); hud_camera->setTarget({0,0,0}); // temp objects ---------------------------------- blist cmpnt_list, joint_list, tree_list; b_set(cmpnt_list,memory,sizeof(Component)); b_set(joint_list,memory,sizeof(Joint)); b_set(tree_list,memory,sizeof(CTree)); irr::core::map<ISceneNode*,Component*> node_cmpnt_map; ISceneNode* ctr_parent = irrlicht->smgr->addEmptySceneNode(); IMesh* cube_mesh = irrlicht->smgr->getGeometryCreator()->createCubeMesh(); auto add_object_to_world = [&] (vec3 pos, vec3 scale, s4 a, s4 r, s4 g, s4 b) -> Component* { const f4 floor_position = 10.0f; Component make_cmpnt; make_cmpnt.id = CMPNT_ID; CMPNT_ID++; make_cmpnt.node = irrlicht->smgr->addMeshSceneNode(cube_mesh,ctr_parent); make_cmpnt.node->setPosition(pos.irr()); make_cmpnt.node->setScale(scale.irr()); make_cmpnt.node->getMaterial(0).AmbientColor.set(a,r,g,b); make_cmpnt.shadow = irrlicht->smgr->addMeshSceneNode(cube_mesh,0); make_cmpnt.shadow->setScale({scale.x, scale.y, 0.1f}); make_cmpnt.shadow->setPosition({pos.x, pos.y,floor_position}); make_cmpnt.shadow->getMaterial(0).AmbientColor.set(GREY_BLUE_SHADOW); for (s4 i = 0; i < MAX_JOINTS; i++) make_cmpnt.joints[i] = 0; make_cmpnt.tree = 0; b_copy(cmpnt_list,&make_cmpnt); node_cmpnt_map.insert(make_cmpnt.node, (Component*)blast_address(cmpnt_list) ); return (Component*)blast_address(cmpnt_list); }; auto add_joint = [&] (Component* A, Component* B, vec3 posA, vec3 posB) { Joint C; C.A = A; C.posA = A->node->getTransformedBoundingBox().getExtent() * A->node->getScale(); C.posA *= (posA * 0.5f); C.B = B; C.posB = B->node->getTransformedBoundingBox().getExtent() * B->node->getScale(); C.posB *= (posB * 0.5f); C.type = Joint::SNAP; C.is_connected = false; b_copy(joint_list,&C); for (s4 i = 0; i < MAX_JOINTS; i++) { if (C.A->joints[i] == 0) { C.A->joints[i] = (Joint*)blast_address(joint_list); break; } else if (i == MAX_JOINTS-1) { std::cout << "ERROR: Joint could not be added to C.A." << std::endl; } } for (s4 i = 0; i < MAX_JOINTS; i++) { if (C.B->joints[i] == 0) { C.B->joints[i] = (Joint*)blast_address(joint_list); break; } else if (i == MAX_JOINTS-1) { std::cout << "ERROR: Joint could not be added to C.B." << std::endl; } } }; { Component* A = add_object_to_world(vec3(0,30,-20),vec3(3,3,3),BLUE_LIGHT); Component* B = add_object_to_world(vec3(0,60,-20),vec3(9,3,2),BLACK); add_joint(A,B,vec3(0.0f,0.0f,1.0f),vec3(0.0f,0.0f,-1.0f)); Component* C = add_object_to_world(vec3(0,-90,-20),vec3(3,3,3),YELLOW_LIGHT); Component* D = add_object_to_world(vec3(0,-40,-20),vec3(8,10,4),GREEN_LIGHT); add_joint(C,D,vec3(0.0f,1.0f,0.0f),vec3(0.0f,-1.0f,0.0f)); add_joint(A,D,vec3(0.0f,0.0f,-1.0f),vec3(0.0f,0.0f,1.0f)); } // temp objects ---------------------------------- SimpleNodeEditor* sneditor = simple_node_editor_init(); sneditor->root_node = ctr_parent; f4 target_z_rotation = empty_node->getRotation().Z; p("---- Game loop start ----"); f4 dt = 0.0f; const f4 maxDelta = 1.0f/60.0f * 5.0f; const f4 tick_ms = 0.01666f; f4 render_dt = 0.0f; const f4 render_ms = 0.016667f; u4 time_physics_prev = btclock->getTimeMicroseconds(); while(irrlicht->device->run() && game_state == GAME_STATE_PLAY) { const u4 time_physics_curr = btclock->getTimeMicroseconds(); const f4 frameTime = ((f4)(time_physics_curr - time_physics_prev)) / 1000000.0; // todo: is this truncated correctly? time_physics_prev = time_physics_curr; f4 capped_dt = frameTime; if (capped_dt > maxDelta) { capped_dt = maxDelta; } render_dt += capped_dt; if ( render_dt >= render_ms ) { render_dt = 0.0f; f4 curr_rotation = empty_node->getRotation().Z; if (curr_rotation != target_z_rotation) { weighted_average(curr_rotation,target_z_rotation, 20.0f); if (curr_rotation >= 360.0f) { curr_rotation -= 360.0f; target_z_rotation -= 360.0f; } else if (curr_rotation < 0) { curr_rotation += 360.0f; target_z_rotation += 360.0f; } empty_node->setRotation({0,0,curr_rotation}); } if (sneditor->selected_node) { position2d<s32> screen_coord = irrlicht->colmgr->getScreenCoordinatesFrom3DPosition(sneditor->selected_node->getPosition(), camera); sneditor->hand_icon->setPosition({(screen_coord.X - (SCREEN_WIDTH/2)) / ortho_scale, (screen_coord.Y - (SCREEN_HEIGHT/2)) / -ortho_scale,0}); } else { sneditor->hand_icon->setPosition({(sneditor->cursor->getPosition().X - (SCREEN_WIDTH/2)) / ortho_scale, (sneditor->cursor->getPosition().Y - (SCREEN_HEIGHT/2)) / -ortho_scale,0}); } // Render irrlicht->driver->beginScene(true, true, SColor(GREY_BLUE)); irrlicht->smgr->drawAll(); irrlicht->driver->clearZBuffer(); irrlicht->hud->drawAll(); irrlicht->driver->endScene(); } dt += capped_dt; while( dt >= tick_ms ) { dt -= tick_ms; receiver->input(); if (receiver->a.state) target_z_rotation -= 90.0f; if (receiver->d.state) target_z_rotation += 90.0f; simple_node_editor_update( sneditor, receiver->mouse.left.state, receiver->mouse.left.released, receiver->mouse.right.state, false, receiver->tab.state, camera, &node_cmpnt_map); // TODO: Change this to: // - only test what the user is holding // - and only if the user is holding the smaller inserting part. // example: holding a screw in a large box bloop(joint_list, i) { Joint* c = (Joint*)b_get_mem_address(joint_list,i); if (c->A->tree != sneditor->selected_tree && c->B->tree != sneditor->selected_tree ) { continue; } if (!c->is_connected) { vec3 A = c->A->node->getPosition(); vec3 B = c->B->node->getPosition(); A += c->posA; B += c->posB; if (A.distance(B) < 13 /* && receiver->spacebar*/) { std::cout << "Comparing " << i << std::endl; c->is_connected = true; connect_joints(c,sneditor,camera,tree_list); } } } bloop(tree_list, i) { CTree* tree = (CTree*)b_get_mem_address(tree_list,i); if (tree->translation == vec3(0,0,0)) { continue; } for (s4 k = 0; k < tree->child_list.length;k++) { Component* cmpnt = (Component*)b_get_value(tree->child_list,k); cmpnt->node->setPosition(cmpnt->node->getPosition() + tree->translation.irr()); cmpnt->shadow->setPosition(cmpnt->node->getPosition() * vector3df(1,1,0) + vector3df(0,0,10)); } tree->translation = vec3(0,0,0); } if (receiver->restart.state) { game_state = GAME_STATE_RESET; } if (receiver->QUIT) { game_state = GAME_STATE_QUIT; } }
void think() { block_value = weighted_average(neighbor_data); }
// Angular Rate = w1 * AccelRate + w2*GyroRate; // // Question is how do we find the variance when the numbers are non constant?! // We can measure how they co-vary with other measurements. void compute_accelGyro_fusion( BOOL mShowDebug ) { calc_fusion_time_delta(FALSE); BestAnglesPrev = BestAngles; BestAngularRatePrev = BestAngularRate; //printf("compute_accelGyro_fusion. "); /* Note to compare apples to apples, Gyro and Accel need to both give degrees per second! Gyro gives (degrees per second) AccelAngularVelocity gives (degrees per second) *** Not oranges to oranges! *** Gyro gives (degrees change) & AccelAngularVelocity gives (degrees change) But time period may be different for each. */ // IF ACCEL IS_WITHIN_1G() AND GYRO NEAR 0 // Safe to extract angles based on accelerometer. // Don't just average this angle in with previous+delta. Instead it sets the standard, // the best result can be within a range +- from this. // IF ACCEL IS_WITHIN_1G() AND Gyro shows movement // Safe to extract angles based on accelerometer. // Average the delta with Gyro // BestAngle will be PrevAngles + averaged deltas. // IF ACCEL IS NOT WITHIN_1G() // BestAngle will be PrevAngles + gyro deltas. // Extract linear acceleration //char LinearAccelerationDetected = compare_to_1g(&AccelScaled, 3.0*Gravity_variance); if (LinearAccelerationDetected) { //calc_stationary_angles( ); already done. BestAngularRate = GyroAdjusted; extract_linear_acceleration(); } else if ( significant_gyro_accel_discrepancy() ) { float wG = 2.0; float wA = 1.0; printf("Significant Discrepancy between Accel & Gyro\n"); // more weight given to gyro for angular changes. struct fXYZ average_rate = weighted_average( cast_f &GyroAdjusted, cast_f &AccelAngularVelocity, wG, wA ); BestAngularRate = *(cast_fr &average_rate); } else { float wG = 1.0; float wA = 10.0; // DELTA denotes a change from 1 time period to the next. // Rate denotes a change over 1 second. struct fXYZ average_rate = weighted_average( cast_f &GyroAdjusted, cast_f &AccelAngularVelocity, wG, wA ); BestAngularRate = *(cast_fr &average_rate); } // SCALE ANGULAR RATE BY Time to get DELTA ANGLE (for the timeslice): struct frXYZ BestAngularDelta; scale( cast_f &BestAngularRate, fusion_time_delta, cast_f &BestAngularDelta ); add ( cast_f &BestAnglesPrev, cast_f &BestAngularDelta, cast_f &BestAngles ); // print_params(); }