Exemple #1
0
int main(int argc, char* argv[])
{
	if ((argc == 2) && (strcmp(argv[1], "-v") == 0)) {
		printf("Server Version: LoginServer/%s\n", VERSION);
		printf("Server Build: %s %s\n", __DATE__, __TIME__);
		return 0;
	}

	signal(SIGPIPE, SIG_IGN);

	CConfigFileReader config_file("loginserver.conf");

    char* client_listen_ip = config_file.GetConfigName("ClientListenIP");
    char* str_client_port = config_file.GetConfigName("ClientPort");
    char* http_listen_ip = config_file.GetConfigName("HttpListenIP");
    char* str_http_port = config_file.GetConfigName("HttpPort");
	char* msg_server_listen_ip = config_file.GetConfigName("MsgServerListenIP");
	char* str_msg_server_port = config_file.GetConfigName("MsgServerPort");
    char* str_msfs_url = config_file.GetConfigName("msfs");
    char* str_discovery = config_file.GetConfigName("discovery");

	if (!msg_server_listen_ip || !str_msg_server_port || !http_listen_ip
        || !str_http_port || !str_msfs_url || !str_discovery) {
		log("config item missing, exit... ");
		return -1;
	}

	uint16_t client_port = atoi(str_client_port);
	uint16_t msg_server_port = atoi(str_msg_server_port);
    uint16_t http_port = atoi(str_http_port);
    strMsfsUrl = str_msfs_url;
    strDiscovery = str_discovery;
    
    
    pIpParser = new IpParser();
    
	int ret = netlib_init();

	if (ret == NETLIB_ERROR)
		return ret;
	CStrExplode client_listen_ip_list(client_listen_ip, ';');
	for (uint32_t i = 0; i < client_listen_ip_list.GetItemCnt(); i++) {
		ret = netlib_listen(client_listen_ip_list.GetItem(i), client_port, client_callback, NULL);
		if (ret == NETLIB_ERROR)
			return ret;
	}

	CStrExplode msg_server_listen_ip_list(msg_server_listen_ip, ';');
	for (uint32_t i = 0; i < msg_server_listen_ip_list.GetItemCnt(); i++) {
		ret = netlib_listen(msg_server_listen_ip_list.GetItem(i), msg_server_port, msg_serv_callback, NULL);
		if (ret == NETLIB_ERROR)
			return ret;
	}
    
    CStrExplode http_listen_ip_list(http_listen_ip, ';');
    for (uint32_t i = 0; i < http_listen_ip_list.GetItemCnt(); i++) {
        ret = netlib_listen(http_listen_ip_list.GetItem(i), http_port, http_callback, NULL);
        if (ret == NETLIB_ERROR)
            return ret;
    }
    

	printf("server start listen on:\nFor client %s:%d\nFor MsgServer: %s:%d\nFor http:%s:%d\n",
			client_listen_ip, client_port, msg_server_listen_ip, msg_server_port, http_listen_ip, http_port);
	init_login_conn();
    init_http_conn();

	printf("now enter the event loop...\n");
    
    writePid();

	netlib_eventloop();

	return 0;
}
int main( ) {

   std::string input_dir = "Input/";

   // Read Nucleus File
   std::string nucleus_string;
   std::ifstream nucleus_file( "domgen.config" );

   nucleus_file >> nucleus_string;

   nucleus_file.close();
   nucleus_file.clear();

   // Read Configuration file
   std::string config_filename = nucleus_string + ".config";
   std::ifstream config_file( config_filename.c_str() );

   std::string parameters_string;
   int fit_ph;
   double rmax;
   int rpts;
   int lmax;

   config_file >> parameters_string >> fit_ph;
   config_file >> rmax >> rpts >> lmax;

   cout<<"parameters_string = "<<parameters_string<<endl;

   int num_lj;
   config_file >> num_lj;

   config_file.close();
   config_file.clear();

   // Read in normalization
   double calc_Z = 20;
   double calc_N = 20;
   //std::cout << "Enter calculated Z: " << std::endl;
   //std::cin >> calc_Z; 

   //std::cout << "Enter calculated N: " << std::endl;
   //std::cin >> calc_N;

   std::string output_dir = "Output_" + parameters_string + "/Spectral_functions_kE/";
   std::string parameters_filename = parameters_string + ".inp";

   std::cout << "rmax = " << rmax << std::endl;
   std::cout << "rpts = " << rpts << std::endl;
   std::cout << "lmax = " << lmax << std::endl;

   std::string n_string = "n" + nucleus_string;
   std::string p_string = "p" + nucleus_string;

   std::string n_filename = input_dir + n_string + ".inp";
   std::string p_filename = input_dir + p_string + ".inp";

   // Create Nuclear Parameter Objects
   NuclearParameters Nu_n = read_nucleus_parameters( n_filename );
   NuclearParameters Nu_p = read_nucleus_parameters( p_filename );

   std::vector< NuclearParameters > Nu_vec;
   Nu_vec.push_back( Nu_n );
   Nu_vec.push_back( Nu_p );


   // Read in DOM parameters
   std::ifstream pfile( parameters_filename.c_str() );
   if ( pfile.is_open() !=1 ) {
      std::cout << "could not open file " << parameters_filename << std::endl;
      std::abort();
   }
   pfile.close();
   pfile.clear();

   // Create radial grid
   std::vector<double> rmesh;
   std::vector<double> rweights;
   double rdelt = rmax / rpts;
   for( int i = 0; i < rpts; ++i ) {

      rmesh.push_back( ( i + 0.5 ) * rdelt );
      rweights.push_back( rdelt );

   }

   // Create momentum space grid for k-slice
   std::vector<double> kmesh1;
   double kmax1 = 6.0;
   int kpts1 = 100;
   double deltak1 = kmax1 / kpts1;

   for ( int i = 0; i < kpts1; ++i ) {

      kmesh1.push_back( ( i + 0.5 ) * deltak1 );
   }

   // Create momentum space grid for E-slice
   std::vector<double> kmesh2; // wave number in units of fm^{-1}
std::vector<double> pmesh; // momentum in units of MeV / c
double pmin = 170; 
double pmax = 650;
double deltap = 40;
int ppts = static_cast<int> ( ( pmax - pmin ) / deltap ) + 1;

for ( int i = 0; i < ppts; ++i ) {

   double p = pmin + i * deltap;
   pmesh.push_back( p );

   double k = p / hbarc;
   kmesh2.push_back( k );
}

// Prepare stuff for output files
std::vector< std::string > np_strings;
np_strings.push_back( n_string );
np_strings.push_back( p_string );

// create L and J strings for output files
std::string L_array[8] = { "s", "p", "d", "f", "g", "h", "i", "j" };
std::string J_array[8] = { "1", "3", "5", "7", "9", "11", "13", "15" };

//Potential specifications
int type = 1; // 1 is P.B. form (average), 0 is V.N. form
int mvolume = 4;
int AsyVolume = 1;


/* CALCULATIONS */


// Loop over protons and neutrons
double Zp; // number of protons in projectile
omp_set_nested(1);
#pragma omp parallel num_threads(2)
{
#pragma omp for
   for ( unsigned int nu = 0; nu < Nu_vec.size(); ++nu ) {

      double tz = nu - 0.5; // +0.5 for protons, -0.5 for neutrons
      double calc_norm;
      if ( tz < 0 ) {

         Zp = 0;
         calc_norm = calc_N;
      }
      else { 

         Zp = 1;
         calc_norm = calc_Z;
      }

      // Nucleus Object
      const NuclearParameters &Nu = Nu_vec[nu];

      // Construct Parameters Object
      Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, Zp );

      // Construct Potential Object
      pot U = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
      pot *U1 = &U;

      // Construct Object for calculating bound-state properties
      boundRspace B( rmax, rpts, Nu.Ef, Nu.ph_gap, lmax, Nu.Z, Zp, Nu.A, U1 );

      // Create Energy Grid for k-slice
      double Emin1 = -225;
      double Emax1 = -25;
      double deltaE1 = 25;
      int epts1 = static_cast<int>( ( Emax1 - Emin1 ) / deltaE1 ) + 1;
      std::vector<double> emesh1;
      for ( int i = 0; i < epts1; ++i ) {

         emesh1.push_back( Emin1 + i * deltaE1 );
      }

      // Create Energy grid for E-slice
      double Emin2 = -300;
      double Emax2 = -25;
      double deltaE2 = 2;
      int epts2 = static_cast<int>( ( Emax2 - Emin2 ) / deltaE2 ) + 1;
      std::vector<double> emesh2;
      for ( int i = 0; i < epts2; ++i ) {

         emesh2.push_back( Emin2 + i * deltaE2 );
      }

      matrix_t S_of_kE_mtx1( kmesh1.size(), emesh1.size() );
      matrix_t S_of_kE_mtx2( kmesh2.size(), emesh2.size() );

      // intialize matrices to zero
      for ( unsigned int i = 0; i < kmesh1.size(); ++i ) {
         for ( unsigned int j = 0; j < emesh1.size(); ++j ) {

            S_of_kE_mtx1( i, j ) = 0;
         }
      }

      for ( unsigned int i = 0; i < kmesh2.size(); ++i ) {
         for ( unsigned int j = 0; j < emesh2.size(); ++j ) {

            S_of_kE_mtx2( i, j ) = 0;
         }
      }

      std::vector< matrix_t > S_of_kE_mtx2_lj_vec;

      // Loop over lj channels
      for ( int L = 0; L < lmax + 1; ++L ) {
         cout<<"l = "<<L<<endl;

         for( int up = -1; up < 2; up+=2 ) {

            double xj = L + up / 2.0;
            int j_index = ( up - 1 ) / 2;
            if ( xj < 0 ) continue;

            std::string j_string;
            if ( L == 0 ) j_string = J_array[ L ];
            else j_string = J_array[ L + j_index ];

            std::string lj_string = L_array[L] + j_string + "2";

            // Create Bessel Function matrix in k and r
            matrix_t bess_mtx1( kmesh1.size(), rmesh.size() );
            for( unsigned int nk = 0; nk < kmesh1.size(); ++nk ) {
               for( unsigned int nr = 0; nr < rmesh.size(); ++nr ) {

                  double rho = kmesh1[nk] * rmesh[nr];

                  bess_mtx1( nk, nr ) = gsl_sf_bessel_jl( L, rho );
               }
            }

            // Create Bessel Function matrix in k and r
            matrix_t bess_mtx2( kmesh2.size(), rmesh.size() );
            for( unsigned int nk = 0; nk < kmesh2.size(); ++nk ) {
               for( unsigned int nr = 0; nr < rmesh.size(); ++nr ) {

                  double rho = kmesh2[nk] * rmesh[nr];

                  bess_mtx2( nk, nr ) = gsl_sf_bessel_jl( L, rho );
               }
            }

            // Calculate S( k; E ) for k-slice 
            for ( unsigned int m = 0; m < emesh1.size(); ++m ) {

               double E = emesh1[m];

               /*
                  std::ostringstream e_strm;
                  e_strm << "m" << std::abs( E );
                  std::string s_of_kE_lj_filename1 = 
                  output_dir + np_strings[nu] + "_s_of_k_" + 
                  "E_at_" + e_strm.str() + "MeV_" + L_array[L] 
                  + j_string + "2.out";

                  std::ofstream file1( s_of_kE_lj_filename1.c_str() );
                  */
               // Propagator
               cmatrix_t G = B.propagator( rmesh, E, L, xj );

               // Spectral Function in momentum space, S( k; E ) 
               for( unsigned int nk = 0; nk < kmesh1.size(); ++nk ) {

                  double rsums = 0;
                  for( unsigned int i = 0; i < rmesh.size(); ++i ) {
                     double jl1 = bess_mtx1( nk, i );

                     for( unsigned int j = 0; j < rmesh.size(); ++j ) {
                        double jl2 = bess_mtx1( nk, j );

                        rsums -= rmesh[i] * jl1 * imag( G( i, j ) ) 
                           * rmesh[j] * jl2 * rdelt * 2 / M_PI / M_PI;
                     }
                  } // end loop over radial coordinates

                  //                        file1 << kmesh1[nk] << " " << rsums << std::endl;

                  S_of_kE_mtx1( nk, m ) += ( 2 * xj + 1 ) * rsums;

               } // end loop over k

               //                    file1.close();
               //                    file1.clear();

               // r-space spectral functions

            } // end loop over energy

            // Calculate S( k; E ) for E-slice 
            matrix_t S_of_kE_mtx_lj( kmesh2.size(), emesh2.size() );
            for ( unsigned int m = 0; m < emesh2.size(); ++m ) {

               double E = emesh2[m];

               // Propagator
               cmatrix_t G = B.propagator( rmesh, E, L, xj );

               // Spectral Function in momentum space, S( k; E ) 
               for( unsigned int nk = 0; nk < kmesh2.size(); ++nk ) {

                  double rsums = 0;
                  for( unsigned int i = 0; i < rmesh.size(); ++i ) {
                     double jl1 = bess_mtx2( nk, i );

                     for( unsigned int j = 0; j < rmesh.size(); ++j ) {
                        double jl2 = bess_mtx2( nk, j );

                        rsums -= rmesh[i] * jl1 * imag( G( i, j ) ) 
                           * rmesh[j] * jl2 * rdelt * 2 / M_PI / M_PI;
                     }
                  } // end loop over radial coordinates

                  S_of_kE_mtx_lj( nk, m ) = ( 2 * xj + 1 ) * rsums;
                  S_of_kE_mtx2( nk, m ) += ( 2 * xj + 1 ) * rsums;

               } // end loop over k

            } // end loop over energy

            S_of_kE_mtx2_lj_vec.push_back( S_of_kE_mtx_lj );

         }// end loop over j

      } // end loop over L

      // write out results summed over the lj combinations
      for ( unsigned int j = 0; j < emesh1.size(); ++j ) {

         std::ostringstream e_strm;
         e_strm << "m" << std::abs( emesh1[j] );
         std::string s_of_kE_filename1 = 
            output_dir + np_strings[nu] + "_s_of_k_" + 
            "E_at_" + e_strm.str() + "MeV.out"; 

         std::ofstream file3( s_of_kE_filename1.c_str() );

         for ( unsigned int i = 0; i < kmesh1.size(); ++i ) {

            file3 << kmesh1[i] << " " << S_of_kE_mtx1( i, j ) << std::endl;
         }

         file3.close();
         file3.clear();
      }

      // write in units of MeV^-4 sr^-1
      double fac = std::pow( hbarc, 3 ) * 4 * M_PI;
      for ( unsigned int i = 0; i < kmesh2.size(); ++i ) {
         std::ostringstream k_strm;
         k_strm << pmesh[i];
         std::string s_of_kE_filename2 = 
            output_dir + np_strings[nu] + "_s_of_E_" + 
            "p_at_" + k_strm.str() + "MeV_over_c.out"; 

         std::ofstream file4( s_of_kE_filename2.c_str() );

         for ( unsigned int j = 0; j < emesh2.size(); ++j ) {

            // write energy in terms of missing energy
            // and in units of GeV
            file4 << std::abs( emesh2[j]/1000) << " " 
               << S_of_kE_mtx2( i, j ) / fac << " "
               << S_of_kE_mtx2( i, j ) / fac / calc_norm << std::endl;
         }

         file4.close();
         file4.clear();
      }

      // write in units of MeV^-4 sr^-1
      for ( unsigned int nk = 0; nk < kmesh2.size(); ++nk ) {

         for ( int L = 0; L < lmax + 1; ++L ) {

            std::ostringstream k_strm;
            k_strm << pmesh[nk];

            std::string s_of_kE_lj_filename2 = 
               output_dir + np_strings[nu] + "_s_of_E_p_at_" 
               + k_strm.str() + "MeV_over_c_" + L_array[L] 
               + ".out";

            std::ofstream file2( s_of_kE_lj_filename2.c_str() );
            for ( unsigned int m = 0; m < emesh2.size(); ++m ) {

               // write energy in terms of missing energy
               // and in units of GeV
               if ( L == 0 ) {
                  file2 << std::abs( emesh2[m]/1000 ) << " " 
                     << S_of_kE_mtx2_lj_vec[0]( nk, m ) / fac 
                     << std::endl;
               }
               else {

                  double jg = S_of_kE_mtx2_lj_vec[2*L]( nk, m );
                  double jl = S_of_kE_mtx2_lj_vec[2*L- 1]( nk, m );

                  file2 << std::abs( emesh2[m]/1000) << " " 
                     << jg / fac << " " << jl / fac << " "
                     << ( jg + jl ) / fac << std::endl;
               }
            }

            file2.close();
            file2.clear();

         } // end loop over L

      } // end loop over momentum

   } // end loop over tz
}                                               /* end of pragma loop */

return 1;
}
Exemple #3
0
int
main(int argc, char *argv[])
{
	time_t start;
	int ch, i, onerun, reps, ret;
	const char *config, *home;

	config = NULL;

	if ((g.progname = strrchr(argv[0], DIR_DELIM)) == NULL)
		g.progname = argv[0];
	else
		++g.progname;

#if 0
	/* Configure the GNU malloc for debugging. */
	(void)setenv("MALLOC_CHECK_", "2", 1);
#endif
#if 0
	/* Configure the FreeBSD malloc for debugging. */
	(void)setenv("MALLOC_OPTIONS", "AJ", 1);
#endif

	/* Track progress unless we're re-directing output to a file. */
	g.track = isatty(1) ? 1 : 0;

	/* Set values from the command line. */
	home = NULL;
	onerun = 0;
	while ((ch = __wt_getopt(
	    g.progname, argc, argv, "1C:c:H:h:Llqrt:")) != EOF)
		switch (ch) {
		case '1':			/* One run */
			onerun = 1;
			break;
		case 'C':			/* wiredtiger_open config */
			g.config_open = __wt_optarg;
			break;
		case 'c':			/* Configuration from a file */
			config = __wt_optarg;
			break;
		case 'H':
			g.helium_mount = __wt_optarg;
			break;
		case 'h':
			home = __wt_optarg;
			break;
		case 'L':			/* Re-direct output to a log */
			/*
			 * The -l option is a superset of -L, ignore -L if we
			 * have already configured logging for operations.
			 */
			if (g.logging == 0)
				g.logging = LOG_FILE;
			break;
		case 'l':			/* Turn on operation logging */
			g.logging = LOG_OPS;
			break;
		case 'q':			/* Quiet */
			g.track = 0;
			break;
		case 'r':			/* Replay a run */
			g.replay = 1;
			break;
		default:
			usage();
		}
	argc -= __wt_optind;
	argv += __wt_optind;

	/*
	 * Initialize the global RNG. Start with the standard seeds, and then
	 * use seconds since the Epoch modulo a prime to run the RNG for some
	 * number of steps, so we don't start with the same values every time.
	 */
	__wt_random_init(&g.rnd);
	for (i = (int)time(NULL) % 10007; i > 0; --i)
		(void)__wt_random(&g.rnd);

	/* Set up paths. */
	path_setup(home);

	/* If it's a replay, use the home directory's CONFIG file. */
	if (g.replay) {
		if (config != NULL)
			die(EINVAL, "-c incompatible with -r");
		if (access(g.home_config, R_OK) != 0)
			die(ENOENT, "%s", g.home_config);
		config = g.home_config;
	}

	/*
	 * If we weren't given a configuration file, set values from "CONFIG",
	 * if it exists.
	 *
	 * Small hack to ignore any CONFIG file named ".", that just makes it
	 * possible to ignore any local CONFIG file, used when running checks.
	 */
	if (config == NULL && access("CONFIG", R_OK) == 0)
		config = "CONFIG";
	if (config != NULL && strcmp(config, ".") != 0)
		config_file(config);

	/*
	 * The rest of the arguments are individual configurations that modify
	 * the base configuration.
	 */
	for (; *argv != NULL; ++argv)
		config_single(*argv, 1);

	/*
	 * Multithreaded runs can be replayed: it's useful and we'll get the
	 * configuration correct.  Obviously the order of operations changes,
	 * warn the user.
	 */
	if (g.replay && !SINGLETHREADED)
		printf("Warning: replaying a threaded run\n");

	/*
	 * Single-threaded runs historically exited after a single replay, which
	 * makes sense when you're debugging, leave that semantic in place.
	 */
	if (g.replay && SINGLETHREADED)
		g.c_runs = 1;

	/*
	 * Let the command line -1 flag override runs configured from other
	 * sources.
	 */
	if (onerun)
		g.c_runs = 1;

	/*
	 * Initialize locks to single-thread named checkpoints and backups, last
	 * last-record updates, and failures.
	 */
	if ((ret = pthread_rwlock_init(&g.append_lock, NULL)) != 0)
		die(ret, "pthread_rwlock_init: append lock");
	if ((ret = pthread_rwlock_init(&g.backup_lock, NULL)) != 0)
		die(ret, "pthread_rwlock_init: backup lock");
	if ((ret = pthread_rwlock_init(&g.death_lock, NULL)) != 0)
		die(ret, "pthread_rwlock_init: death lock");

	printf("%s: process %" PRIdMAX "\n", g.progname, (intmax_t)getpid());
	while (++g.run_cnt <= g.c_runs || g.c_runs == 0 ) {
		startup();			/* Start a run */

		config_setup();			/* Run configuration */
		config_print(0);		/* Dump run configuration */
		key_len_setup();		/* Setup keys */

		start = time(NULL);
		track("starting up", 0ULL, NULL);

#ifdef HAVE_BERKELEY_DB
		if (SINGLETHREADED)
			bdb_open();		/* Initial file config */
#endif
		wts_open(g.home, 1, &g.wts_conn);
		wts_create();

		wts_load();			/* Load initial records */
		wts_verify("post-bulk verify");	/* Verify */

		/*
		 * If we're not doing any operations, scan the bulk-load, copy
		 * the statistics and we're done. Otherwise, loop reading and
		 * operations, with a verify after each set.
		 */
		if (g.c_timer == 0 && g.c_ops == 0) {
			wts_read_scan();		/* Read scan */
			wts_stats();			/* Statistics */
		} else
			for (reps = 1; reps <= FORMAT_OPERATION_REPS; ++reps) {
				wts_read_scan();	/* Read scan */

							/* Operations */
				wts_ops(reps == FORMAT_OPERATION_REPS);

				/*
				 * Copy out the run's statistics after the last
				 * set of operations.
				 *
				 * XXX
				 * Verify closes the underlying handle and
				 * discards the statistics, read them first.
				 */
				if (reps == FORMAT_OPERATION_REPS)
					wts_stats();

							/* Verify */
				wts_verify("post-ops verify");
			}

		track("shutting down", 0ULL, NULL);
#ifdef HAVE_BERKELEY_DB
		if (SINGLETHREADED)
			bdb_close();
#endif
		wts_close();

		/*
		 * If single-threaded, we can dump and compare the WiredTiger
		 * and Berkeley DB data sets.
		 */
		if (SINGLETHREADED)
			wts_dump("standard", 1);

		/*
		 * Salvage testing.
		 */
		wts_salvage();

		/* Overwrite the progress line with a completion line. */
		if (g.track)
			printf("\r%78s\r", " ");
		printf("%4d: %s, %s (%.0f seconds)\n",
		    g.run_cnt, g.c_data_source,
		    g.c_file_type, difftime(time(NULL), start));
		fflush(stdout);
	}

	/* Flush/close any logging information. */
	fclose_and_clear(&g.logfp);
	fclose_and_clear(&g.randfp);

	config_print(0);

	if ((ret = pthread_rwlock_destroy(&g.append_lock)) != 0)
		die(ret, "pthread_rwlock_destroy: append lock");
	if ((ret = pthread_rwlock_destroy(&g.backup_lock)) != 0)
		die(ret, "pthread_rwlock_destroy: backup lock");

	config_clear();

	return (EXIT_SUCCESS);
}
Exemple #4
0
void read_config_into_struct(std::string path,
		glxosd_config_type* configuration) {
	std::ifstream config_file(path.c_str());
	if (!config_file) {
		std::cout << "[GLXOSD]: There is no file at \"" << path
				<< "\". Skipping." << std::endl;
		return;
	}
	while (!config_file.eof()) {
		std::string line;
		std::getline(config_file, line);
		std::string::size_type key_begin = line.find_first_not_of(" \f\t\v");
		if (key_begin == std::string::npos || line[key_begin] == '#') //Empty line or comment
			continue;
		std::string::size_type assign_op = line.find('=', key_begin);
		std::string::size_type key_end = line.find_last_not_of(" \f\n\r\t\v",
				assign_op - 1);
		std::string key = line.substr(key_begin, key_end - key_begin + 1);
		std::string::size_type value_begin = line.find_first_not_of(
				" \f\n\r\t\v", assign_op + 1);
		std::string::size_type value_end = line.find_last_not_of(" \f\n\r\t\v")
				+ 1;
		std::string value = line.substr(value_begin, value_end - value_begin);
		if (value.size() > 1 && value[0] == '"'
				&& value[value.size() - 1] == '"')
			value = value.substr(1, value.size() - 2);
		if (value.size() > 1 && value[0] == '\\' && value[1] == '"')
			value = value.substr(1, value.size() - 1);
		std::cout << "[GLXOSD]: Found key-value pair: (key: \"" << key << "\""
				<< ", value: \"" << value << "\")" << std::endl;
		value = unescape(value);
		if (key == "font_name")
			configuration->font_name = value;
		else if (key == "font_size")
			configuration->font_size = boost::lexical_cast<int>(value);
		else if (key == "font_colour_r")
			configuration->font_colour_r = boost::lexical_cast<int>(value);
		else if (key == "font_colour_g")
			configuration->font_colour_g = boost::lexical_cast<int>(value);
		else if (key == "font_colour_b")
			configuration->font_colour_b = boost::lexical_cast<int>(value);
		else if (key == "text_pos_x")
			configuration->text_pos_x = boost::lexical_cast<int>(value);
		else if (key == "text_pos_y")
			configuration->text_pos_y = boost::lexical_cast<int>(value);
		else if (key == "text_spacing_x")
			configuration->text_spacing_x = boost::lexical_cast<int>(value);
		else if (key == "text_spacing_y")
			configuration->text_spacing_y = boost::lexical_cast<int>(value);
		else if (key == "fps_format")
			configuration->fps_format = boost::format(value);
		else if (key == "chip_format")
			configuration->chip_format = boost::format(value);
		else if (key == "chip_feature_format")
			configuration->chip_feature_format = boost::format(value);
		else if (key == "nvidia_gpu_format")
			configuration->nvidia_gpu_format = boost::format(value);
		else if (key == "temperature_format")
			configuration->temperature_format = boost::format(value);
		else if (key == "chip_feature_filter") {
			configuration->chip_feature_filter = boost::regex();
			configuration->chip_feature_filter.assign(value,
					boost::regex_constants::icase);
		} else if (key == "show_text_outline")
			configuration->show_text_outline = (value == "true");
		else
			std::cout << "[GLXOSD]: Unknown key: \"" << key << "\""
					<< std::endl;
	}
	std::cout << "[GLXOSD]: The configuration was read successfully."
			<< std::endl;
}
Exemple #5
0
int main(int argc, char* argv[])
{
#if 0
    pid_t pid = fork();
    if (pid < 0) {
        exit(-1);
    } else if (pid > 0) {
        exit(0);
    }
    setsid();
#endif
	if ((argc == 2) && (strcmp(argv[1], "-v") == 0)) {
		printf("Server Version: FileServer/%s\n", VERSION);
		printf("Server Build: %s %s\n", __DATE__, __TIME__);
		return 0;
	}

	signal(SIGPIPE, SIG_IGN);
	// ¶ÁÈ¡ÅäÖÃÎļþ
	CConfigFileReader config_file("fileserver.conf");

    char* str_client_listen_ip = config_file.GetConfigName("ClientListenIP");
	char* str_client_listen_port = config_file.GetConfigName("ClientListenPort");
    char* str_msg_server_listen_ip = config_file.GetConfigName("MsgServerListenIP");
    char* str_msg_server_listen_port = config_file.GetConfigName("MsgServerListenPort");

    char* str_task_timeout = config_file.GetConfigName("TaskTimeout");

	if (!str_client_listen_ip || !str_client_listen_port || !str_msg_server_listen_ip || !str_msg_server_listen_port) {
		log("config item missing, exit... ");
		return -1;
	}

    uint16_t client_listen_port = atoi(str_client_listen_port);
 
    CStrExplode client_listen_ip_list(str_client_listen_ip, ';');
    std::list<IM::BaseDefine::IpAddr> q;
    for (uint32_t i = 0; i < client_listen_ip_list.GetItemCnt(); i++) {
        ConfigUtil::GetInstance()->AddAddress(client_listen_ip_list.GetItem(i), client_listen_port);
    }
    
    uint16_t msg_server_listen_port = atoi(str_msg_server_listen_port);
    uint32_t task_timeout = atoi(str_task_timeout);

    ConfigUtil::GetInstance()->SetTaskTimeout(task_timeout);
    
    InitializeFileMsgServerConn();
	InitializeFileClientConn();

	int ret = netlib_init();

	if (ret == NETLIB_ERROR)
		return ret;


	for (uint32_t i = 0; i < client_listen_ip_list.GetItemCnt(); i++) {
		// sokcet bind listen FileClientConnCallback
		ret = netlib_listen(client_listen_ip_list.GetItem(i), client_listen_port, FileClientConnCallback, NULL);
        if (ret == NETLIB_ERROR) {
            printf("listen %s:%d error!!\n", client_listen_ip_list.GetItem(i), client_listen_port);
			return ret;
        } else {
            printf("server start listen on %s:%d\n", client_listen_ip_list.GetItem(i), client_listen_port);
        }
	}
	// sokcet bind listen FileMsgServerConnCallback
    ret = netlib_listen(str_msg_server_listen_ip, msg_server_listen_port, FileMsgServerConnCallback, NULL);
    if (ret == NETLIB_ERROR) {
        printf("listen %s:%d error!!\n", str_msg_server_listen_ip, msg_server_listen_port);
        return ret;
    } else {
        printf("server start listen on %s:%d\n", str_msg_server_listen_ip, msg_server_listen_port);
    }

	printf("now enter the event loop...\n");
    
    writePid();

	netlib_eventloop();

	printf("exiting.......\n");
	log("exit");

	return 0;
}
int main(int argc, char** argv)
{
    std::string filename;
    try
    {
        configuration config;
        std::string copyright_filename;

        // Read/get configuration
        {
            namespace po = boost::program_options;
            po::options_description description("=== doxml2qbk ===\nAllowed options");


            std::string convenience_headers;

            description.add_options()
                ("help", "Help message")
                ("xml", po::value<std::string>(&filename), 
                            "Name of XML file written by Doxygen")
                ("start_include", po::value<std::string>(&config.start_include), 
                            "Start include")
                ("convenience_header_path", po::value<std::string>(&config.convenience_header_path), 
                            "Convenience header path")
                ("convenience_headers", po::value<std::string>(&convenience_headers), 
                            "Convenience header(s) (comma-separated)")
                ("skip_namespace", po::value<std::string>(&config.skip_namespace), 
                            "Namespace to skip (e.g. boost::mylib::")
                ("copyright", po::value<std::string>(&copyright_filename), 
                            "Name of QBK file including (commented) copyright and license")
            ;

            po::variables_map varmap;

            if (argc == 2 && ! boost::starts_with(argv[1], "--"))
            {
                // (especially for debugging) options might go into an INI file
                std::ifstream config_file (argv[1], std::ifstream::in);
                po::store(po::parse_config_file(config_file, description), varmap);
            }
            else
            {
                po::store(po::parse_command_line(argc, argv, description), varmap);
            }

            po::notify(varmap);

            if (varmap.count("help") || filename.empty())
            {
                std::cout << description << std::endl;
                return 1;
            }

            // Split CSV with headerfile names into configuration
            if (! convenience_headers.empty())
            {
                boost::split(config.convenience_headers, convenience_headers, boost::is_any_of(","));
            }
        }

        // Read files into strings
        std::string xml_string = file_to_string(filename);
        std::string license = copyright_filename.empty() 
            ? "" 
            : file_to_string(copyright_filename);

        // Parse the XML outputted by Doxygen
        xml_doc xml(xml_string.c_str());

        documentation doc;
        parse(xml.first_node(), config, doc);

        // Check for duplicate function names
        for (std::size_t i = 0; i < doc.functions.size(); i++)
        {
            function& f1 = doc.functions[i];
            for (std::size_t j = i + 1; j < doc.functions.size(); j++)
            {
                function& f2 = doc.functions[j];

                if (f1.name == f2.name)
                {
                    // It is not a unique function, so e.g. an overload,
                    // so a description must distinguish them.
                    // Difference is either the number of parameters, or a const / non-const version
                    // Use the "\qbk{distinguish,with strategy}" in the source code to distinguish
                    f1.unique = false;
                    f2.unique = false;
                }
            }
        }


        // Write copyright/license (keep inspect silent)
        if (! license.empty())
        {
            std::cout << license << std::endl;
        }

        // Write warning comment
        std::cout
            << "[/ Generated by doxygen_xml2qbk, don't change, will be overwritten automatically]" << std::endl
            << "[/ Generated from " << filename << "]" << std::endl;

        // Write the rest: functions, defines, classes or structs
        BOOST_FOREACH(function const& f, doc.functions)
        {
            quickbook_output(f, config, std::cout);
        }
        BOOST_FOREACH(function const& f, doc.defines)
        {
            quickbook_output(f, config, std::cout);
        }
        BOOST_FOREACH(enumeration const& e, doc.enumerations)
        {
            quickbook_output(e, config, std::cout);
        }

        if (! doc.cos.name.empty())
        {
            std::sort(doc.cos.functions.begin(), doc.cos.functions.end(), sort_on_line<function>());
            quickbook_output(doc.cos, config, std::cout);
        }

    }
    catch(std::exception const& e)
    {
        std::cerr << "Exception in doxygen_xml2qbk: " << std::endl
            << "   Message: " << e.what() << std::endl
            << "   File: " << filename << std::endl
            << "   Type: " << typeid(e).name() << std::endl
            << std::endl;
        return 1;
    }
    catch(...)
    {
        std::cerr << "Unknown exception in doxygen_xml2qbk" 
            << std::endl;
        return 1;
    }
    return 0;
}
Exemple #7
0
int main(int argc, char* argv[])
{
	if ((argc == 2) && (strcmp(argv[1], "-v") == 0)) {
//		printf("Server Version: MsgServer/%s\n", VERSION);
		printf("Server Build: %s %s\n", __DATE__, __TIME__);
		return 0;
	}

	signal(SIGPIPE, SIG_IGN);
	srand(time(NULL));

	log("MsgServer max files can open: %d ", getdtablesize());

	CConfigFileReader config_file("msgserver.conf");

	char* listen_ip = config_file.GetConfigName("ListenIP");
	char* str_listen_port = config_file.GetConfigName("ListenPort");
	char* ip_addr1 = config_file.GetConfigName("IpAddr1");	// 电信IP
	char* ip_addr2 = config_file.GetConfigName("IpAddr2");	// 网通IP
	char* str_max_conn_cnt = config_file.GetConfigName("MaxConnCnt");
    char* str_aes_key = config_file.GetConfigName("aesKey");
	uint32_t db_server_count = 0;
	serv_info_t* db_server_list = read_server_config(&config_file, "DBServerIP", "DBServerPort", db_server_count);

	uint32_t login_server_count = 0;
	serv_info_t* login_server_list = read_server_config(&config_file, "LoginServerIP", "LoginServerPort", login_server_count);

	uint32_t route_server_count = 0;
	serv_info_t* route_server_list = read_server_config(&config_file, "RouteServerIP", "RouteServerPort", route_server_count);

    uint32_t push_server_count = 0;
    serv_info_t* push_server_list = read_server_config(&config_file, "PushServerIP",
                                                       "PushServerPort", push_server_count);
    
    uint32_t file_server_count = 0;
    serv_info_t* file_server_list = read_server_config(&config_file, "FileServerIP",
                                                       "FileServerPort", file_server_count);
    
    if (!str_aes_key || strlen(str_aes_key)!=32) {
        log("aes key is invalied");
        return -1;
    }
 
    pAes = new CAes(str_aes_key);
    
	// 必须至少配置2个BusinessServer实例, 一个用于用户登录业务,一个用于其他业务
	// 这样当其他业务量非常繁忙时,也不会影响客服端的登录验证
	// 建议配置4个实例,这样更新BusinessServer时,不会影响业务
	if (db_server_count < 2) {
		log("DBServerIP need 2 instance at lest ");
		return 1;
	}

	// 到BusinessServer的开多个并发的连接
	uint32_t concurrent_db_conn_cnt = DEFAULT_CONCURRENT_DB_CONN_CNT;
	uint32_t db_server_count2 = db_server_count * DEFAULT_CONCURRENT_DB_CONN_CNT;
	char* concurrent_db_conn = config_file.GetConfigName("ConcurrentDBConnCnt");
	if (concurrent_db_conn) {
		concurrent_db_conn_cnt  = atoi(concurrent_db_conn);
		db_server_count2 = db_server_count * concurrent_db_conn_cnt;
	}

	serv_info_t* db_server_list2 = new serv_info_t [ db_server_count2];
	for (uint32_t i = 0; i < db_server_count2; i++) {
		db_server_list2[i].server_ip = db_server_list[i / concurrent_db_conn_cnt].server_ip.c_str();
		db_server_list2[i].server_port = db_server_list[i / concurrent_db_conn_cnt].server_port;
	}

	if (!listen_ip || !str_listen_port || !ip_addr1) {
		log("config file miss, exit... ");
		return -1;
	}

	// 没有IP2,就用第一个IP
	if (!ip_addr2) {
		ip_addr2 = ip_addr1;
	}

	uint16_t listen_port = atoi(str_listen_port);
	uint32_t max_conn_cnt = atoi(str_max_conn_cnt);

	int ret = netlib_init();

	if (ret == NETLIB_ERROR)
		return ret;

	CStrExplode listen_ip_list(listen_ip, ';');
	for (uint32_t i = 0; i < listen_ip_list.GetItemCnt(); i++) {
		ret = netlib_listen(listen_ip_list.GetItem(i), listen_port, msg_serv_callback, NULL);
		if (ret == NETLIB_ERROR)
			return ret;
	}

	printf("server start listen on: %s:%d\n", listen_ip, listen_port);

	init_msg_conn();

    init_file_serv_conn(file_server_list, file_server_count);

	init_db_serv_conn(db_server_list2, db_server_count2, concurrent_db_conn_cnt);

	init_login_serv_conn(login_server_list, login_server_count, ip_addr1, ip_addr2, listen_port, max_conn_cnt);

	init_route_serv_conn(route_server_list, route_server_count);

    init_push_serv_conn(push_server_list, push_server_count);
	printf("now enter the event loop...\n");
    
    writePid();

	netlib_eventloop();

	return 0;
}
Exemple #8
0
int main(int argc, char *argv[])
{
    try {
        if(argc<=1) {
            const std::string path(argv[0]);
            std::cout << "usage: " << path.substr(path.find_last_of("/\\") + 1) <<
R"_help_( <parameters> input_dir

<parameters> include:
    --device=<name>
        name of dynamic library (without suffix) with computational device
        to be used for demo
    --batch=<value>
        size of group of images that are classified together;  large batch
        sizes have better performance
    --model=<name>
        name of network model that is used for classfication
        can be: caffenet_float,  caffenet_int16 or lenet_float
    --training
        Run a training mode of selected model (default is classification)
    --input=<directory>
        path to directory that contains images to be classfied
    --config=<name>
        file name of config file containing additional parameters
        command line parameters take priority over config ones

If last parameters do not fit --key=value format it is assumed to be a --input.
Instead of "--" "-" or "/" can be used.
)_help_";
            return 0;
        }

        // convert argc/argv to vector of arguments
        std::vector<std::string> arg;
        for(int n=1; n<argc; ++n) arg.push_back(argv[n]);

        // parse configuration (command line and from file)
        using config_t = std::map<std::string, std::string>;
        config_t config;
        parse_parameters(config, arg);
        { // find if config file name was given from commandline
            config_t::iterator it;
            if((it = config.find("config"))!=std::end(config)){
                std::ifstream config_file(it->second);
                std::vector<std::string> config_lines;
                using istream_it = std::istream_iterator<std::string>;
                std::copy(istream_it(config_file), istream_it(), std::back_inserter(config_lines));
                parse_parameters(config, config_lines);
            }
        }
        { // validate & add defalut value for missing arguments
          // default device is device_cpu  its default batch is 48
          // if other devices (gpu or int16) are given its default batch is 32
            auto not_found = std::end(config);
            if(config.find("device")==not_found)
            {
                config["device"]="device_cpu";
                if(config.find("batch") ==not_found) config["batch"]="48";
            }
            else 
            {  
                if( config.find("batch") == not_found)
                {
                    config["batch"] = (config["device"] == "device_cpu" ? "48" : "32");
                }
            }
            if(config.find("model") ==not_found) config["model"]="caffenet_float";
            if(config.find("input") ==not_found) throw std::runtime_error("missing input directory; run without arguments to get help");
            if(config.find("loops") ==not_found) config["loops"]="1";
        }


        // RAII for loading library, device initialization and opening interface 0
        scoped_library      library(config["device"]+dynamic_library_extension);
        scoped_device       device(library);
        scoped_interface_0  interface_0(device);

        std::string builder_desc(config["model"]);

        // If training is to happen then builder of training should be chosen
        if( config.find("training") != std::end(config))
        {
            builder_desc += "_training"; 
        }
        // get workflow builder as specified by model parameter
        auto builder = workflow_builder::instance().get(builder_desc);

        const int config_batch = std::stoi(config["batch"]);

        if(config_batch<=0) throw std::runtime_error("batch_size is 0 or negative");
        nn_workflow_t *workflow = builder->init_workflow(&interface_0);

        // compiling workload
        NN_WORKLOAD_DATA_TYPE input_format; 

        // lenet topology works with MNIST so input is 2D greyscaled images
        if( config["model"].compare("lenet_float") == 0 )
        {
            input_format = NN_WORKLOAD_DATA_TYPE_F32_2D_BATCH;
        } 
        else
        {
            input_format = NN_WORKLOAD_DATA_TYPE_F32_ZXY_BATCH;
        }
        NN_WORKLOAD_DATA_TYPE output_format = NN_WORKLOAD_DATA_TYPE_F32_1D_BATCH;
        nn_workload_t *workload = nullptr;
        C_time_control timer;
        auto status = interface_0.workflow_compile_function(&workload, interface_0.device, workflow, &input_format, &output_format, config_batch);
        timer.tock();
        if(!workload) throw std::runtime_error("workload compilation failed");
        std::cout << "workload compiled in " << timer.time_diff_string() <<" [" <<timer.clocks_diff_string() <<"]" << std::endl;

        if( config.find("training") == std::end(config))
        {
            //TODO: currently lenet model comes to use mnist database for training/testing
            // so It could be changed to recgonize digits from regular images
            if( config["model"].compare("lenet_float") == 0 )
            {
                run_mnist_classification(library,device,interface_0,workload,builder,argv,config,config_batch);
            } else
            {
                run_images_classification(library,device,interface_0,workload,builder,argv,config,config_batch);
            }
        } else {
            if( config["model"].compare("lenet_float") == 0 )
            {
                run_mnist_training(library,device,interface_0,workload,builder,argv,config,config_batch);
            } else {
                printf("TODO: :)\n");
            }
        }

    return 0;
    }
Exemple #9
0
int main(int argc, char* argv[])
{

    pid_t pid = fork();
    if (pid < 0) {
        exit(-1);
    } else if (pid > 0) {
        exit(0);
    }
    setsid();


	if ((argc == 2) && (strcmp(argv[1], "-v") == 0)) {
		printf("Server Version: FileServer/%s\n", VERSION);
		printf("Server Build: %s %s\n", __DATE__, __TIME__);
		return 0;
	}

	signal(SIGPIPE, SIG_IGN);

	CConfigFileReader config_file("fileserver.conf");

	char* listen_ip = config_file.GetConfigName("Address");
	char* str_listen_port = config_file.GetConfigName("ListenPort");
    char* str_task_timeout = config_file.GetConfigName("TaskTimeout");

	if (!listen_ip || !str_listen_port) {
		log("config item missing, exit...\n");
		return -1;
	}

	uint16_t listen_port = atoi(str_listen_port);
    uint32_t task_timeout = atoi(str_task_timeout);

    CStrExplode listen_ip_list(listen_ip, ';');
    std::list<svr_ip_addr_t> q;
    for (uint32_t i = 0; i < listen_ip_list.GetItemCnt(); i++) {
    	svr_ip_addr_t t(listen_ip_list.GetItem(i), listen_port);
    	q.push_back(t);
    }
	init_file_conn(q, task_timeout);
	int ret = netlib_init();

	if (ret == NETLIB_ERROR)
		return ret;


//	for (uint32_t i = 0; i < listen_ip_list.GetItemCnt(); i++) {
		ret = netlib_listen("0.0.0.0"/*"127.0.0.1"*/, /*listen_ip_list.GetItem(i), */listen_port, file_serv_callback, NULL);
		if (ret == NETLIB_ERROR) {
			printf("Failed to listen on port %d\n", listen_port);
			log("Failed to listen on port %d\n", listen_port);
			return ret;
		}
//	}

	printf("server start listen on %s:%d\n", listen_ip, listen_port);
	printf("now enter the event loop...\n");

	netlib_eventloop();

	printf("exiting.......\n");
	log("exit\n");

	return 0;
}
// Refactor?
void SlideshowController::parse_config_file(QString file_path)
{
  QFile config_file(file_path);
  if (config_file.open(QIODevice::ReadOnly))
    {
      QTextStream stream(&config_file);

      // separate keys from values
      while (!stream.atEnd())
        {
          QString line;
          QString key, value_str;
          int line_index;
          int value_int;

          line = stream.readLine();

          // Check if line is a comment line
          if (line.at(0) == '#')
            {
              line = stream.readLine();
            }
          line_index = 0;
          while (line_index < line.size() && line.at(line_index) != '=')
            {
              key.append(line.at(line_index));
              ++line_index;
            }
          ++line_index;
          while (line_index < line.size())
            {
              value_str.append(line.at(line_index));
              ++line_index;
            }

          // update config settings
          if (key == "display_timer_interval")
            {
              bool value_is_integer;
              value_int = value_str.toInt(&value_is_integer);
              if (value_is_integer && value_int > 0)
                {
                  slideshow_data_model_->
                      set_main_timer_interval(value_int);
                }
              else
                {
                  warn_config_error(key, value_str);
                }
            }
          else if (key == "marketing_timer_interval")
            {
              bool value_is_integer;
              value_int = value_str.toInt(&value_is_integer);
              if (value_is_integer && value_int > 0)
                {
                  slideshow_data_model_->
                      set_marketing_timer_interval(value_int);
                }
              else
                {
                  warn_config_error(key, value_str);
                }
            }
          else if (key == "fullscreen_disabled")
            {
              bool value_is_integer;
              value_int = value_str.toInt(&value_is_integer);
              if (value_is_integer && value_int >= 0)
                {
                  slideshow_data_model_->set_fullscreen_disabled(value_int);
                }
              else
                {
                  warn_config_error(key, value_str);
                }
            }
          else if (key == "video_disabled")
            {
              bool value_is_integer;
              value_int = value_str.toInt(&value_is_integer);
              if (value_is_integer && value_int >= 0)
                {
                  slideshow_data_model_->set_video_disabled(value_int);
                }
              else
                {
                  warn_config_error(key, value_str);
                }
            }
          else if (key == "main_slide_order")
            {
              bool value_is_integer;
              value_int = value_str.toInt(&value_is_integer);
              if (value_is_integer && value_int >= 0)
                {
                  slideshow_data_model_->slideshow_queue()->
                      set_main_order((QueueSortOrder) value_int);
                }
              else
                {
                  warn_config_error(key, value_str);
                }
            }
            else if (key == "marketing_slide_order")
              {
                bool value_is_integer;
                value_int = value_str.toInt(&value_is_integer);
                if (value_is_integer && value_int >= 0)
                  {
                    slideshow_data_model_->slideshow_queue()->
                        set_marketing_order((QueueSortOrder) value_int);
                  }
                else
                  {
                    warn_config_error(key, value_str);
                  }
            }
          else if (key == "marketing_playback_option")
            {
              bool value_is_integer;
              value_int = value_str.toInt(&value_is_integer);
              if (value_is_integer && value_int >= 0)
                {
                  slideshow_data_model_->slideshow_queue()->
                      set_marketing_option((MarketingPlaybackOption) value_int);
                }
              else
                {
                  warn_config_error(key, value_str);
                }
          }
          else if (key == "begin_on_marketing_slide")
            {
              bool value_is_integer;
              value_int = value_str.toInt(&value_is_integer);
              if (value_is_integer && value_int >= 0)
                {
                  slideshow_data_model_->set_begin_on_marketing(value_int);
                }
              else
                {
                  warn_config_error(key, value_str);
                }
            }
          else if (key == "init_delay")
            {
              bool value_is_integer;
              value_int = value_str.toInt(&value_is_integer);
              if (value_is_integer && value_int >= 0)
                {
                  slideshow_data_model_->set_init_delay(value_int);
                }
              else
                {
                  warn_config_error(key, value_str);
                }
            }
          else if (key == "indiv_info_interval")
            {
              bool value_is_integer;
              value_int = value_str.toInt(&value_is_integer);
              if (value_is_integer && value_int >= 0)
                {
                  slideshow_data_model_->
                      set_indiv_info_slide_interval(value_int);
                }
              else
                {
                  warn_config_error(key, value_str);
                }
            }
        }
      config_file.close();
    }
}
Exemple #11
0
bool gr_dumper::dump_platform( std::string _path, gr_dump_format_e _format)
{
	bool retval = false;
	unsigned int i = 0;
	
	boost::filesystem::path _boost_path( _path.c_str());
	boost::filesystem::create_directory( _boost_path);
	
	std::vector< unsigned int> ids = g_gr_device_container.get_all_data_ids();

	std::stringstream ss;
	ss << _path << "/platform.txt";
	
	std::basic_ofstream<char> file( ss.str().c_str(), std::ios_base::out);
	
	try {
		if( file.is_open() )
		{    
			file << "##########\n"
				<< "# This file lists configuration files for the entire platform.\n"
				<< "# Each file represents a single device in the platform.\n"
				<< "# This allows a flexible, auto-generated system, that is easy to maintain.\n"
				<< "##########\n";
			
			for( i = 0; i < ids.size(); i++)
			{
				ss.str("");
				ss << g_gr_device_container.get_data_key( ids[i]) << " = "
					<< g_gr_device_container.get_data_key( ids[i]) << ".txt\n";
				file << ss.str().c_str();
			}
			file << "\n";
			file.close();
			
		} else {
			std::stringstream ss;
			ss << "File not found.\n";
			GR_FORCE_WARNING( ss.str().c_str());
		}
	} catch( ... ) {
		std::stringstream ss;
		ss << "File is missing or has invalid structure.\n";
		GR_FORCE_WARNING( ss.str().c_str());
	}

	for( i = 0; i < ids.size(); i++)
	{
		ss.str("");
		ss << _path << "/" << g_gr_device_container.get_data_key( ids[i]) << ".txt";
		std::basic_ofstream<char> config_file( ss.str().c_str(), std::ios_base::out);
		try {
			if( config_file.is_open() )
			{    
				static_cast< gs::reg::device *>(g_gr_device_container.get_data( ids[i]))->gr_dump( _format, config_file, 0);
				retval = true;
				config_file.close();
			} else {
				std::stringstream ss;
				ss << "File not found.\n";
				GR_FORCE_WARNING( ss.str().c_str());
			}
		} catch( ... ) {
			std::stringstream ss;
			ss << "File is missing or has invalid structure.\n";
			GR_FORCE_WARNING( ss.str().c_str());
		}
	}

	return( retval);
}
Exemple #12
0
int main( ) {

    std::string input_dir = "Input/";

    // Read Nucleus File
    std::string nucleus_string;
    std::ifstream nucleus_file( "domgen.config" );

    nucleus_file >> nucleus_string;

    nucleus_file.close();
    nucleus_file.clear();

    // Read Configuration file
    std::string config_filename = nucleus_string + ".config";
    std::ifstream config_file( config_filename.c_str() );

    std::string parameters_string;

    int fit_ph;
    double rmax;
    int rpts;
    int lmax;

    config_file >> parameters_string >> fit_ph;
    config_file >> rmax >> rpts >> lmax;

    int num_lj;
    config_file >> num_lj;

    // These maps hold the number of bound states for each lj
    std::map<std::string, int> n_lj_map; // neutrons
    std::map<std::string, int> p_lj_map; // protons
    std::vector< std::map< std::string, int > > map_vec;
    for ( int n = 0; n < num_lj; ++n ) {

        std::string key;
        int n_num_bound, p_num_bound;
        config_file >> key >> n_num_bound >> p_num_bound;

        std::pair< std::map< std::string, int >::iterator, bool > n_ret;
        std::pair< std::map< std::string, int >::iterator, bool > p_ret;
        n_ret = n_lj_map.insert ( std::make_pair( key, n_num_bound ) );
        p_ret = p_lj_map.insert ( std::make_pair( key, p_num_bound ) );

        if ( n_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << n_ret.first->second << std::endl;
        }

        if ( p_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << p_ret.first->second << std::endl;
        }
    }

    map_vec.push_back( n_lj_map );
    map_vec.push_back( p_lj_map );

    config_file.close();
    config_file.clear();

    bool hole;
    if ( fit_ph == 0 ) hole = true;
    else hole = false;

    std::string output_dir = "Output_" + parameters_string + "/Output_domgen/";
    std::string parameters_filename = parameters_string + ".inp";

    std::cout << "rmax = " << rmax << std::endl;
    std::cout << "rpts = " << rpts << std::endl;
    std::cout << "lmax = " << lmax << std::endl;

    std::string n_string = "n" + nucleus_string;
    std::string p_string = "p" + nucleus_string;

    std::string n_filename = input_dir + n_string + ".inp";
    std::string p_filename = input_dir + p_string + ".inp";

    // Create Nuclear Parameter Objects
    NuclearParameters Nu_n = read_nucleus_parameters( n_filename );
    NuclearParameters Nu_p = read_nucleus_parameters( p_filename );

    std::vector< NuclearParameters > Nu_vec;
    Nu_vec.push_back( Nu_n );
    Nu_vec.push_back( Nu_p );

    // Read in DOM parameters
    std::ifstream pfile( parameters_filename.c_str() );
    if ( pfile.is_open() !=1 ) {
        std::cout << "could not open file " << parameters_filename << std::endl;
        std::abort();
    }
    pfile.close();
    pfile.clear();

    // Create radial grid
    std::vector<double> rmesh;
    double rdelt = rmax / rpts;
    for( int i = 0; i < rpts; ++i ) {

        rmesh.push_back( ( i + 0.5 ) * rdelt );
        
    }

    // Prepare stuff for output files
    std::vector< std::string > np_strings;
    np_strings.push_back( n_string );
    np_strings.push_back( p_string );

    std::string L_array[8] = { "s", "p", "d", "f", "g", "h", "i", "j" };
    std::string J_array[8] = { "1", "3", "5", "7", "9", "11", "13", "15" };

    //Potential specifications
    int type = 1; // 1 is P.B. form (average), 0 is V.N. form
    int mvolume = 4;
    int AsyVolume = 1;

    /* CALCULATIONS */

    // Loop over protons and neutrons
    double Zp; // number of protons in projectile
    for ( unsigned int nu = 1; nu < 2; ++nu ) {
    //for ( unsigned int nu = 0; nu < Nu_vec.size(); ++nu ) {
        
        double tz = nu - 0.5; // +0.5 for protons, -0.5 for neutrons
        std::map< std::string, int > lj_map = map_vec[nu];
        if ( tz < 0 ) Zp = 0;
        else Zp = 1;

        // Nucleus Object
        const NuclearParameters &Nu = Nu_vec[nu];

        // Construct Parameters Object
        Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, Zp );

        // Construct Potential Object
        pot U = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
        pot *U1 = &U;

        // Construct boundRspace Object
        boundRspace B( rmax, rpts, Nu.Ef, Nu.ph_gap, lmax, Nu.Z, Zp, Nu.A, U1 );

        double tol = 0.01;
        std::vector< lj_eigen_t > bound_levels = 
            B.get_bound_levels( rmesh, tol );

        // Output Files
        std::string qp_filename = output_dir + np_strings[nu] 
                                + "_quasiparticle" + ".test";
        std::ofstream qp_file( qp_filename.c_str() );

        // Loop over lj channels
        for ( int l = 0; l < lmax + 1; ++l ) {

            for( int up = -1; up < 2; up+=2 ) {

                double xj = l + up / 2.0;
                int j_index = ( up - 1 ) / 2;
                if ( xj < 0 ) continue;

                int index = B.index_from_LJ( l, xj );
                std::vector< eigen_t > &bound_info = bound_levels[index];

                double lp; 
                if ( xj > l ) lp = l;
                else lp = - l - 1;
                
                std::string j_string;
                if ( l == 0 ) j_string = J_array[ l ];
                else j_string = J_array[ l + j_index ];

                std::string lj_string = L_array[l] + j_string + "2";

                /* QUASIPARTICLE AND QUASIHOLE INFORMATION */

                // Find self-consistent solutions

                // loop over the orbitals and write out the 
                // bound state information to a file
                int intj = static_cast<int>( 2 * xj );
                for ( unsigned int N = 0; N < bound_info.size(); ++N ) {

                    std::string level_str = util::IntToStr( N ) + L_array[l] 
                                          + j_string + "2";

                    std::string wfx_filename = output_dir + np_strings[nu] 
                        + "_" + level_str + ".wfx";
                    std::ofstream wfx_file( wfx_filename.c_str() );

                    // Quasiparticle energy
                    double QPE = bound_info[N].first; 

                    // Quasiparticle wavefunction
                    std::vector<double> &QPF = bound_info[N].second;
                    double S = B.sfactor( rmesh, QPE, l, xj, QPF );

                    qp_file << N << L_array[l] << intj << "/2" 
                            << " " << QPE << " " << S << std::endl;

                    // Write out wavefunctions to a file
                    for ( unsigned int i = 0; i < rmesh.size(); ++i ) {
                        
                        wfx_file << rmesh[i] << " " << QPF[i] << std::endl;

                    }

                    wfx_file.close();
                    wfx_file.clear();

                } // end loop over N 

            } //end loop over j
        } // end loop over l

        qp_file.close();
        qp_file.clear();

    } // end loop over Nu_vec

    return 1;
}
int main(int argc, char* argv[])
{
	if ((argc == 2) && (strcmp(argv[1], "-v") == 0)) {
		printf("Server Version: DBProxyServer/%s\n", VERSION);
		printf("Server Build: %s %s\n", __DATE__, __TIME__);
		return 0;
	}

	signal(SIGPIPE, SIG_IGN);
	srand(time(NULL));

	CacheManager* pCacheManager = CacheManager::getInstance(CONFIGFILE_NAME);
	if (!pCacheManager) {
		log("CacheManager init failed");
		return -1;
	}

	CDBManager* pDBManager = CDBManager::getInstance(CONFIGFILE_NAME);
	if (!pDBManager) {
		log("DBManager init failed");
		return -1;
	}

	// 主线程初始化单例,不然在工作线程可能会出现多次初始化
	if (!CAudioModel::getInstance()) {
		return -1;
	}
    
    if (!CGroupMessageModel::getInstance()) {
        return -1;
    }
    
    if (!CGroupModel::getInstance()) {
        return -1;
    }
    
    if (!CMessageModel::getInstance()) {
        return -1;
    }

	if (!CSessionModel::getInstance()) {
		return -1;
	}
    
    if(!CRelationModel::getInstance())
    {
        return -1;
    }
    
    if (!CUserModel::getInstance()) {
        return -1;
    }
    
    if (!CFileModel::getInstance()) {
        return -1;
    }


	CConfigFileReader config_file(CONFIGFILE_NAME);

	char* listen_ip		  = config_file.GetConfigName("ListenIP");
	char* str_listen_port = config_file.GetConfigName("ListenPort");
	char* str_thread_num  = config_file.GetConfigName("ThreadNum");
    char* str_file_site   = config_file.GetConfigName("MsfsSite");
    char* str_aes_key     = config_file.GetConfigName("aesKey");

	if (!listen_ip || !str_listen_port || !str_thread_num || !str_file_site || !str_aes_key) {
		log("missing ListenIP/ListenPort/ThreadNum/MsfsSite/aesKey, exit...");
		return -1;
	}
    
    if(strlen(str_aes_key) != 32)
    {
        log("aes key is invalied");
        return -2;
    }
    string strAesKey(str_aes_key, 32);
    CAes cAes = CAes(strAesKey);
    string strAudio = "[语音]";
    char* pAudioEnc;
    uint32_t nOutLen;
    if(cAes.Encrypt(strAudio.c_str(), strAudio.length(), &pAudioEnc, nOutLen) == 0)
    {
        strAudioEnc.clear();
        strAudioEnc.append(pAudioEnc, nOutLen);
        cAes.Free(pAudioEnc);
    }

	uint16_t listen_port = atoi(str_listen_port);
	uint32_t thread_num = atoi(str_thread_num);
    
    string strFileSite(str_file_site);
    CAudioModel::getInstance()->setUrl(strFileSite);

	int ret = netlib_init();

	if (ret == NETLIB_ERROR)
		return ret;
    
    /// yunfan add 2014.9.28
    // for 603 push
    curl_global_init(CURL_GLOBAL_ALL); //初始化libcurl,CURL_GLOBAL_ALL初始化所有可能的调用
    /// yunfan add end

	init_proxy_conn(thread_num);
    CSyncCenter::getInstance()->init();
    CSyncCenter::getInstance()->startSync();

	CStrExplode listen_ip_list(listen_ip, ';');
	for (uint32_t i = 0; i < listen_ip_list.GetItemCnt(); i++) {
		ret = netlib_listen(listen_ip_list.GetItem(i), listen_port, proxy_serv_callback, NULL);
		if (ret == NETLIB_ERROR)
			return ret;
	}

	printf("server start listen on: %s:%d\n", listen_ip,  listen_port);
	printf("now enter the event loop...\n");
    writePid();
	netlib_eventloop(10);

	return 0;
}
Exemple #14
0
int main(int argc, char** argv)
{

	/*
	 * Define options for argument list
	 */
	boost::program_options::variables_map vm;
	boost::program_options::options_description desc("MessageCentre Options");
	boost::program_options::options_description conf("Configuration Options");
	boost::program_options::options_description all("All Options");

    /*
     * Define message centre
     */
	MessageCentre mc;

	/*
	 * Wrangle arguments
	 */
	conf.add_options()
			( "config,c", boost::program_options::value<std::string>(),"Configuration file." );

	desc.add_options()
			( "help,h", "Display help message" )
			( "global.servername", boost::program_options::value<std::string>(), "Server name.")
			( "global.hostid", boost::program_options::value<std::string>(), "Unique host/server identification.")
			( "global.logdir", boost::program_options::value<std::string>(), "Directory for logs")
			( "global.rundir", boost::program_options::value<std::string>(), "Directory for runtime files.")
			( "discovery.broker", boost::program_options::value<std::string>()->notifier(boost::bind(&MessageCentre::setBroker,&mc,_1)),"Discovery service URL.")

			;

	/*
	 * Group it up into an All option
	 */
	all.add(conf).add(desc);

	/*
	 * Finding the configuration
	 */
    boost::filesystem::path config_file_path;
    bool config_found = false;


	try
	{
		/*
		 * First we check the command line arguments in case a config file is
		 * passed ... so we can try it first
		 */
		boost::program_options::store(
				boost::program_options::parse_command_line(argc,argv,all),
				vm
				);

		/*
		 * Special Case  : Help
		 */
		if( vm.count("help") )
		{
			std::cout << all << std::endl;
			return 0;
		}

		/*
		 * Special Case : config file passed via command line
		 */
		if ( vm.count("config") )
		{
			config_file_path = vm["config"].as<std::string>();
		}


		/*
		 * First Check: Command line configuration file
		 */
		if( ! config_file_path.empty() )
		{
		    std::cout << "Specified configuration : " << config_file_path.string() << " ... ";
		    if ( boost::filesystem::is_regular_file(config_file_path) )
		    {
		    	std::cout << "Accepted." << std::endl;
		    	config_found = true;
		    }
		    else
		    {
		    	std::cout << std::endl << "Specified configuration was not present.  Refusing to continue." << std::endl;
		    	return 1;
		    }
		}

		/*
	     * Second Check: Home directory conf, takes precedence
	     * HOME_CONF = $HOME/.gorgon.conf
	     */
		if( ! config_found )
		{
		    config_file_path = HOME_CONF;
		    std::cout << "Searching configuration : " << config_file_path.string() << " ... ";
		    if ( boost::filesystem::is_regular_file(config_file_path) )
		    {
		    	std::cout << "Accepted.";
		    	config_found = true;
		    }
		    std::cout << std::endl;
		}

	    /*
	     * Third Check: Prefix etc directory
	     * DIST_DIR = $PREFIX/etc/gorgon.conf
	     */
	    if ( ! config_found )
	    {
	    	config_file_path = DIST_CONF;
	    	std::cout << "Searching configuration : " << config_file_path.string() << " ... ";
	    	if ( boost::filesystem::is_regular_file(config_file_path) )
	    	{
	    		std::cout << "Accepted.";
	    		config_found = true;
	    	}
	    	std::cout << std::endl;
	    }

	    /*
	     * Last Resort : check current directory for file
	     * ./gorgon.conf
	     */
	    if ( ! config_found )
	    {
	    	config_file_path = "gorgon.conf";
	    	std::cout << "Searching configuration : " << config_file_path.string() << " ... ";
	    	if ( boost::filesystem::is_regular_file(config_file_path) )
	    	{
	    		std::cout << "Accepted.";
	    		config_found = true;
	    	}
	    	std::cout << std::endl;
	    }

	    /*
	     * If we can't find the config, bail out.  The configuration potential is too complicated
	     * to try and wrangle it just by the CLI alone.
	     */
	    if ( ! config_found )
	    {
	    	std::cout << "No configuration found, aborting!" << std::endl;
	    	return 1;
	    }


	    /*
	     * Wrangle the rest of the configuration
	     */
	    std::ifstream config_file(config_file_path.string());
	    boost::program_options::store(
	    		boost::program_options::parse_config_file(config_file, desc, true),
	    		vm
	    		);

	    boost::program_options::notify(vm);

	    std::cout << "----------------------------" << std::endl;
	    std::cout << "SERVER_VERSION   : " << SERVER_VERSION << std::endl;
	    std::cout << "SERVER_SIGNATURE : " << SERVER_SIGNATURE << std::endl;
	    std::cout << "BUILD_UNAME      : " << BUILD_UNAME << std::endl;
	    std::cout << "BUILD_USER       : "******"BUILD_HOST       : " << BUILD_HOST << std::endl;
	    std::cout << "BUILD_NUM        : " << BUILD_NUM << std::endl;
	    std::cout << "SERVER_SIG       : " << mc.getServerSignature() << std::endl;
	    std::cout << "----------------------------" << std::endl;
		std::cout << mc.getServerSignature() << std::endl;


	}
	catch( const std::exception& ex )
	{
		std::cout << "ERROR: " << ex.what() << std::endl;
		return 2;
	}

}
Exemple #15
0
/*
	Entry point
*/
int main(int argc, char** argv)
{

	std::ifstream config_file("metaserver-ng.conf");
	boost::asio::io_service io_service;
	boost::program_options::variables_map vm;

	int port = 8453;
	std::string ip = "0.0.0.0";

	/**
	 * Argument Wrangling
	 *
	 * Note: not exactly the most friendly option parsing I've seen
	 */
	boost::program_options::options_description desc( "MetaServer Configuration" );

	/**
	 * Note: options inside the configuration file that are NOT listed here
	 *       become ignored and are not accessible.
	 */
	desc.add_options()
		( "help,h", "Display help message" )
		( "server.port,p", boost::program_options::value<int>(), "Server bind port. \nDefault:8543" )
		( "server.ip", boost::program_options::value<std::string>(), "Server bind IP. \nDefault:0.0.0.0" )
		( "server.daemon", boost::program_options::value<std::string>(), "Daemonize after startup [true|false].\nDefault: true" )
		( "server.logfile", boost::program_options::value<std::string>(), "Server logfile location.\nDefault: ~/.metaserver-ng/metaserver-ng.log" )
		( "server.client_stats", boost::program_options::value<std::string>(), "Keep internals stats [true|false].  This can affect performance.\nDefault: false" )
		( "server.server_stats", boost::program_options::value<std::string>(), "Keep internals stats [true|false].  This can affect performance.\nDefault: false" )
		( "logging.server_sessions", boost::program_options::value<std::string>(), "Output server sessions to logfile [true|false].  \nDefault: false" )
		( "logging.client_sessions", boost::program_options::value<std::string>(), "Output client sessions to logfile [true|false].  \nDefault: false" )
		( "logging.packet_logging", boost::program_options::value<std::string>(), "Output all packets to logfile [true|false].  \nDefault: false" )
		( "logging.packet_logfile", boost::program_options::value<std::string>(), "Packet logfile location.\nDefault: ~/.metaserver-ng/packetlog.bin" )
		( "security.auth_scheme", boost::program_options::value<std::string>(), "What method of authentication to use [none|server|delegate|both].\nDefault: none" )
		( "performance.max_server_sessions", boost::program_options::value<int>(), "Max number of server sessions [1-32768].\nDefault: 1024" )
		( "performance.max_client_sessions", boost::program_options::value<int>(), "Max number of client sessions [1-32768].\nDefault: 4096")
		( "performance.server_session_expiry_seconds", boost::program_options::value<int>(), "Expiry in seconds for server sessions [300-3600].\nDefault: 300" )
		( "performance.client_session_expiry_seconds", boost::program_options::value<int>(), "Expiry in seconds for client sessions [300-3600].\nDefault: 300" )
			;

	/**
	 * Create our metaserver
	 */
	MetaServer ms(io_service);

	try
	{

		boost::program_options::store(
				boost::program_options::parse_command_line(argc, argv, desc),
				vm
				);
		boost::program_options::store(
				boost::program_options::parse_config_file(config_file, desc, true),
				vm
				);

		boost::program_options::notify(vm);

		/**
		 * Special case for help
		 */
		if ( vm.count("help") )
		{
			std::cout << desc << std::endl;
			return 1;
		}

		/**
		 * The only real options that we need to process outside of the
		 * metaesrver as it affects the handlers
		 */
		if ( vm.count("server.port") )
			port=vm["server.port"].as<int>();

		if ( vm.count("server.ip") )
			ip=vm["server.ip"].as<std::string>();

		/**
		 * Register the configuration.
		 */
		ms.registerConfig(vm);

		/**
		 * Go daemon if needed
		 */
		if ( ms.isDaemon() )
		{
			ms.getLogger().info("Running as a daemon");
			daemon(0,0);
		}

		/**
		 * Define Handlers
		 */
		//MetaServerHandlerTCP tcp(ms, io_service, ip, port);
		MetaServerHandlerUDP udp(ms, io_service, ip, port);

		/**
		 * This is the async loop
		 */
		for(;;)
		{
			try
			{
				/*
				 * We run and complete normally
				 */
				io_service.run();
				break;
			}
			catch(std::exception ex)
			{
				/*
				 * This will catch exceptions inside the io_service loop/handler.
				 *
				 * If we have a handler exception this should account as a reasonable
				 * effort to resume operation despite the error
				 */
				std::cerr << "IOService Loop Exception:" << ex.what() << std::endl;
			}
		}

	}
	catch (std::exception& e)
	{
		/*
		 * This will catch exceptions during the startup etc
		 */
		std::cerr << "Exception: " << e.what() << std::endl;
	}
	std::cout << "All Done!" << std::endl;
	return 0;
}
int main(int argc, const char ** argv) {
	auto start = std::chrono::high_resolution_clock::now();

	std::cout << "MSAcquisitionSimulator Version " << MSAcquisitionSimulator_VERSION_MAJOR << "." << MSAcquisitionSimulator_VERSION_MINOR << "." << MSAcquisitionSimulator_VERSION_PATCH << std::endl;
	std::cout << "AcquisitionSimulator Version " << AcquisitionSimulator_VERSION_MAJOR << "." << AcquisitionSimulator_VERSION_MINOR << "." << AcquisitionSimulator_VERSION_PATCH << std::endl;

	std::string sqlite_in_path;
	std::string mzml_out_path;
	std::string param_file_path;
	std::string fido_out_path;
	std::string fasta_in_path;
	std::string target_decoy_out_path;
	std::string acquisition_algorithm_name;

	std::vector<std::string> acquisition_param_values;

	double ms1_scan_time;
	double ms2_scan_time;
	double scan_overhead_time;
	int acquisition_length;

	double elution_tau;
	double elution_sigma;

	double resolution;
	double dynamic_range;

	double db_search_min_mass;
	double db_search_max_mass;
	double db_search_mass_tolerance;
	int db_search_max_missed_cleavages;
	int db_search_max_dynamic_mods;
	int db_search_min_enzymatic_termini;
	double null_lambda;

	double max_ms1_injection_time;
	double max_ms2_injection_time;
	double ms1_target_total_ion_count;
	double ms2_target_total_ion_count;

	std::vector<DBPTM> PTMs;
	std::vector<DBEnzyme> enzymes;


	//region Command line specification
	boost::program_options::options_description general("USAGE: AcquisitionSimulator [options] ground_truth.tab\n\nOptions");
	general.add_options()
			("help", "Print usage and exit.")
			("conf,c", boost::program_options::value<std::string>(&param_file_path)->default_value("acquisition.conf"), "Input path to config file.")
			("mzml_out_path,o", boost::program_options::value<std::string>(&mzml_out_path)->default_value("sample.mzML"), "output path for mzML file.")
			("fido_out_path,f", boost::program_options::value<std::string>(&fido_out_path)->default_value("sample.fido"), "output path for fido file.")
			("target_decoy_out_path,d", boost::program_options::value<std::string>(&target_decoy_out_path)->default_value("targetDecoy.txt"), "output path for fido targetDecoy file.")
			;

	boost::program_options::options_description hidden("");
	hidden.add_options()
			("ground_truth_in_path", boost::program_options::value<std::string>(&sqlite_in_path), "input path for ground truth file made by GroundTruthSimulator.")
			;

	boost::program_options::options_description all("Allowed options");
	all.add(general).add(hidden);

	boost::program_options::positional_options_description p;
	p.add("ground_truth_in_path", -1);

	boost::program_options::variables_map vm;
	boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(all).positional(p).run(), vm);
	boost::program_options::notify(vm);
	//endregion

	//region Command line processing
	if (vm.count("help")) {
		std::cout << general << std::endl;
		return 0;
	}

	//region config file specification
	boost::program_options::options_description config("Configuration file options");
	config.add_options()
			("acquisition_algorithm", boost::program_options::value<std::string>(&acquisition_algorithm_name)->default_value("TopN"), "acquisition algorithm")
			("acquisition_algorithm_params", boost::program_options::value<std::vector<std::string>>(&acquisition_param_values)->multitoken(), "acquisition_algorithm_params")
			("ms1_scan_time", boost::program_options::value<double>(&ms1_scan_time)->default_value(0.256), "ms1_scan_time")
			("ms2_scan_time", boost::program_options::value<double>(&ms2_scan_time)->default_value(0.064), "ms2_scan_time")
			("scan_overhead_time", boost::program_options::value<double>(&scan_overhead_time)->default_value(0.015), "scan_overhead_time")
			("acquisition_length", boost::program_options::value<int>(&acquisition_length)->default_value(3600), "acquisition_length")
			("fasta", boost::program_options::value<std::string>(&fasta_in_path), "acquisition fasta_in_path")
			("elution_tau", boost::program_options::value<double>(&elution_tau)->default_value(4), "elution_tau")
			("elution_sigma", boost::program_options::value<double>(&elution_sigma)->default_value(6), "elution_sigma")
			("resolution", boost::program_options::value<double>(&resolution)->default_value(60000), "resolution")
			("dynamic_range", boost::program_options::value<double>(&dynamic_range)->default_value(5000), "dynamic_range")
			("db_search_min_mass", boost::program_options::value<double>(&db_search_min_mass)->default_value(200), "db_search_min_mass")
			("db_search_max_mass", boost::program_options::value<double>(&db_search_max_mass)->default_value(9000), "db_search_max_mass")
			("db_search_max_missed_cleavages", boost::program_options::value<int>(&db_search_max_missed_cleavages)->default_value(0), "db_search_max_missed_cleavages")
			("db_search_max_dynamic_mods", boost::program_options::value<int>(&db_search_max_dynamic_mods)->default_value(0), "db_search_max_dynamic_mods")
			("db_search_min_enzymatic_termini", boost::program_options::value<int>(&db_search_min_enzymatic_termini)->default_value(2), "db_search_min_enzymatic_termini")
			("db_search_mass_tolerance", boost::program_options::value<double>(&db_search_mass_tolerance)->default_value(.05), "db_search_mass_tolerance")
			("db_search_PTM", boost::program_options::value<std::vector<DBPTM> >(&PTMs)->multitoken(), "PTMs")
			("db_search_enzyme", boost::program_options::value<std::vector<DBEnzyme>>(&enzymes)->multitoken(), "enzymes")
			("db_search_null_lambda", boost::program_options::value<double>(&null_lambda)->default_value(6), "db_search_null_lambda")
			("max_ms1_injection_time", boost::program_options::value<double>(&max_ms1_injection_time)->default_value(0.2), "max_ms1_injection_time")
			("max_ms2_injection_time", boost::program_options::value<double>(&max_ms2_injection_time)->default_value(0.5), "max_ms2_injection_time")
			("ms1_target_total_ion_count", boost::program_options::value<double>(&ms1_target_total_ion_count)->default_value(1e6), "ms1_target_total_ion_count")
			("ms2_target_total_ion_count", boost::program_options::value<double>(&ms2_target_total_ion_count)->default_value(1e5), "ms2_target_total_ion_count")
			;
	boost::program_options::variables_map vm_config;
	std::ifstream config_file(param_file_path.c_str());

	if(!config_file.is_open()) {
		std::cerr << "Unable to open configuration file: " << param_file_path << std::endl;
		exit(1);
	}

	boost::program_options::store(boost::program_options::parse_config_file(config_file, config, true), vm_config);
	boost::program_options::notify(vm_config);
	//endregion


	ElutionShapeSimulator elution_shape_simulator(elution_tau, elution_sigma);
	std::unique_ptr<GroundTruthText> db = std::unique_ptr<GroundTruthText>(new GroundTruthText(sqlite_in_path, false));
	std::unique_ptr<Instrument> instrument = std::unique_ptr<Instrument>(new Instrument(resolution, dynamic_range, ms1_scan_time, ms2_scan_time,
																						scan_overhead_time, max_ms1_injection_time,
																						max_ms2_injection_time, ms1_target_total_ion_count,
																						ms2_target_total_ion_count));

	Sequencer sequencer(fasta_in_path, PTMs, enzymes, db_search_mass_tolerance, db_search_max_missed_cleavages, db_search_min_enzymatic_termini, db_search_min_mass, db_search_max_mass, db_search_max_dynamic_mods, null_lambda);
	Oracle oracle(db.get(), instrument.get(), elution_shape_simulator);
	MzMLWriter mzml_writer(mzml_out_path);
	FidoWriter fido_writer(fido_out_path);

	AcquisitionController* controller = get_controller(acquisition_algorithm_name, acquisition_param_values);

	int ms1_count = 0;
	int ms2_count = 0;
	int quality_ms2_count = 0;
	double current_time = 0;

	std::cout << "Simulating Acquisition:" << std::endl;

	while (current_time <= acquisition_length) {
		std::unique_ptr<ScanRequest> scan_request = controller->get_scan_request(current_time);
		std::unique_ptr<Scan> scan = oracle.get_scan_data(scan_request.get(), current_time);

		if (scan->scan_type == Scan::ScanType::MS2) {
			ms2_count++;
			MS2Scan* tmp_scan = static_cast<MS2Scan*>(scan.get());
			sequencer.sequence_ms2_scan(tmp_scan);

			if (tmp_scan->probability >= 0 && tmp_scan->peptide != "DECOY") {
				fido_writer.write_peptide(tmp_scan->probability, tmp_scan->peptide, tmp_scan->proteins);
				if (tmp_scan->probability >= .9) quality_ms2_count++;
			}

			/*double max_int = 0;
			std::string max_pep;
			for (auto itr = tmp_scan->peptide2intensity.begin(); itr != tmp_scan->peptide2intensity.end(); ++itr) {
				if (itr->second > max_int) {
					max_int = itr->second;
					max_pep = itr->first;
				}
			}
			std::cout << tmp_scan->precursor_peak.mz << " " << tmp_scan->precursor_peak.intensity << " " << tmp_scan->elapsed_time << " " << tmp_scan->TIC << " " << max_pep << " " << max_int / tmp_scan->TIC << " " << tmp_scan->peptide << std::endl;
			*/
		} else {
			ms1_count++;
		}

		controller->process_scan(scan.get());
		current_time += scan->elapsed_time;

		if (scan->scan_id % 20 == 0) {
			std::cout << "\rCurrent time: " << current_time << " seconds. MS1 count: " << ms1_count << ". MS2 count: " << ms2_count << ". Num PSMs >= 0.9: " << quality_ms2_count << std::flush;
		}

		mzml_writer.add_to_scan_buffer(std::move(scan));
		if (mzml_writer.buffer.size() > 100) mzml_writer.write_buffer();
	}

	std::cout << "\rCurrent time: " << current_time << " seconds. MS1 count: " << ms1_count << ". MS2 count: " << ms2_count << ". Num PSMs >= 0.9: " << quality_ms2_count << std::endl;

	mzml_writer.write_buffer();
	mzml_writer.output_file_end();

	mzml_writer.close_file();
	fido_writer.close_file();

	sequencer.write_target_decoy_file(target_decoy_out_path);

	auto end = std::chrono::high_resolution_clock::now();

	std::cout << "Simulation Complete." << std::endl;
	std::cout << "Elapsed time: " << std::chrono::duration_cast<std::chrono::seconds>(end-start).count() << " seconds" << std::endl;

	return 0;
}
Options::Options(int argc, char **argv)
	:helpRequested_(false)
{

	std::string colorBackgroundString, 
		colorUnseenString, 
		colorHeisigString,
		colorApprenticeString,
		colorGuruString,
		colorMasterString,
		colorEnlightenedString,
		colorBurnedString,
		colorErrorString;

	po::options_description cmdline("Command line options");
	cmdline.add_options()
		("apikey,k", po::value<std::string>(), "API key")
		("width,w", po::value<int>(&width_)->default_value(1920), "Width of wallpaper")
		("height,h", po::value<int>(&height_)->default_value(1080), "Height of wallpaper")
		("out,o", po::value<std::string>(&outFileName_)->default_value("out.png"), "Output filename")
		("font,f", po::value<std::string>(&fontFileName_)->default_value("ipag.ttf"), "Relative or absolute font filepath")
		("heisig-index,i", po::value<int>(&heisigIndex_)->default_value(0), "Progress in Heisig's RTK (6th edition)")
		("margin-left", po::value<int>(&marginLeft_)->default_value(0), "Space to leave blank to the left")
		("margin-right", po::value<int>(&marginRight_)->default_value(0), "Space to leave blank to the right")
		("margin-top", po::value<int>(&marginTop_)->default_value(0), "Space to leave blank to the top")
		("margin-bottom", po::value<int>(&marginBottom_)->default_value(0), "Space to leave blank to the bottom")
		("color-background", po::value<std::string>(&colorBackgroundString)->default_value("0x000000"), "Color for background")
		("color-unseen", po::value<std::string>(&colorUnseenString)->default_value("0x303030"), "Color for unseen characters")
		("color-heisig", po::value<std::string>(&colorHeisigString)->default_value("0xA0A0A0"), "Color for Heisig characters")
		("color-apprentice", po::value<std::string>(&colorApprenticeString)->default_value("0xDD0093"), "Color for apprentice characters")
		("color-guru", po::value<std::string>(&colorGuruString)->default_value("0x882D9E"), "Color for guru characters")
		("color-master", po::value<std::string>(&colorMasterString)->default_value("0x294DDB"), "Color for master characters")
		("color-enlightened", po::value<std::string>(&colorEnlightenedString)->default_value("0x0093DD"), "Color for enlightened characters")
		("color-burned", po::value<std::string>(&colorBurnedString)->default_value("0xFFFFFF"), "Color for burned characters")
		("color-error", po::value<std::string>(&colorErrorString)->default_value("0xFF0000"), "Color for error\'ed characters")
		("help", "Produce this help message")
		;

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, cmdline), vm);
	
	std::ifstream config_file("config.ini", std::ifstream::in);
	if(config_file.good())
	{
		po::store(po::parse_config_file(config_file, cmdline), vm);
	}
	
	po::notify(vm);

	if(vm.count("help"))
	{
		std::cout << cmdline << std::endl;
		std::cout << "These options can also be saved in a config.ini file in this directory.\n";
		helpRequested_ = true;
	}

	if(vm.count("apikey"))
	{
		apikey_ = vm["apikey"].as<std::string>();
	}

	colorBackground_ = Color(colorBackgroundString);
	colorUnseen_ = Color(colorUnseenString);
	colorHeisig_ = Color(colorHeisigString);
	colorApprentice_ = Color(colorApprenticeString);
	colorGuru_ = Color(colorGuruString);
	colorMaster_ = Color(colorMasterString);
	colorEnlightened_ = Color(colorEnlightenedString);
	colorBurned_ = Color(colorBurnedString);
	colorError_ = Color(colorErrorString);
}
Exemple #18
0
int main() {

    double hbarc = 197.327; // hbar * c in [MeV fm]
    double Mass = 938; // nucleon mass in MeV

    std::string input_dir = "Input/";

    // Read Nucleus File
    std::string nucleus_string;
    std::ifstream nucleus_file( "domgen.config" );

    nucleus_file >> nucleus_string;

    nucleus_file.close();
    nucleus_file.clear();

    // Read Configuration file
    std::string config_filename = nucleus_string + ".config";
    std::ifstream config_file( config_filename.c_str() );

    std::string parameters_string;
    int fit_ph;
    double rmax;
    int rpts;
    int lmax;
    config_file >> parameters_string >> fit_ph;
    config_file >> rmax >> rpts >> lmax;

    int num_lj;
    config_file >> num_lj;
    // Knowing the expected number of bound states is useful when
    // looking for particle states that are near the continuum

    // These maps hold the number of bound states for each lj
    std::map<std::string, int> n_lj_map; // neutrons
    std::map<std::string, int> p_lj_map; // protons
    std::vector< std::map< std::string, int > > map_vec;
    for ( int n = 0; n < num_lj; ++n ) {

        std::string key;
        int n_num_bound, p_num_bound;
        config_file >> key >> n_num_bound >> p_num_bound;

        std::pair< std::map< std::string, int >::iterator, bool > n_ret;
        std::pair< std::map< std::string, int >::iterator, bool > p_ret;
        n_ret = n_lj_map.insert ( std::make_pair( key, n_num_bound ) );
        p_ret = p_lj_map.insert ( std::make_pair( key, p_num_bound ) );

        if ( n_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << n_ret.first->second << std::endl;
        }

        if ( p_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << p_ret.first->second << std::endl;
        }
    }

    map_vec.push_back( n_lj_map );
    map_vec.push_back( p_lj_map );



    config_file.close();
    config_file.clear();

  //  std::string output_dir = "Output_" + parameters_string + "/Ener/";
    std::cout<< std::endl; 
   // std::string parameters_filename = parameters_string + ".inp";
   // std::string parameters_filename ="Output_hosfit/roott/Oct31/hoskhooboo_int.inp";
    std::string parameters_filename ="Output_hosfit/roott/Oct31/root.inp";
    std::cout<< "Input file is" <<" "<< " : " <<" " <<parameters_filename<<std::endl; 

    std::string output_dir = "Output_test/New/Ener/";
    std::cout<< "Output folder is" <<" "<<":"<<" "<< output_dir <<std::endl; 
    std::cout<< std::endl; 

    std::cout << "rmax = " << rmax << std::endl;
    std::cout << "rpts = " << rpts << std::endl;
    std::cout << "lmax = " << lmax << std::endl;

    std::string n_string = "n" + nucleus_string;
    std::string p_string = "p" + nucleus_string;

    std::string n_filename = input_dir + n_string + ".inp";
    std::string p_filename = input_dir + p_string + ".inp";

    // Create Nuclear Parameter Objects
    NuclearParameters Nu_n = read_nucleus_parameters( n_filename );
    NuclearParameters Nu_p = read_nucleus_parameters( p_filename );

    std::vector< NuclearParameters > Nu_vec;
    Nu_vec.push_back( Nu_n );
    Nu_vec.push_back( Nu_p );


    // Read in DOM parameters
    std::ifstream pfile( parameters_filename.c_str() );
    if ( pfile.is_open() !=1 ) {
        std::cout << "could not open file " << parameters_filename << std::endl;
        std::abort();
    }
    pfile.close();
    pfile.clear();

    std::string L_array[8] = { "s", "p", "d", "f", "g", "h", "i", "j" };
    std::string J_array[8] = { "1", "3", "5", "7", "9", "11", "13", "15" };

    // Create momentum space grid
    std::vector<double> kmesh;
    std::vector<double> kweights;
   // double const kmax = 1.4;
    double const kmax = 6.;
    int const kpts = 104;
    kmesh.resize( kpts );
    kweights.resize( kpts );
    GausLeg( 0., kmax, kmesh, kweights );

    // Create radial grid
    std::vector<double> rmesh;
    std::vector<double> rweights;
    double rdelt = rmax / rpts;
    for( int i = 0; i < rpts; ++i ) {

        rmesh.push_back( ( i + 0.5 ) * rdelt );
        rweights.push_back( rdelt );
    }

    // Prepare stuff for output files
    std::vector< std::string > np_strings;
    np_strings.push_back( n_string );
    np_strings.push_back( p_string );

    std::string energy_filename = output_dir + nucleus_string + "_energy.out";
    std::ofstream energy_file( energy_filename.c_str() );
    double total_energy = 0;
    double calc_A = 0;

    //Potential specifications
    int type = 1; // 1 is P.B. form (average), 0 is V.N. form
    int mvolume = 4;
    int AsyVolume = 1;

    // --- CALCULATIONS --- //

    // Loop over protons and neutrons
    double Zp; // number of protons in projectile

    for ( unsigned int nu = 0; nu < Nu_vec.size(); ++nu ) {
        
        std::map< std::string, int > lj_map = map_vec[nu];

        double tz = nu - 0.5; // +0.5 for protons, -0.5 for neutrons
        double Elim;

        if ( tz < 0 ) {
            Zp = 0;
            Elim = -62; // below 0s1/2 level for neutrons in 40Ca
        }
        else {
            Zp = 1;
            Elim = -56; // below 0s1/2 level for protons in 40Ca
        }

        // Nucleus Object
        const NuclearParameters &Nu = Nu_vec[nu];

        // Construct Parameters Object
        Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, Zp );

        // Construct Potential Object
        pot U = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
        pot *U1 = &U;

        // Construct boundRspace Object
//        double Emax = Nu.Ef - Nu.Wgap * p.fGap_B; // energy < Ef where imaginary part begins
        double Emax = 2.* Nu.Ef;
        double Emin = -200 + Emax;
        boundRspace B( rmax, rpts, Nu.Ef, Nu.ph_gap, lmax, Nu.Z, Zp, Nu.A, U1 );

        double tol = 0.01;
        std::vector< lj_eigen_t > bound_levels = 
            B.get_bound_levels( rmesh, tol );

        std::vector< mesh_t > emesh_vec = 
            B.get_emeshes( rmesh, Emin, Emax, bound_levels );

        double T_plus_2V = 0; // for total energy calculation
        double T_plus_2V_qh_peak_tot = 0;
        double T_plus_2V_c_tot = 0;
        std::vector< double > T_plus_2V_c_lj_vec;
        std::vector< double > T_plus_2V_c_Elim_lj_vec;
        std::vector< double > e_kin_c_lj_vec;
        std::vector< double > e_kin_peak_lj_vec;
        std::vector< double > e_kin_c_Elim_lj_vec;

        std::vector<double> n_of_k;
        n_of_k.assign( kmesh.size(), 0 );
        std::vector<double> n_of_k_qh;
        n_of_k_qh.assign( kmesh.size(), 0 );
        std::vector<double> n_of_k_Elim;
        n_of_k_Elim.assign( kmesh.size(), 0 );
        std::vector<double> n_of_k_c_tot;
        n_of_k_c_tot.assign( kmesh.size(), 0 );
        std::vector<double> n_of_k_qh_peak_tot;
        n_of_k_qh_peak_tot.assign( kmesh.size(), 0 );




        // Loop over lj channels
        for ( int l = 0; l < lmax + 1; ++l ) {

            // Create Bessel Function matrix in k and r
            matrix_t bess_mtx( kmesh.size(), rmesh.size() );
            for( unsigned int nk = 0; nk < kmesh.size(); ++nk ) {
            for( unsigned int nr = 0; nr < rmesh.size(); ++nr ) {

                double rho = kmesh[nk] * rmesh[nr];

                bess_mtx( nk, nr ) = gsl_sf_bessel_jl( l, rho );
            }
            }

            for( int up = -1; up < 2; up+=2 ) {

                double xj = l + up / 2.0;
                int j_index = ( up - 1 ) / 2;
                if ( xj < 0 ) continue;

                std::string j_string;
                if ( l == 0 ) j_string = J_array[ l ];
                else j_string = J_array[ l + j_index ];

                int index = B.index_from_LJ( l, xj );
                mesh_t &emesh = emesh_vec[index];
                std::vector< eigen_t > &bound_info = bound_levels[index];

                std::string lj_string = L_array[l] + j_string + "2";

                double T_plus_2V_c = 0; // contribution from continuum
                double T_plus_2V_qh = 0; // contribution from quasiholes
                double T_plus_2V_c_Elim = 0; // contribution for E < Elim

                std::vector<double> n_of_k_c_lj;
                std::vector<double> n_of_k_c_Elim_lj;
                std::vector<double> n_of_k_qh_lj;
                std::vector<double> n_of_k_qh_peak;
                n_of_k_c_lj.assign( kmesh.size(), 0 );
                n_of_k_c_Elim_lj.assign( kmesh.size(), 0 );
                n_of_k_qh_lj.assign( kmesh.size(), 0 );
                n_of_k_qh_peak.assign( kmesh.size(), 0 );

	        matrix_t n_r_lj(rmesh.size(),rmesh.size());
	        matrix_t k_r_lj(rmesh.size(),rmesh.size());
		for (int i=0;i<rmesh.size();++i){
		     for (int j=0;j<rmesh.size();++j){n_r_lj(i,j) = 0.;k_r_lj(i,j) = 0.;}}

                // Find self-consistent solutions

                std::cout << "lj = " << l << " " << xj << std::endl;

                // Loop over energy
                double Esum = 0.;
                double Esum2 = 0.; // sum for energies up to E = Elim
		vector<cmatrix_t> G;
	        vector<double> E;
	        vector<double> Edelt;
                for ( unsigned int m = 0; m < emesh.size(); ++m ) {
                    
                    E.push_back(emesh[m].first);
                    Edelt.push_back(emesh[m].second);
                    // Propagator
                    G.push_back(B.propagator( rmesh, E[m], l, xj ));
                  } // end loop over energy
	         for (int i = 0 ; i < rmesh.size(); ++i){
		         for (int j = 0 ; j < rmesh.size(); ++j){
			     double sumnr = 0.;
                             double ksum = 0;
			     double r_r = rmesh[i] * rmesh[j]; 	
                             for ( unsigned int m = 0; m < emesh.size(); ++m ) {
			            sumnr += r_r * imag(G[m](i,j)) * Edelt[m];
			            ksum += r_r * imag(G[m](i,j)) * E[m] * Edelt[m];
		            }
		    n_r_lj(i,j) = sumnr;	
		    k_r_lj(i,j) = ksum;	
		         }
                  }
                 // Spectral Function in momentum space    
                 // Integrate E * S( k; E ) over k and E for 
                 // calculation of total energy
                 for( unsigned int nk = 0; nk < kmesh.size(); ++nk ) {
                        double rsums = 0.;
                        for( unsigned int i = 0; i < rmesh.size(); ++i ) {
                            double jl1 = bess_mtx( nk, i );
                        for( unsigned int j = 0; j < rmesh.size(); ++j ) {
                            double jl2 = bess_mtx( nk, j );
                            
                            Esum  -= kweights[nk] * std::pow( kmesh[nk], 2 ) * k_r_lj(i,j) * jl1 * jl2 * rdelt;;
                            rsums -= n_r_lj(i,j) * jl1 * jl2 * rdelt;
                        }
                        } // end loop over radial coordinates

                        n_of_k_c_lj[nk] += rsums * ( 2 * xj + 1 )/( 4 * M_PI ) * 2 / M_PI / M_PI;

                      //   if ( E < Elim ) { n_of_k_c_Elim_lj[nk] += rsums * ( 2 * xj + 1 )
                      //                                            / ( 4 * M_PI );}

                        // integral over k
                } // end loop over k

                // integral over energy
                Esum = Esum * 2.0 / M_PI / M_PI;
                T_plus_2V_c = Esum;
                T_plus_2V_c_Elim = Esum2;
                T_plus_2V_c_lj_vec.push_back( ( 2 * xj + 1 ) * T_plus_2V_c );
                T_plus_2V_c_Elim_lj_vec.push_back(( 2 * xj + 1 ) * T_plus_2V_c_Elim );

                // loop over the orbitals and write out the 
                // bound state information to a file
                for ( unsigned int N = 0; N < bound_info.size(); ++N ) {
                    // Quasiparticle energy
                    double QPE = bound_info[N].first; 

                    // Quasiparticle wavefunction
                    std::vector<double> &QPF = bound_info[N].second;

                    // Spectroscopic Factor
                    double S = B.sfactor( rmesh, QPE, l, xj, QPF );

                    // Transform wavefunction to momentum space
                    std::vector<double> kQPF;
                    for( unsigned int nk = 0; nk < kmesh.size(); ++nk ) {

                        double sum = 0;
                        for( unsigned int i = 0; i < rmesh.size(); ++i ) {

                           sum += std::sqrt( 2 / M_PI ) * rweights[i] 
                                * std::pow( rmesh[i], 2 ) * QPF[i] * bess_mtx( nk, i );
                        }
                        kQPF.push_back( sum );
                      }

                    // This should automatically be normalized to N or Z
                    // since the wavefunctions are normalized to 1
                    if ( QPE < Nu.Ef ) {
                        for ( unsigned int kk = 0; kk < kmesh.size(); ++kk ) {

                            n_of_k_qh_lj[kk] += ( 2 * xj + 1 ) / ( 4 * M_PI ) * kQPF[kk] * kQPF[kk]; 
                        } // end loop over k
                    }
                    // Peak contributions
                    if ( ( QPE > Emax ) && ( QPE < Nu.Ef ) ) {

                        T_plus_2V_qh += S * QPE;

                        // This needs to be added to the continuum part
                        for ( unsigned int kk = 0; kk < kmesh.size(); ++kk ) {

                            n_of_k_qh_peak[kk] += ( 2 * xj + 1 ) / ( 4 * M_PI ) * S * kQPF[kk] * kQPF[kk];
                        } // end loop over k

                        // Add peak contributions to the momentum distribution
                        std::cout << "added to momentum distribution " 
                                  << N << " " << l << " " << xj << " " 
                                  << QPE << " " << S << std::endl;

                    } // endif

                } // end loop over N 
                T_plus_2V += ( 2 * xj + 1 ) * ( T_plus_2V_c + T_plus_2V_qh );

                T_plus_2V_qh_peak_tot += ( 2 * xj + 1 ) * T_plus_2V_qh;
                T_plus_2V_c_tot += ( 2 * xj + 1 ) * T_plus_2V_c;


                // Write Out Momentum Distribution for each lj channel
                // Also, add up the contribution from each channel to get 
                // the total momentum distribution
                std::string n_of_k_lj_filename = output_dir + "n_of_k_" 
                                               + np_strings[nu] 
                                               + "_" + L_array[l] + j_string 
                                               + "2.out";
                std::ofstream n_of_k_lj_file( n_of_k_lj_filename.c_str() );

                double e_kin_c_lj = 0;
                double e_kin_c_Elim_lj = 0;
                double e_kin_peak_lj = 0;
                for ( unsigned int i = 0; i < kmesh.size(); ++i ) {
                    double n_of_k_lj = n_of_k_c_lj[i] + n_of_k_qh_peak[i];

                    n_of_k_lj_file << kmesh[i] << " " << n_of_k_lj 
                                   << " " << n_of_k_qh_lj[i] << std::endl;

                    n_of_k[i] += n_of_k_lj;
                    n_of_k_qh[i] += n_of_k_qh_lj[i];
                    n_of_k_Elim[i] += n_of_k_c_Elim_lj[i];
                    n_of_k_qh_peak_tot[i] += n_of_k_qh_peak[i];
                    n_of_k_c_tot[i] += n_of_k_c_lj[i];

                    e_kin_c_lj += kweights[i] * std::pow( kmesh[i], 4 ) 
                                * std::pow( hbarc, 2 ) / ( 2 * Mass ) 
                                * n_of_k_c_lj[i] * 4 * M_PI; 

                    e_kin_peak_lj += kweights[i] * std::pow( kmesh[i], 4 ) 
                                   * std::pow( hbarc, 2 ) / ( 2 * Mass ) 
                                   * n_of_k_qh_peak[i] * 4 * M_PI; 

                    e_kin_c_Elim_lj += kweights[i] * std::pow( kmesh[i], 4 ) 
                                     * std::pow( hbarc, 2 ) / ( 2 * Mass ) 
                                     * n_of_k_c_Elim_lj[i] * 4 * M_PI;

                }

                n_of_k_lj_file.close();
                n_of_k_lj_file.clear();

                e_kin_c_lj_vec.push_back( e_kin_c_lj );
                e_kin_peak_lj_vec.push_back( e_kin_peak_lj );
                e_kin_c_Elim_lj_vec.push_back( e_kin_c_Elim_lj );
	    }//up
         }//lj


        // Output Files
        std::string strength_filename = output_dir + np_strings[nu] 
                                      + "_k_strength.out";
        std::ofstream strength_file( strength_filename.c_str() );

        std::string n_of_k_filename = output_dir + np_strings[nu]
                                    + "_momentum_dist.out";
        std::ofstream n_of_k_file( n_of_k_filename.c_str() ); 

        // Calculate Particle Number and Kinetic Energy
        double norm = 0;
        double kineticE = 0;
        double kineticE_c = 0;
        double kineticE_peak = 0;
        for ( unsigned int n = 0; n < kmesh.size(); ++n ) {
            norm += 4 * M_PI * kweights[n] * std::pow( kmesh[n], 2 ) 
                  * n_of_k[n];

            kineticE += 4 * M_PI * kweights[n] * std::pow( kmesh[n], 4 ) 
                      * n_of_k[n] * std::pow( hbarc, 2 ) / ( 2 * Mass );

            kineticE_c += 4 * M_PI * kweights[n] * std::pow( kmesh[n], 4 ) 
                        * n_of_k_c_tot[n] * std::pow( hbarc, 2 ) / ( 2 * Mass );

            kineticE_peak += 4 * M_PI * kweights[n] * std::pow( kmesh[n], 4 ) 
                           * n_of_k_qh_peak_tot[n] 
                           * std::pow( hbarc, 2 ) / ( 2 * Mass );

        }

        // Energetics
        double E_total = ( kineticE + T_plus_2V ) / 2;
        double E_potential = ( T_plus_2V - kineticE ) / 2;

        double E_total_c4 = ( kineticE_c + T_plus_2V_c_tot ) / 2;
        double E_total_peak = ( kineticE_peak + T_plus_2V_qh_peak_tot ) / 2;

        if ( tz > 0 ) energy_file << "Protons " << std::endl;
        else energy_file << "Neutrons " << std::endl;

        energy_file << " " << std::endl;
        energy_file << "Total Energy: " << E_total << std::endl;
        energy_file << "Kinetic Energy: " << kineticE << std::endl;
        energy_file << "Potential Energy: " << E_potential << std::endl;
        energy_file << "T_plus_2V: " << T_plus_2V << std::endl;
        energy_file << " " << std::endl;
        energy_file << "Kinetic Energy from continuum: " << kineticE_c 
                    << std::endl;
        energy_file << "Kinetic Energy from qh delta peaks: " << kineticE_peak 
                    << std::endl;
        energy_file << "T_plus_2V from continuum: " << T_plus_2V_c_tot 
                    << std::endl;
        energy_file << "T_plus_2V from qh delta peaks: " << T_plus_2V_qh_peak_tot 
                    << std::endl;
        energy_file << "Total energy from continuum: " << E_total_c4 
                    << std::endl;
        energy_file << "Total energy from qh delta peaks: " << E_total_peak 
                    << std::endl;

        energy_file << " " << std::endl;
        double N_or_Z; // actual number of neutrons or protons
        if( tz > 0 ) { 
            energy_file << "E / Z = " << E_total / norm << std::endl;
            energy_file << "Z = " << norm << std::endl;
            N_or_Z = Nu.Z;
        }
        else {
            energy_file << "E / N = " << E_total / norm << std::endl;
            energy_file << "N = " << norm << std::endl;
            N_or_Z = Nu.N();
        }

        total_energy += E_total;
        calc_A += norm;

        energy_file << " " << std::endl;
        energy_file << "// --- Continuum Contributions to energy --- //" 
                    << std::endl;
        energy_file << "L  j  KE  KE [-inf,-50]  Total E  Total E [-inf,-50]"
                    << std::endl;

        
        double E_total_c = 0;
        double E_total_c2 = 0;
        double E_total_c3 = 0;
        double kineticE2_check = 0;

        for ( int L = 0; L < lmax + 1; ++L ) {
        for ( int nj = -1; nj <= 0; ++nj ) {
            
            double xj = L + 0.5 + nj;
            int lj_index = 2 * L + nj;
            if ( lj_index < 0 ) continue;

            double ekin = e_kin_c_lj_vec.at( lj_index );
            double ekin_Elim = e_kin_c_Elim_lj_vec.at( lj_index );
            double T_plus_2V_c = T_plus_2V_c_lj_vec.at( lj_index );
            double T_plus_2V_c_Elim = T_plus_2V_c_Elim_lj_vec.at( lj_index );

            double total = ( ekin + T_plus_2V_c ) / 2.0;
            double total_Elim = ( ekin_Elim + T_plus_2V_c_Elim ) / 2.0;
            energy_file << L << " " << xj << " " << ekin << " " << ekin_Elim 
                        << " " << total << " " << total_Elim << std::endl;

            E_total_c += total; // Should be the same as Etotal
            kineticE2_check += ekin_Elim;

            if ( L == 0 ) E_total_c2 += total_Elim;
            else E_total_c2 += total;

            E_total_c3 += total_Elim;
        }
        }

        energy_file << "Total Continuum Contribution = " 
                    << E_total_c << ", " << E_total_c / E_total * 100 
                    << "\%" << std::endl;

        energy_file << "Total Continuum Contribution ( s wave, " 
                    << "Emax = " << Elim << " ) = " << E_total_c2 
                    << ", " << E_total_c2 / E_total * 100 
                    << "\%" << std::endl;

        energy_file << "Total Continuum Contribution ( " 
                    << "Emax = " << Elim << " ) = " << E_total_c3 
                    << ", " << E_total_c3 / E_total * 100 
                    << "\%" << std::endl;

        energy_file << " " << std::endl;
        energy_file << "-----------------------------------------" << std::endl;
        energy_file << " " << std::endl;

        // Momentum Distribution and strength
        double k_strength = 0;
        double qh_strength = 0;
        for ( unsigned int n = 0; n < kmesh.size(); ++n ) {
            n_of_k_file << kmesh[n] << " " << n_of_k[n] / norm        
                                    << " " << n_of_k_qh[n] / N_or_Z 
                                    << std::endl;

            //verify that n_of_k_qh is normalized to N or Z
            qh_strength += 4 * M_PI * kweights[n] * std::pow( kmesh[n], 2 ) 
                     * n_of_k_qh[n] / N_or_Z;

            k_strength += 4 * M_PI * kweights[n] * std::pow( kmesh[n], 2 ) 
                        * n_of_k[n] / norm;
            
            strength_file << kmesh[n] << " " << k_strength 
                                      << " " << qh_strength << std::endl;
        }

        strength_file << " " << std::endl;
        strength_file << "norm = " << norm << std::endl;
        strength_file << "N or Z = " << N_or_Z << std::endl;

        n_of_k_file.close();
        n_of_k_file.clear();
        strength_file.close();
        strength_file.clear();


    }//tz
return 1;
}
Exemple #19
0
    void CacheSettingsWidget::ReadConfig()
    {
        bool default_textures_cache_everything = false;
        int default_textures_max_size = 500*1024*1024;
        int default_assets_max_size = 300*1024*1024;

        // Init config file if file/segments doesent exist
        QSettings cache_config(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/CacheSettings");
        QString segment = "AssetCache";
        QFile config_file(cache_config.fileName());
        if (!config_file.exists())
        {
            cache_config.beginGroup("TextureCache");
            cache_config.setValue("CacheEverything", default_textures_cache_everything);
            cache_config.setValue("MaxSize", default_textures_max_size);
            cache_config.endGroup();

            cache_config.beginGroup("AssetCache");
            cache_config.setValue("MaxSize", default_assets_max_size);
            cache_config.endGroup();
            cache_config.sync();
        }
        else if (!cache_config.childGroups().contains("TextureCache"))
        {
            cache_config.beginGroup("TextureCache");
            cache_config.setValue("CacheEverything", default_textures_cache_everything);
            cache_config.setValue("MaxSize", default_textures_max_size);
            cache_config.endGroup();
            cache_config.sync();
        }
        else if (!cache_config.childGroups().contains("AssetCache"))
        {
            cache_config.beginGroup("AssetCache");
            cache_config.setValue("MaxSize", default_assets_max_size);
            cache_config.endGroup();
            cache_config.sync();
        }

        // Read config and update ui with them
        // Note: The key-value pairs might not be there even if the segment exists, lets do one more set of checks
        QVariant val;
        segment = "TextureCache/CacheEverything";
        val = cache_config.value(segment);
        if (val.isNull())
        {
            cache_config.setValue(segment, default_textures_cache_everything);
            current_textures_cache_everything_ = default_textures_cache_everything;
        }
        else
            current_textures_cache_everything_ = val.toBool();

        segment = "TextureCache/MaxSize";
        val = cache_config.value(segment);
        if (val.isNull())
        {
            cache_config.setValue(segment, default_textures_max_size);
            current_textures_max_size_ = default_textures_max_size;
        }
        else
            current_textures_max_size_ = val.toInt();
        
        segment = "AssetCache/MaxSize";
        val = cache_config.value(segment);
        if (val.isNull())
        {
            cache_config.setValue(segment, default_assets_max_size);
            current_assets_max_size_ = default_assets_max_size;
        }
        else
            current_assets_max_size_ = val.toInt();

        cache_config.sync();
    }
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      m_sqlModel(0),
      m_workerThread(new QThread),
      m_proxy(0)
{
    QCoreApplication::addLibraryPath("./sqldrivers");
    QPluginLoader p_loader(QCoreApplication::applicationDirPath() + "/sqldrivers/qsqlmysql4.dll");
    p_loader.load();
    qDebug() << p_loader.isLoaded();

    qDebug() << "Starting new window " << QThread::currentThread();
    tableView = new QTableView(this);
    tableView->horizontalHeader()->setMovable(true);
    QString newMenuTitle = QString::fromUtf8("编辑");

    QMenu* new_menu = QMainWindow::menuBar()->addMenu(newMenuTitle);
    QAction* new_result_act = new_menu->addAction(QString::fromUtf8("新建开奖结果"));
    QAction* delete_result_act = new_menu->addAction(QString::fromUtf8("删除结果"));
    // add a new separator
    new_menu->addSeparator();
    // the action use to trigger the data import functin
    QAction* import_data_act = new_menu->addAction(QString::fromUtf8("导入开奖结果"));



    connect(new_result_act, SIGNAL(triggered(bool)), SLOT(onNewActionClick()));
    connect(delete_result_act, SIGNAL(triggered(bool)), SLOT(onDeleteActionClicked()));
    connect(import_data_act, SIGNAL(triggered(bool)), SLOT(onImportDataClicked()));
    setCentralWidget(tableView);

    LotteryDockWidget *myDockWidget = new LotteryDockWidget(this);
    QWidget *title_bar = new QWidget(this);
    // trick to remove the title bar of dock widget
    myDockWidget->setTitleBarWidget(title_bar);
    myDockWidget->setAllowedAreas(Qt::TopDockWidgetArea);
    addDockWidget(Qt::TopDockWidgetArea, myDockWidget);

    // hash table for setting strings
    QHash<QString, QString> config_hash;
    // open the configuration file
    QFile config_file(QCoreApplication::applicationDirPath() + "/config.txt");
    config_file.open(QIODevice::ReadOnly);

    memset(buffer, '\0', 64);
    int readLength = config_file.readLine(buffer, 64);
    while (readLength != -1)
    {
        QString line(buffer);
        QStringList list1 = line.split(" = ");

        // remove carriage return
        list1[1].remove(0x0D);
        // remove line feed
        list1[1].remove(0x0A);

        config_hash.insert(list1[0], list1[1]);
        memset(buffer, '\0', 64);
        readLength = config_file.readLine(buffer, 64);
    }
    config_file.close();

    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(config_hash.value("host_name"));
    db.setUserName(config_hash.value("user"));
    db.setPort(3306);
    db.setDatabaseName(config_hash.value("database"));
    db.setPassword(config_hash.value("password"));


    bool open_ok = db.open();


    if (!open_ok)
    {
        QErrorMessage err_msg;
        QString error_str = QString::fromUtf8("开启数据库失败.请重启程序") + "\n" + db.lastError().text() +
                "\n" + QString::number(db.lastError().type()) + "\n" + db.hostName() + db.password() + db.userName() + db.databaseName();
        if (!p_loader.isLoaded())
            error_str += "\Plugin not loaded";
        err_msg.showMessage(error_str);
        err_msg.exec();
        exit(-1);
    }

    m_sqlModel = new MyModel(0, db);

    connect(myDockWidget, SIGNAL(blueBallSelectChanged(int)),
            m_sqlModel, SLOT(setBlueBallSelect(int)));
    connect(myDockWidget, SIGNAL(redBlueSeparateChanged(bool)),
            m_sqlModel, SLOT(setRedBlueSeparated(bool)));
    // use the current selection from the dock widget to dertermine how the model selects data
    m_sqlModel->setRedBlueSeparated(myDockWidget->isRedBlueSeparated());
    // call this function to make sure that the right table is used
    // use previsouly set boolean value
    m_sqlModel->setRedBlueSeparated(m_sqlModel->isRedBlueSeparated());


    tableView->setModel(m_sqlModel);
    tableView->verticalHeader()->hide();

    m_sqlModel->setEditStrategy(QSqlTableModel::OnFieldChange);
    m_sqlModel->select();
    m_sqlModel->query().first();

    connect(m_sqlModel, SIGNAL(beforeUpdate(int,QSqlRecord&)), this, SLOT(submitCheck(int,QSqlRecord&)));
    reOrderHeader(tableView->horizontalHeader());
}
Exemple #21
0
bool RecpathConfig::LoadConfig(const std::string & path_to_config)
{
    logD(recpath, _func_);
    //m_mutex.lock();

    m_configs.clear();
    m_bIsEmpty = true;

    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;

    std::ifstream config_file(path_to_config, std::ifstream::binary);
    if(!config_file.good())
    {
        //m_mutex.unlock();
        logE_(_func_, "fail to load config");
        return false;
    }

    bool parsingSuccessful = reader.parse( config_file, root, false );
    if(!parsingSuccessful)
    {
        //m_mutex.unlock();
        logE_(_func_, "fail to parse config");
        return false;
    }

    Json::Value configs = root["configs"];
    if(configs.empty())
    {
        //m_mutex.unlock();
        logE_(_func_, "fail to find \"configs\" section");
        return false;
    }

    for( Json::ValueIterator itr = configs.begin() ; itr != configs.end() ; itr++ )
    {
        Json::Value value = (*itr);

        Json::Value path = value["path"];
//        Json::Value quota = value["quota"];
//        Json::Value mode = value["mode"];

        if(path.empty())// || quota.empty() || mode.empty())
        {
            m_configs.clear();
            //m_mutex.unlock();
            logE_(_func_, "fail to parse params for section No ", itr.index());
            return false;
        }

        m_configs[path.asString()] = ConfigParam();
    }

    // dump config in log
    int i = 0;
    for(ConfigMap::const_iterator it = m_configs.begin(); it != m_configs.end(); ++it)
    {
        logD(recpath, _func_, "PathEntry ", i++);
        logD(recpath, _func_, "Path: ", it->first.c_str());
//        logD(recpath, _func_, "Quota: ", it->second.quota);
//        logD(recpath, _func_, "Mode: ", it->second.write_mode);
    }
    m_configJson = root.toStyledString();

    m_bIsInit = true;

    //m_mutex.unlock();

    return true;
}
Exemple #22
0
int main() {

    double wightt_J [11] = { 2., 4., 2., 4., 6., 6., 8., 8., 10., 10., 12. };
    std::string input_dir = "Input/";

    // Read Nucleus File
    std::string nucleus_string;
    std::ifstream nucleus_file( "domgen.config" );

    nucleus_file >> nucleus_string;

    nucleus_file.close();
    nucleus_file.clear();

    // Read Configuration file
    std::string config_filename = nucleus_string + ".config";
    std::ifstream config_file( config_filename.c_str() );

    std::string parameters_string;
    int fit_ph;
    double rmax;
    int rpts;
    int lmax;

    config_file >> parameters_string >> fit_ph;
    config_file >> rmax >> rpts >> lmax;

    int num_lj;
    config_file >> num_lj;

    // Knowing the expected number of bound states is useful when
    // looking for particle states that are near the continuum

    // These maps hold the number of bound states for each lj
    std::map<std::string, int> n_lj_map; // neutrons
    std::map<std::string, int> p_lj_map; // protons
    std::vector< std::map< std::string, int > > map_vec;
    for ( int n = 0; n < num_lj; ++n ) {

        std::string key;
        int n_num_bound, p_num_bound;
        config_file >> key >> n_num_bound >> p_num_bound;

        std::pair< std::map< std::string, int >::iterator, bool > n_ret;
        std::pair< std::map< std::string, int >::iterator, bool > p_ret;
        n_ret = n_lj_map.insert ( std::make_pair( key, n_num_bound ) );
        p_ret = p_lj_map.insert ( std::make_pair( key, p_num_bound ) );

        if ( n_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << n_ret.first->second << std::endl;
        }

        if ( p_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << p_ret.first->second << std::endl;
        }
    }

    map_vec.push_back( n_lj_map );
    map_vec.push_back( p_lj_map );

    int num_so;
    config_file >> num_so;

    // These maps determine which orbits are included in the
    // spin-orbit correction to the charge density
    std::map<std::string, int> n_so_map; // neutrons
    std::map<std::string, int> p_so_map; // protons
    std::vector< std::map< std::string, int > > so_map_vec;
    for ( int n = 0; n < num_so; ++n ) {

        std::string key;

        // 1 if shell is filled, 0 if not at all (in IPM),
        // in between if shell is partially filled
        int n_shell, p_shell; 
        config_file >> key >> n_shell >> p_shell;

        std::pair< std::map< std::string, int >::iterator, bool > n_ret;
        std::pair< std::map< std::string, int >::iterator, bool > p_ret;
        n_ret = n_so_map.insert ( std::make_pair( key, n_shell ) );
        p_ret = p_so_map.insert ( std::make_pair( key, p_shell ) );

        if ( n_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << n_ret.first->second << std::endl;
        }

        if ( p_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << p_ret.first->second << std::endl;
        }
    }

    so_map_vec.push_back( n_so_map );
    so_map_vec.push_back( p_so_map );

    config_file.close();
    config_file.clear();

    bool hole;
    if ( fit_ph == 0 ) hole = true;
    else hole = false;

    std::string output_dir = "Output_" + parameters_string + "/Output_domgen/";
    std::string parameters_filename = parameters_string + ".inp";

    std::cout << "rmax = " << rmax << std::endl;
    std::cout << "rpts = " << rpts << std::endl;
    std::cout << "lmax = " << lmax << std::endl;

    std::string n_string = "n" + nucleus_string;
    std::string p_string = "p" + nucleus_string;

    std::string n_filename = input_dir + n_string + ".inp";
    std::string p_filename = input_dir + p_string + ".inp";

    // Create Nuclear Parameter Objects
    NuclearParameters Nu_n = read_nucleus_parameters( n_filename );
    NuclearParameters Nu_p = read_nucleus_parameters( p_filename );

    std::vector< NuclearParameters > Nu_vec;
    Nu_vec.push_back( Nu_n );
    Nu_vec.push_back( Nu_p );


    // Read in DOM parameters
    std::ifstream pfile( parameters_filename.c_str() );
    if ( pfile.is_open() !=1 ) {
        std::cout << "could not open file " << parameters_filename << std::endl;
        std::abort();
    }
    pfile.close();
    pfile.clear();

    std::string L_array[8] = { "s", "p", "d", "f", "g", "h", "i", "j" };
    std::string J_array[8] = { "1", "3", "5", "7", "9", "11", "13", "15" };


    // Create radial grid
    std::vector<double> rmesh;
    std::vector<double> rweights;
    double rdelt = rmax / rpts;
    for( int i = 0; i < rpts; ++i ) {

        rmesh.push_back( ( i + 0.5 ) * rdelt );
        rweights.push_back( rdelt );
    }

    // initialize charge density vector
    std::vector<double> chd_ls; //relativistic spin-orbit correction
    std::vector<double> chd_ls_test; //relativistic spin-orbit correction
    chd_ls.assign( rmesh.size(), 0 ); 
    chd_ls_test.assign( rmesh.size(), 0 ); 
   

    double E_c = -20;
    double HOSS[20][rmesh.size()];
//    double HOSS1[20][rmesh.size()];    
    for (unsigned int ii = 0 ;ii<20 ; ++ii){for (unsigned int k = 0 ; k<rmesh.size(); ++k) {HOSS[ii][k]=0.0;}}
    std::vector<vector < double > > HOSS1;   
    std::vector< double > EHOSS1; 
    

    std::string chd_filename = 
        output_dir + nucleus_string + "_charge_density.out";
    std::ofstream chd_file( chd_filename.c_str() );
    std::vector< std::vector<double> > chdf_np_vec;

    // Prepare stuff for output files
    std::vector< std::string > np_strings;
    np_strings.push_back( n_string );
    np_strings.push_back( p_string );

    //Potential specifications
    int type = 1; // 1 is P.B. form (average), 0 is V.N. form
    int mvolume = 4;
    int AsyVolume = 1;

    // --- CALCULATIONS --- //

    // Loop over protons and neutrons
    double Zp; // number of protons in projectile
    std::vector< double > coulomb_vec;
    coulomb_vec.assign( rmesh.size(), 0 ); // store coulomb potential
    for ( unsigned int nu = 0; nu < Nu_vec.size(); ++nu ) {
        
        std::map< std::string, int > lj_map = map_vec[nu];
        std::map< std::string, int > so_map = so_map_vec[nu];

        double tz = nu - 0.5; // +0.5 for protons, -0.5 for neutrons
        double mag_moment;

        if ( tz < 0 ) {
            Zp = 0;
            mag_moment = -1.91; // mu_n;
        }
        else {
            Zp = 1;
            mag_moment = 2.29; // Actually mu_p - 0.5

        }

        // Nucleus Object
        const NuclearParameters &Nu = Nu_vec[nu];

        // Construct Parameters Object
        Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, Zp );

        // Construct Potential Object
        pot U = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
        pot *U1 = &U;

        // Construct boundRspace Object
        double Emax = Nu.Ef - Nu.Wgap * p.fGap_B; // energy < Ef where imaginary part begins
        double Emin = -200 + Emax;
        boundRspace B( rmax, rpts, Nu.Ef, Nu.ph_gap, lmax, Nu.Z, Zp, Nu.A, U1 );

        double tol = 0.01;
        std::vector< lj_eigen_t > bound_levels = 
            B.get_bound_levels( rmesh, tol );

        std::vector< mesh_t > emesh_vec = 
            B.get_emeshes( rmesh, Emin, Emax, bound_levels );

        // store coulomb potential in order to compare with
        // proton charge distribution
        if ( tz > 0 ) {
            for ( unsigned int i = 0; i < rmesh.size(); ++i ) {

                coulomb_vec[i] += U.coulomb( rmesh[i] );
            }
        }

        // Vector for holding neutron or proton point distribution
        std::vector<double> point_dist;
        std::vector<double> point_dist_wfx; // calculated using wavefunctions
        point_dist.assign( rmesh.size(), 0 );
        point_dist_wfx.assign( rmesh.size(), 0 );

        // Output Files
        std::string qp_filename = 
            output_dir + np_strings[nu] + "_quasiparticle" + ".out";
        std::ofstream qp_file( qp_filename.c_str() );

        std::string strength_filename = 
            output_dir + np_strings[nu] + "_strengths.out";
        std::ofstream strength_file( strength_filename.c_str() );

        std::string density_filename = 
            output_dir + np_strings[nu] + "_density_dist.out";
        std::ofstream density_file( density_filename.c_str() ); 

        


        // Loop over lj channels
        double rsum = 0; // running sum of strength
        for ( int l = 0; l < lmax + 1; ++l ) {

            for( int up = -1; up < 2; up+=2 ) {

                double xj = l + up / 2.0;
                int j_index = ( up - 1 ) / 2;
                if ( xj < 0 ) continue;

                int index = B.index_from_LJ( l, xj );
                mesh_t &emesh = emesh_vec[index];
                std::vector< eigen_t > &bound_info = bound_levels[index];

                double lp; 
                if ( xj > l ) lp = l;
                else lp = - l - 1;
                
                std::string j_string;
                if ( l == 0 ) j_string = J_array[ l ];
                else j_string = J_array[ l + j_index ];

                std::string lj_string = L_array[l] + j_string + "2";

                std::string spf_filename;
                std::string chd_lj_filename;

                spf_filename = output_dir + np_strings[nu] + "_spectral_f_" 
                             + L_array[l] + j_string + "2.out";

                chd_lj_filename = output_dir + np_strings[nu] + "_chd_" 
                                + L_array[l] + j_string + "2.out";

                std::ofstream spf_file( spf_filename.c_str() );
                std::ofstream chd_lj_file( chd_lj_filename.c_str() );

                // Find self-consistent solutions
                std::cout << "lj = " << l << " " << xj << std::endl;




		std::vector<double> sumG;
                sumG.assign( rmesh.size() ,0);
               
               



                 
                // Loop over energy
                double strength = 0;
                matrix_t d_mtx( rmesh.size(), rmesh.size() ); // density matrix
                d_mtx.clear();
                std::vector<cmatrix_t> G_vec;
                for ( unsigned int m = 0; m < emesh.size(); ++m ) {
                    
                    double E = emesh[m].first;
                    double Edelt = emesh[m].second;

                    // Propagator
                    cmatrix_t G = B.propagator( rmesh, E, l, xj );

                    G_vec.push_back( G );

                    // Spectral Function 
                    complex_t trace = 0;
                    for( unsigned int i = 0; i < rmesh.size(); ++i ) {
				
				if (tz>0){ 
                                	sumG[i] = sumG[i] - 1/M_PI *imag( G(i,i))/(rmesh[i] * rmesh [i] * rdelt) * Edelt;
				}

                       
                        trace += G( i, i ); 
                    }

		    if( (tz>0) && (index==4) && (E>E_c)) {
							  HOSS1.push_back(sumG);
							  EHOSS1.push_back(E);
							  E_c+=.2;}			

                    double spf = -imag( trace ) / M_PI; 
                    spf_file << E << " " << spf << std::endl;

                    // Density Matrix
                    for( unsigned int i = 0; i < rmesh.size(); ++i ) {
                        for( unsigned int j = 0; j < rmesh.size(); ++j ) {
                            
                            //G( i, j ) /= rmesh[i] * rmesh[j] * rdelt;
                            d_mtx( i, j ) -= Edelt * imag( G( i, j ) ) / M_PI
                                           / ( rmesh[i] * rmesh[j] * rdelt );
                        }
                    }

                    strength += Edelt * spf;

                } // end loop over energy

          	if (tz > 0){
                    for (unsigned int i = 0 ; i<rmesh.size() ; ++i){
                        HOSS[index][i] = sumG[i];   
		
                    }
                } 
                // Charge Density
                std::vector<double> chd_lj;
                for( unsigned int i = 0; i < rmesh.size(); ++i ) {
    
                    double chd = ( 2 * xj + 1 ) * d_mtx( i, i ) / ( 4 * M_PI );
                    chd_lj.push_back( chd );
                }

                // loop over the orbitals and write out the 
                // bound state information to a file
                int intj = static_cast<int>( 2 * xj );
                for ( int N = 0; N < bound_info.size(); ++N ) {

                    std::string level_str = util::IntToStr( N ) + L_array[l] 
                                          + j_string + "2";
/*
                    std::string wfx_filename = output_dir + np_strings[nu] 
                        + "_" + level_str + ".wfx";
                    std::ofstream wfx_file( wfx_filename.c_str() );
*/
                    std::string chd_nlj_filename = output_dir + np_strings[nu] 
                        + "_" + level_str + ".chd";
                    std::ofstream chd_nlj_file ( chd_nlj_filename.c_str() );

                    std::string spf_nlj_filename = output_dir + np_strings[nu] 
                        + "_" + level_str + ".spf"; 
                    std::ofstream spf_nlj_file( spf_nlj_filename.c_str() );
                
                    // Quasiparticle energy
                    double QPE = bound_info[N].first; 

                    // Quasiparticle wavefunction
                    std::vector<double> &QPF = bound_info[N].second;

                    // Spectroscopic Factor
                    double S = B.sfactor( rmesh, QPE, l, xj, QPF );
                    double radius = B.rms_radius( rmesh, QPF );
        
                    // Occupation of continuum part
                    double occ = B.occupation( rmesh, d_mtx, QPF );

                    // fold spectral function with quasihole wavefunctions
                    double occ2 = 0; // should be the same as occ
                    //matrix_t projected_dmtx( rmesh.size(), rmesh.size() );
                    for( unsigned int g = 0; g < G_vec.size(); ++g ) {

                        double E = emesh[g].first;
                        double Edelt = emesh[g].second;

                        double fspf = 0;
                        for( unsigned int i = 0; i < rmesh.size(); ++i ) {
                        for( unsigned int j = 0; j < rmesh.size(); ++j ) {

                           fspf -= rmesh[i] * rmesh[j] * rdelt / M_PI
                                 * QPF[i] * QPF[j] * imag( G_vec[g]( i, j ) );
                        }
                        }

                        occ2 += fspf * Edelt;
                        spf_nlj_file << E << " " << fspf << std::endl;
                    }

                    // get rough estimate of quasihole width
                    double gamma = B.approx_width( rmesh, QPE, l, xj, QPF );

                    spf_nlj_file.close();
                    spf_nlj_file.clear();

                    qp_file << N << L_array[l] << intj << "/2" 
                            << " " << QPE << " " << S 
                            << " " << radius << " " << occ 
                            << " " << gamma << std::endl;


                    /* CHARGE DENSITY STUFF */

                    // calculate charge density using wavefunctions
                    std::vector<double> chd_nlj;
                    for ( unsigned int i = 0; i < rmesh.size(); ++i ) {
                        
                        chd_nlj.push_back( ( 2 * xj + 1 ) / ( 4 * M_PI )
                                            * QPF[i] * QPF[i] );
                                            
                        point_dist_wfx[i] += chd_nlj[i];
                        // Write out wavefunctions to a file
                        //wfx_file << rmesh[i] << " " << QPF[i] << std::endl;
                        chd_nlj_file << rmesh[i] << " " << chd_nlj[i] << " " 
                                     << rmesh[i] * chd_nlj[i] << std::endl;
                    }

                    //wfx_file.close();
                    //wfx_file.clear();
                    chd_nlj_file.close();
                    chd_nlj_file.clear();

                    double total_occ;
                    if ( ( QPE > Emax ) && ( QPE <= ( Nu.Ef ) ) ) {

                        strength += S;
                        total_occ = occ + S;

                        for ( unsigned int i = 0; i < rmesh.size(); ++i ) {

                            chd_lj[i] += ( 2 * xj + 1 ) * S * QPF[i] * QPF[i] 
                                       / ( 4 * M_PI );

                        } // end loop over r

                        // Add peak contributions to the charge density
                        std::cout << "added to charge density " << N << " " 
                                  << l << " " << xj << " " << QPE << " " 
                                  << S << std::endl;

                    } // endif
                    else total_occ = occ;

                    // calculate derivative of r * charge density for 
                    // relativistic spin-orbit correction. Taken from
                    // J. Phys. G: Nucl. Phys. 5, 1655 ( 1979 )

                    if( ( so_map.count(level_str) > 0 ) && 
                        ( so_map[level_str] > 0 ) ) {
                        
                        std::cout << "doing spinorbit correction" << std::endl;
                    for ( unsigned int i = 1; i < rmesh.size()-1; ++i ) {

                        double der = 
                            der_3pt( rdelt, rmesh[i-1] * chd_nlj[i-1], 
                                     rmesh[i+1] * chd_nlj[i+1] );

                        // correction
                        chd_ls[i] += 0.5 * total_occ * lp * mag_moment
                                   * der / std::pow( rmesh[i], 2 )
                                   * so_map[level_str];
/*
                        double der4 = 
                            der_4pt( rdelt, rmesh[i-2] * chd_nlj[i-2],
                                     rmesh[i-1] * chd_nlj[i-1],
                                     rmesh[i+1] * chd_nlj[i+1],
                                     rmesh[i+2] * chd_nlj[i+2] );
                        chd_ls_test[i] += 0.5 * total_occ * lp * mag_moment
                                        * der4 / std::pow( rmesh[i], 2 );
                        
*/
                    }
                    } // end if so_correction

                } // end loop over N 

                rsum += strength * ( 2 * xj + 1 );

                strength_file << L_array[l] << intj << "/2"
                              << " " << strength << " " << rsum << std::endl;

                // print out point distribution for each lj
                for ( unsigned int i = 0; i < rmesh.size(); ++i ) {

                    chd_lj_file << rmesh[i] << " " << chd_lj[i] << std::endl;
                    point_dist[i] += chd_lj[i];
                }

                spf_file.close();
                spf_file.clear();
                chd_lj_file.close();
                chd_lj_file.clear();

            } //end loop over j
        } // end loop over l

        qp_file.close();
        qp_file.clear();

        // Print to file the matter distribution. Find Normalization first
        double point_norm = 0;
        for ( unsigned int i = 0; i < rmesh.size(); ++i ) {

            point_norm += 4 * M_PI * point_dist[i] * std::pow( rmesh[i], 2 )
                        * rdelt;
        }
std::cout<<point_dist[0]<<std::endl;
        double particle_number;
        if ( tz > 0 ) particle_number = Nu.Z;
        else particle_number = Nu.N();

        double norm_fac = particle_number / point_norm;
        double new_norm = 0; 
        for ( unsigned int i = 0; i < rmesh.size(); ++i ) {
        
            point_dist[i] *= norm_fac;
            new_norm += 4 * M_PI * std::pow( rmesh[i], 2 ) * rdelt 
                      * point_dist[i];
        }

        strength_file << " " << std::endl;
        strength_file << "Number of Particles from point distribution: " 
                      << point_norm << std::endl;

        strength_file << "Number after normalization: " << new_norm 
                      << std::endl;

        strength_file.close();
        strength_file.clear();


        std::cout << "Folding density distribution" << std::endl;
        // Fold point charge density with neutron and proton charge distribution

        std::vector<double> chdf = 
            folded_ch_density( rmesh, rweights, point_dist, tz, Nu.A );

        chdf_np_vec.push_back( chdf );

        // approximate finite size of neutron with proton charge
        // distribution in order to calculate the neutron matter
        // distribution
        std::vector<double> matter_dist =
            matter_distribution( rmesh, rweights, point_dist, Nu.A );

        // write out point distribution and matter distribution to file
        for ( unsigned int i = 0; i < rmesh.size(); ++i ) {
            density_file << rmesh[i] << " " << point_dist[i] << " " 
                         << point_dist_wfx[i] << " " 
                         << matter_dist[i] << std::endl;
        }

        density_file.close();
        density_file.clear();

        if (tz>0) {
	std::string outputdirrr="/scratch/mmahzoon/Jafer/s";
        std::ofstream spectral_r_file( "/scratch/mmahzoon/Jafer/spec_file_r.out" );
        std::ofstream Espectral_s_r_file( "/scratch/mmahzoon/Jafer/Espec_file_s_r.out" );
        for (int i=0 ; i<rmesh.size();++i) {  		
							double tot_HOSS = 0;	
							for(int jj=0 ; jj <11 ; ++jj)  { tot_HOSS+= wightt_J[jj] * HOSS[jj][i]; }
							spectral_r_file <<rmesh[i] << " " << HOSS[0][i] << " " << HOSS[1][i] << " " << HOSS[2][i] 
								   << " " << HOSS[3][i] << " " << HOSS[4][i] << " " << HOSS[5][i]
								   << " " << HOSS[6][i] << " " << HOSS[7][i] << " " << HOSS[8][i] 
								   << " " << HOSS[9][i] << " " << HOSS[10][i] <<" " <<tot_HOSS<<std::endl;}



         for (int i=0 ; i<HOSS1.size();++i) { 
                Espectral_s_r_file << i <<" "<< EHOSS1[i] << std::endl;
		std::string Stringg = static_cast<ostringstream*>( &(ostringstream() << i) )->str();
		std::string spectral_s_r_file= outputdirrr + Stringg + ".out";
		std::ofstream spectral_sr_file( spectral_s_r_file.c_str() );
   	 	for (int j=0 ; j<rmesh.size() ; ++j) { 
    			spectral_sr_file << rmesh[j]<<" " << HOSS1[i][j] <<  std::endl;
 
	   	}   
		spectral_sr_file.close();	

	}   
        Espectral_s_r_file.close();
	spectral_r_file.close();	}
    } // end loop over Nu_vec

    if ( chdf_np_vec.size() < 2 ) { 
        std::cout << "chdf_np_vec has wrong size." << std::endl;
        throw std::exception();
    }

    std::vector<double> chd_tot;
    chd_tot.assign( rmesh.size(), 0 );

    double hbar_over_mc = 0.21;
    for( unsigned int i = 0; i < rmesh.size(); ++i ) {

        // add folded proton charge distribution
        chd_tot[i] += chdf_np_vec[1][i];

        // add folded neutron charge distribution
        chd_tot[i] += chdf_np_vec[0][i];

        // add spin-orbit correction
        chd_ls[i] *= - std::pow( hbar_over_mc, 2 );
        chd_tot[i] += chd_ls[i];
    }

    // Find normalization of Charge Density Distribution
    double chd_norm = 0;
    for ( unsigned int i = 0; i < rmesh.size(); ++i ) {

        chd_norm += 4 * M_PI * chd_tot[i] * std::pow( rmesh[i], 2 ) * rdelt;
        
    }
    std::cout << "chd_norm = " << chd_norm << std::endl;

    // Write Charge Density Information
    double norm_fac = Nu_p.Z / chd_norm;
    for ( unsigned int i = 0; i < rmesh.size(); ++i ) {

        chd_file << rmesh[i] << " " << chd_tot[i] * norm_fac << " " 
                 << chdf_np_vec[1][i] * norm_fac << " " 
                 << chdf_np_vec[0][i] * norm_fac << " " 
                 << chd_ls[i] * norm_fac << " " 
                 << chd_ls_test[i] * norm_fac  << " " 
                 << coulomb_vec[i] << std::endl;
    }

    chd_file.close();
    chd_file.clear();

    // Calculate RMS Radius
    double sum_pf = 0; // contribution from protons
    double sum_pfr2 = 0;
    double sum_nfr2 = 0; // contribution from neutrons
    double sum_lsr2 = 0; // contribution from spin-orbit correction
    double sum_totr2 = 0; // total
    for ( unsigned int i = 1; i < rmesh.size() - 1; ++i ) {
        
        sum_pf += std::pow( rmesh[i], 2 ) * chdf_np_vec[1][i] * rdelt;
        sum_pfr2 += std::pow( rmesh[i], 4 ) * chdf_np_vec[1][i] * rdelt;

        sum_nfr2 += std::pow( rmesh[i], 4 ) * chdf_np_vec[0][i] * rdelt;

        sum_lsr2 += std::pow( rmesh[i], 4 ) * chd_ls[i] * rdelt;

        sum_totr2 += std::pow( rmesh[i], 4 ) * chd_tot[i] * rdelt;

    }

    double rms_pf = std::sqrt( sum_pfr2 / sum_pf );
    double rms_tot = std::sqrt( 4 * M_PI * sum_totr2 / chd_norm );
    double rms2_p = 4 * M_PI * sum_pfr2 / chd_norm;
    double rms2_n = 4 * M_PI * sum_nfr2 / chd_norm;
    double rms2_ls = 4 * M_PI * sum_lsr2 / chd_norm;
    double rms_tot_check = std::sqrt( rms2_p + rms2_n + rms2_ls );

    std::string rms_filename = output_dir + nucleus_string + "_rms.out";
    std::ofstream rms_file( rms_filename.c_str() );
    rms_file << "Folded with proton charge distribution only" << std::endl;
    rms_file << "RMS radius: " << rms_pf << std::endl;
    rms_file << "Number of protons: " << sum_pf * 4 * M_PI << std::endl;

    rms_file << " " << std::endl;

    rms_file << "Proton, neutron and spin-orbit contributions included" 
             << std::endl;
    rms_file << "RMS radius: " << rms_tot << std::endl;
    rms_file << "Number of protons: " << chd_norm << std::endl;

    rms_file << "Mean Square Radius for different contributions "
             << "(normalized by Z = " << chd_norm << ")" << std::endl;

    rms_file << " " << std::endl;
    rms_file << "Proton Contribution (with Folding): " << rms2_p << std::endl;
    rms_file << "Neutron Conribution: " << rms2_n << std::endl;
    rms_file << "Spin-orbit Contribution: " << rms2_ls << std::endl;
    rms_file << " " << std::endl;
    rms_file << "Check with total: " << rms_tot_check << std::endl;

    rms_file.close();
    rms_file.clear();

    return 1;
}