int main(int argc, char *argv[]) { int my_rank; double mpi_start_time, mpi_end_time; deme *subpop = (deme*) malloc(sizeof(deme)); MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); init_population(subpop, argc, argv); mpi_start_time = MPI_Wtime(); while (!subpop->complete) { migration(subpop); reproduction(subpop); crossover(subpop); mutation(subpop); fitness(subpop); subpop->old_pop = subpop->new_pop; subpop->cur_gen++; check_complete(subpop); sync_complete(subpop); report_all(subpop); } mpi_end_time = MPI_Wtime(); report_fittest(subpop); MPI_Finalize(); printf("[%i] Elapsed time: %f\n", my_rank, mpi_end_time - mpi_start_time); return 1; }
// On Android, there there is a libqgis.so instead of a qgis executable. // The main method symbol of this library needs to be exported so it can be called by java // On Windows this main is included in qgis_app and called from mainwin.cpp APP_EXPORT #endif int main( int argc, char *argv[] ) { #ifdef Q_OS_MACX // Increase file resource limits (i.e., number of allowed open files) // (from code provided by Larry Biehl, Purdue University, USA, from 'MultiSpec' project) // This is generally 256 for the soft limit on Mac // NOTE: setrlimit() must come *before* initialization of stdio strings, // e.g. before any debug messages, or setrlimit() gets ignored // see: http://stackoverflow.com/a/17726104/2865523 struct rlimit rescLimit; if ( getrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 ) { rlim_t oldSoft( rescLimit.rlim_cur ); rlim_t oldHard( rescLimit.rlim_max ); #ifdef OPEN_MAX rlim_t newSoft( OPEN_MAX ); rlim_t newHard( std::min( oldHard, newSoft ) ); #else rlim_t newSoft( 4096 ); rlim_t newHard( std::min( ( rlim_t )8192, oldHard ) ); #endif if ( rescLimit.rlim_cur < newSoft ) { rescLimit.rlim_cur = newSoft; rescLimit.rlim_max = newHard; if ( setrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 ) { QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard NEW: %1 / %2" ) .arg( rescLimit.rlim_cur ).arg( rescLimit.rlim_max ) ); } } Q_UNUSED( oldSoft ); //avoid warnings QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard ORIG: %1 / %2" ) .arg( oldSoft ).arg( oldHard ) ); } #endif QgsDebugMsg( QString( "Starting qgis main" ) ); #ifdef WIN32 // Windows #ifdef _MSC_VER _set_fmode( _O_BINARY ); #else //MinGW _fmode = _O_BINARY; #endif // _MSC_VER #endif // WIN32 // Set up the custom qWarning/qDebug custom handler #ifndef ANDROID qInstallMsgHandler( myMessageOutput ); #endif #if (defined(linux) && !defined(ANDROID)) || defined(__FreeBSD__) signal( SIGQUIT, qgisCrash ); signal( SIGILL, qgisCrash ); signal( SIGFPE, qgisCrash ); signal( SIGSEGV, qgisCrash ); signal( SIGBUS, qgisCrash ); signal( SIGSYS, qgisCrash ); signal( SIGTRAP, qgisCrash ); signal( SIGXCPU, qgisCrash ); signal( SIGXFSZ, qgisCrash ); #endif #ifdef Q_OS_WIN SetUnhandledExceptionFilter( QgsCrashHandler::handle ); #endif // initialize random number seed qsrand( time( nullptr ) ); ///////////////////////////////////////////////////////////////// // Command line options 'behavior' flag setup //////////////////////////////////////////////////////////////// // // Parse the command line arguments, looking to see if the user has asked for any // special behaviors. Any remaining non command arguments will be kept aside to // be passed as a list of layers and / or a project that should be loaded. // // This behavior is used to load the app, snapshot the map, // save the image to disk and then exit QString mySnapshotFileName; QString configLocalStorageLocation; QString profileName; int mySnapshotWidth = 800; int mySnapshotHeight = 600; bool myHideSplash = false; bool mySettingsMigrationForce = false; bool mySkipVersionCheck = false; #if defined(ANDROID) QgsDebugMsg( QString( "Android: Splash hidden" ) ); myHideSplash = true; #endif bool myRestoreDefaultWindowState = false; bool myRestorePlugins = true; bool myCustomization = true; QString dxfOutputFile; QgsDxfExport::SymbologyExport dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology; double dxfScale = 50000.0; QString dxfEncoding = QStringLiteral( "CP1252" ); QString dxfPreset; QgsRectangle dxfExtent; // This behavior will set initial extent of map canvas, but only if // there are no command line arguments. This gives a usable map // extent when qgis starts with no layers loaded. When layers are // loaded, we let the layers define the initial extent. QString myInitialExtent; if ( argc == 1 ) myInitialExtent = QStringLiteral( "-1,-1,1,1" ); // This behavior will allow you to force the use of a translation file // which is useful for testing QString myTranslationCode; // The user can specify a path which will override the default path of custom // user settings (~/.qgis) and it will be used for QgsSettings INI file QString configpath; QString authdbdirectory; QString pythonfile; QString customizationfile; QString globalsettingsfile; // TODO Fix android #if defined(ANDROID) QgsDebugMsg( QString( "Android: All params stripped" ) );// Param %1" ).arg( argv[0] ) ); //put all QGIS settings in the same place configpath = QgsApplication::qgisSettingsDirPath(); QgsDebugMsg( QString( "Android: configpath set to %1" ).arg( configpath ) ); #endif QStringList args; if ( !bundleclicked( argc, argv ) ) { // Build a local QCoreApplication from arguments. This way, arguments are correctly parsed from their native locale // It will use QString::fromLocal8Bit( argv ) under Unix and GetCommandLine() under Windows. QCoreApplication coreApp( argc, argv ); args = QCoreApplication::arguments(); for ( int i = 1; i < args.size(); ++i ) { const QString &arg = args[i]; if ( arg == QLatin1String( "--help" ) || arg == QLatin1String( "-?" ) ) { usage( args[0] ); return 2; } else if ( arg == QLatin1String( "--nologo" ) || arg == QLatin1String( "-n" ) ) { myHideSplash = true; } else if ( arg == QLatin1String( "--version-migration" ) ) { mySettingsMigrationForce = true; } else if ( arg == QLatin1String( "--noversioncheck" ) || arg == QLatin1String( "-V" ) ) { mySkipVersionCheck = true; } else if ( arg == QLatin1String( "--noplugins" ) || arg == QLatin1String( "-P" ) ) { myRestorePlugins = false; } else if ( arg == QLatin1String( "--nocustomization" ) || arg == QLatin1String( "-C" ) ) { myCustomization = false; } else if ( i + 1 < argc && ( arg == QLatin1String( "--profile" ) ) ) { profileName = args[++i]; } else if ( i + 1 < argc && ( arg == QLatin1String( "--profiles-path" ) || arg == QLatin1String( "-s" ) ) ) { configLocalStorageLocation = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == QLatin1String( "--snapshot" ) || arg == QLatin1String( "-s" ) ) ) { mySnapshotFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == QLatin1String( "--width" ) || arg == QLatin1String( "-w" ) ) ) { mySnapshotWidth = QString( args[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == QLatin1String( "--height" ) || arg == QLatin1String( "-h" ) ) ) { mySnapshotHeight = QString( args[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == QLatin1String( "--lang" ) || arg == QLatin1String( "-l" ) ) ) { myTranslationCode = args[++i]; } else if ( i + 1 < argc && ( arg == QLatin1String( "--project" ) || arg == QLatin1String( "-p" ) ) ) { sProjectFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == QLatin1String( "--extent" ) || arg == QLatin1String( "-e" ) ) ) { myInitialExtent = args[++i]; } else if ( i + 1 < argc && ( arg == QLatin1String( "--authdbdirectory" ) || arg == QLatin1String( "-a" ) ) ) { authdbdirectory = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() ); } else if ( i + 1 < argc && ( arg == QLatin1String( "--code" ) || arg == QLatin1String( "-f" ) ) ) { pythonfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == QLatin1String( "--customizationfile" ) || arg == QLatin1String( "-z" ) ) ) { customizationfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == QLatin1String( "--globalsettingsfile" ) || arg == QLatin1String( "-g" ) ) ) { globalsettingsfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } else if ( arg == QLatin1String( "--defaultui" ) || arg == QLatin1String( "-d" ) ) { myRestoreDefaultWindowState = true; } else if ( arg == QLatin1String( "--dxf-export" ) ) { dxfOutputFile = args[++i]; } else if ( arg == QLatin1String( "--dxf-extent" ) ) { QgsLocaleNumC l; QString ext( args[++i] ); QStringList coords( ext.split( ',' ) ); if ( coords.size() != 4 ) { std::cerr << "invalid dxf extent " << ext.toStdString() << std::endl; return 2; } for ( int i = 0; i < 4; i++ ) { bool ok; double d; d = coords[i].toDouble( &ok ); if ( !ok ) { std::cerr << "invalid dxf coordinate " << coords[i].toStdString() << " in extent " << ext.toStdString() << std::endl; return 2; } switch ( i ) { case 0: dxfExtent.setXMinimum( d ); break; case 1: dxfExtent.setYMinimum( d ); break; case 2: dxfExtent.setXMaximum( d ); break; case 3: dxfExtent.setYMaximum( d ); break; } } } else if ( arg == QLatin1String( "--dxf-symbology-mode" ) ) { QString mode( args[++i] ); if ( mode == QLatin1String( "none" ) ) { dxfSymbologyMode = QgsDxfExport::NoSymbology; } else if ( mode == QLatin1String( "symbollayer" ) ) { dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology; } else if ( mode == QLatin1String( "feature" ) ) { dxfSymbologyMode = QgsDxfExport::FeatureSymbology; } else { std::cerr << "invalid dxf symbology mode " << mode.toStdString() << std::endl; return 2; } } else if ( arg == QLatin1String( "--dxf-scale-denom" ) ) { bool ok; QString scale( args[++i] ); dxfScale = scale.toDouble( &ok ); if ( !ok ) { std::cerr << "invalid dxf scale " << scale.toStdString() << std::endl; return 2; } } else if ( arg == QLatin1String( "--dxf-encoding" ) ) { dxfEncoding = args[++i]; } else if ( arg == QLatin1String( "--dxf-preset" ) ) { dxfPreset = args[++i]; } else if ( arg == QLatin1String( "--" ) ) { for ( i++; i < args.size(); ++i ) sFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) ); } else { sFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) ); } } } ///////////////////////////////////////////////////////////////////// // If no --project was specified, parse the args to look for a // // .qgs file and set myProjectFileName to it. This allows loading // // of a project file by clicking on it in various desktop managers // // where an appropriate mime-type has been set up. // ///////////////////////////////////////////////////////////////////// if ( sProjectFileName.isEmpty() ) { // check for a .qgs for ( int i = 0; i < args.size(); i++ ) { QString arg = QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ); if ( arg.endsWith( QLatin1String( ".qgs" ), Qt::CaseInsensitive ) ) { sProjectFileName = arg; break; } } } ///////////////////////////////////////////////////////////////////// // Now we have the handlers for the different behaviors... //////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Initialize the application and the translation stuff ///////////////////////////////////////////////////////////////////// #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(ANDROID) bool myUseGuiFlag = nullptr != getenv( "DISPLAY" ); #else bool myUseGuiFlag = true; #endif if ( !myUseGuiFlag ) { std::cerr << QObject::tr( "QGIS starting in non-interactive mode not supported.\n" "You are seeing this message most likely because you " "have no DISPLAY environment variable set.\n" ).toUtf8().constData(); exit( 1 ); //exit for now until a version of qgis is capabable of running non interactive } // GUI customization is enabled according to settings (loaded when instance is created) // we force disabled here if --nocustomization argument is used if ( !myCustomization ) { QgsCustomization::instance()->setEnabled( false ); } QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME ); QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN ); QCoreApplication::setApplicationName( QgsApplication::QGIS_APPLICATION_NAME ); QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false ); QgsSettings settings; if ( configLocalStorageLocation.isEmpty() ) { if ( getenv( "QGIS_CUSTOM_CONFIG_PATH" ) ) { configLocalStorageLocation = getenv( "QGIS_CUSTOM_CONFIG_PATH" ); } else if ( settings.contains( QStringLiteral( "profilesPath" ), QgsSettings::Core ) ) { configLocalStorageLocation = settings.value( QStringLiteral( "profilesPath" ), "", QgsSettings::Core ).toString(); QgsDebugMsg( QString( "Loading profiles path from global config at %1" ).arg( configLocalStorageLocation ) ); } // If it is still empty at this point we get it from the standard location. if ( configLocalStorageLocation.isEmpty() ) { configLocalStorageLocation = QStandardPaths::standardLocations( QStandardPaths::AppDataLocation ).value( 0 ); } } QString rootProfileFolder = QgsUserProfileManager::resolveProfilesFolder( configLocalStorageLocation ); QgsUserProfileManager manager( rootProfileFolder ); QgsUserProfile *profile = manager.getProfile( profileName, true ); QString profileFolder = profile->folder(); profileName = profile->name(); delete profile; QgsDebugMsg( "User profile details:" ); QgsDebugMsg( QString( "\t - %1" ).arg( profileName ) ); QgsDebugMsg( QString( "\t - %1" ).arg( profileFolder ) ); QgsDebugMsg( QString( "\t - %1" ).arg( rootProfileFolder ) ); QgsApplication myApp( argc, argv, myUseGuiFlag, profileFolder ); // SetUp the QgsSettings Global Settings: // - use the path specified with --globalsettingsfile path, // - use the environment if not found // - use a default location as a fallback if ( globalsettingsfile.isEmpty() ) { globalsettingsfile = getenv( "QGIS_GLOBAL_SETTINGS_FILE" ); } if ( globalsettingsfile.isEmpty() ) { QString default_globalsettingsfile = QgsApplication::pkgDataPath() + "/qgis_global_settings.ini"; if ( QFile::exists( default_globalsettingsfile ) ) { globalsettingsfile = default_globalsettingsfile; } } if ( !globalsettingsfile.isEmpty() ) { if ( ! QgsSettings::setGlobalSettingsPath( globalsettingsfile ) ) { QgsMessageLog::logMessage( QStringLiteral( "Invalid globalsettingsfile path: %1" ).arg( globalsettingsfile ), QStringLiteral( "QGIS" ) ); } else { QgsMessageLog::logMessage( QStringLiteral( "Successfully loaded globalsettingsfile path: %1" ).arg( globalsettingsfile ), QStringLiteral( "QGIS" ) ); } } // Settings migration is only supported on the default profile for now. if ( profileName == "default" ) { std::unique_ptr< QgsVersionMigration > migration( QgsVersionMigration::canMigrate( 20000, Qgis::QGIS_VERSION_INT ) ); if ( migration && ( mySettingsMigrationForce || migration->requiresMigration() ) ) { QgsDebugMsg( "RUNNING MIGRATION" ); migration->runMigration(); } } // Redefine QgsApplication::libraryPaths as necessary. // IMPORTANT: Do *after* QgsApplication myApp(...), but *before* Qt uses any plugins, // e.g. loading splash screen, setting window icon, etc. // Always honor QT_PLUGIN_PATH env var or qt.conf, which will // be part of libraryPaths just after QgsApplication creation. #ifdef Q_OS_WIN // For non static builds on win (static builds are not supported) // we need to be sure we can find the qt image plugins. QCoreApplication::addLibraryPath( QApplication::applicationDirPath() + QDir::separator() + "qtplugins" ); #endif #ifdef Q_OS_MAC // Resulting libraryPaths has critical QGIS plugin paths first, then any Qt plugin paths, then // any dev-defined paths (in app's qt.conf) and/or user-defined paths (QT_PLUGIN_PATH env var). // // NOTE: Minimizes, though does not fully protect against, crashes due to dev/user-defined libs // built against a different Qt/QGIS, while still allowing custom C++ plugins to load. QStringList libPaths( QCoreApplication::libraryPaths() ); QgsDebugMsgLevel( QStringLiteral( "Initial macOS QCoreApplication::libraryPaths: %1" ) .arg( libPaths.join( " " ) ), 4 ); // Strip all critical paths that should always be prepended if ( libPaths.removeAll( QDir::cleanPath( QgsApplication::pluginPath() ) ) ) { QgsDebugMsgLevel( QStringLiteral( "QgsApplication::pluginPath removed from initial libraryPaths" ), 4 ); } if ( libPaths.removeAll( QCoreApplication::applicationDirPath() ) ) { QgsDebugMsgLevel( QStringLiteral( "QCoreApplication::applicationDirPath removed from initial libraryPaths" ), 4 ); } // Prepend path, so a standard Qt bundle directory is parsed QgsDebugMsgLevel( QStringLiteral( "Prepending QCoreApplication::applicationDirPath to libraryPaths" ), 4 ); libPaths.prepend( QCoreApplication::applicationDirPath() ); // Check if we are running in a 'release' app bundle, i.e. contains copied-in // standard Qt-specific plugin subdirectories (ones never created by QGIS, e.g. 'sqldrivers' is). // Note: bundleclicked(...) is inadequate to determine which *type* of bundle was opened, e.g. release or build dir. // An app bundled with QGIS_MACAPP_BUNDLE > 0 is considered a release bundle. QString relLibPath( QDir::cleanPath( QCoreApplication::applicationDirPath().append( "/../PlugIns" ) ) ); // Note: relLibPath becomes the defacto QT_PLUGINS_DIR of a release app bundle if ( QFile::exists( relLibPath + QStringLiteral( "/imageformats" ) ) && QFile::exists( relLibPath + QStringLiteral( "/codecs" ) ) ) { // We are in a release app bundle. // Strip QT_PLUGINS_DIR because it will crash a launched release app bundle, since // the appropriate Qt frameworks and plugins have been copied into the bundle. if ( libPaths.removeAll( QT_PLUGINS_DIR ) ) { QgsDebugMsgLevel( QStringLiteral( "QT_PLUGINS_DIR removed from initial libraryPaths" ), 4 ); } // Prepend the Plugins path, so copied-in Qt plugin bundle directories are parsed. QgsDebugMsgLevel( QStringLiteral( "Prepending <bundle>/Plugins to libraryPaths" ), 4 ); libPaths.prepend( relLibPath ); // TODO: see if this or another method can be used to avoid QCA's install prefix plugins // from being parsed and loaded (causes multi-Qt-loaded errors when bundled Qt should // be the only one loaded). QCA core (> v2.1.3) needs an update first. //setenv( "QCA_PLUGIN_PATH", relLibPath.toUtf8().constData(), 1 ); } else { // We are either running from build dir bundle, or launching Mach-O binary directly. // Add system Qt plugins, since they are not bundled, and not always referenced by default. // An app bundled with QGIS_MACAPP_BUNDLE = 0 will still have Plugins/qgis in it. // Note: Don't always prepend. // User may have already defined it in QT_PLUGIN_PATH in a specific order. if ( !libPaths.contains( QT_PLUGINS_DIR ) ) { QgsDebugMsgLevel( QStringLiteral( "Prepending QT_PLUGINS_DIR to libraryPaths" ), 4 ); libPaths.prepend( QT_PLUGINS_DIR ); } } QgsDebugMsgLevel( QStringLiteral( "Prepending QgsApplication::pluginPath to libraryPaths" ), 4 ); libPaths.prepend( QDir::cleanPath( QgsApplication::pluginPath() ) ); // Redefine library search paths. QCoreApplication::setLibraryPaths( libPaths ); QgsDebugMsgLevel( QStringLiteral( "Rewritten macOS QCoreApplication::libraryPaths: %1" ) .arg( QCoreApplication::libraryPaths().join( " " ) ), 4 ); #endif #ifdef Q_OS_MAC // Set hidpi icons; use SVG icons, as PNGs will be relatively too small QCoreApplication::setAttribute( Qt::AA_UseHighDpiPixmaps ); // Set 1024x1024 icon for dock, app switcher, etc., rendering myApp.setWindowIcon( QIcon( QgsApplication::iconsPath() + QStringLiteral( "qgis-icon-macos.png" ) ) ); #else myApp.setWindowIcon( QIcon( QgsApplication::appIconPath() ) ); #endif // TODO: use QgsSettings QSettings *customizationsettings = nullptr; // Using the customizationfile option always overrides the option and config path options. if ( !customizationfile.isEmpty() ) { customizationsettings = new QSettings( customizationfile, QSettings::IniFormat ); QgsCustomization::instance()->setEnabled( true ); } else { customizationsettings = new QSettings( QStringLiteral( "QGIS" ), QStringLiteral( "QGISCUSTOMIZATION2" ) ); } // Load and set possible default customization, must be done after QgsApplication init and QgsSettings ( QCoreApplication ) init QgsCustomization::instance()->setSettings( customizationsettings ); QgsCustomization::instance()->loadDefault(); #ifdef Q_OS_MACX // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH // is not already defined, use the GDAL plugins in the application bundle. QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) ); if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) ) { setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 ); } // Point GDAL_DATA at any GDAL share directory embedded in the app bundle if ( !getenv( "GDAL_DATA" ) ) { QStringList gdalShares; QString appResources( QDir::cleanPath( QgsApplication::pkgDataPath() ) ); gdalShares << QCoreApplication::applicationDirPath().append( "/share/gdal" ) << appResources.append( "/share/gdal" ) << appResources.append( "/gdal" ); Q_FOREACH ( const QString &gdalShare, gdalShares ) { if ( QFile::exists( gdalShare ) ) { setenv( "GDAL_DATA", gdalShare.toUtf8().constData(), 1 ); break; } } }
int main(int argc, char *argv[]) { int ch; char *progname = argv[0]; // read in optional command line arguments while ((ch = getopt(argc, argv, "A:C:D:I:L:m:M:N:p:P:q:r:R:s:S:t:T:u:U:w:W:z:Z?")) != -1) { switch (ch) { case 'A': DURATION_ALLOPATRY = atoi(optarg); break; case 'C': CUTOFF = strtod(optarg, (char**)NULL); break; case 'D': DETERMINISTIC = atoi(optarg); break; case 'I': INITIAL_CONDITION = atoi(optarg); break; case 'L': nSITES_PER_WINDOW = atoi(optarg); break; case 'm': MIGRATION_RATE = strtod(optarg, (char **)NULL); break; case 'M': MODEL_TYPE = atoi(optarg); break; case 'N': TOTAL_N = atoi(optarg); break; case 'p': PROB_MUT_BENEFICIAL = strtod(optarg, (char **)NULL); break; case 'P': PROB_MUT_BG = strtod(optarg, (char **)NULL); break; case 'q': PROB_MUT_DIVERGENT = strtod(optarg, (char **)NULL); break; case 'Q': HIGH_RECOMB_PROB_PER_KB = strtod(optarg, (char **)NULL); break; case 'r': LOW_RECOMB_PROB_PER_KB = strtod(optarg, (char **)NULL); break; case 'R': nGENOMIC_REGIONS = atoi(optarg); break; case 's': MEAN_S_BENEFICIAL = strtod(optarg, (char **)NULL); break; case 'S': MEAN_S_BG = strtod(optarg, (char **)NULL); break; case 't': MEAN_S_DIVERGENT = strtod(optarg, (char **)NULL); break; case 'T': TOTAL_GENERATIONS = atoi(optarg); break; case 'u': MU_LOW = strtod(optarg, (char **)NULL); break; case 'U': MU_HIGH = strtod(optarg, (char **)NULL); break; case 'w': WINDOW_SIZE_BASES = atoi(optarg); break; case 'W': nWINDOWS_PER_REGION = atoi(optarg); break; case 'z': MONITOR_PROGRESS = atoi(optarg); break; case 'Z': useShortTestValuesOfParameters(); break; case '?': default: usage(progname); exit(-1); } } int *demeIndexes; demeIndexes = (int *) malloc( (sizeof(int) * TOTAL_N * nDEMES)); // set up RNGsetup(); initializePopulation(); openDataRecordingFiles(); // main operations for ( t = 1; t <= TOTAL_GENERATIONS; t++ ) { if ( t > DURATION_ALLOPATRY ) migration( demeIndexes ); reproduction( demeIndexes ); calculateMetricsAndStats(); if ( MONITOR_PROGRESS ) { if ( t % MONITOR_PROGRESS == 0 ) fprintf(stdout, "%li\n", t); } } finalPrints(); // free blocks from malloc free(genomeMap); free(genotypes); free(isVariableSite); free(fixedAllele); free(alleleFrequenciesByDeme); free(alleleSelectionCoeffs); free(demeLocations); free(demeIndexes); free(regionFlags); free(windowFlags); free(regionMembership); free(windowMembership); free(mutationRateClass); free(alleleFrequencies); // close files fclose(mutationLog); fclose(alleleFrequenciesOverTime); fclose(fixationLog); fclose(piOverTime); fclose(DaOverTime); fclose(DxyOverTime); fclose(variableLociOverTime); return 0; }
bool XMLConfigReader::read() { bool error = false; if (configFile && configFile->exists() && joystick) { xml->clear(); if (!configFile->isOpen()) { configFile->open(QFile::ReadOnly | QFile::Text); xml->setDevice(configFile); } xml->readNextStartElement(); if (xml->name() != joystick->getXmlName()) { xml->raiseError("Root node is not a joystick"); } else if (xml->name() == Joystick::xmlName) { XMLConfigMigration migration(xml); if (migration.requiresMigration()) { QString migrationString = migration.migrate(); if (migrationString.length() > 0) { // Remove QFile from reader and clear state xml->clear(); // Add converted XML string to reader xml->addData(migrationString); // Skip joystick root node xml->readNextStartElement(); // Close current config file configFile->close(); // Write converted XML to file configFile->open(QFile::WriteOnly | QFile::Text); if (configFile->isOpen()) { configFile->write(migrationString.toLocal8Bit()); configFile->close(); } else { xml->raiseError(tr("Could not write updated profile XML to file %1.").arg(configFile->fileName())); } } } } while (!xml->atEnd()) { if (xml->name() == joystick->getXmlName() && xml->isStartElement()) { joystick->readConfig(xml); } else { // If none of the above, skip the element xml->skipCurrentElement(); } xml->readNextStartElement(); } if (configFile->isOpen()) { configFile->close(); } if (xml->hasError() && xml->error() != QXmlStreamReader::PrematureEndOfDocumentError) { error = true; } else if (xml->hasError() && xml->error() == QXmlStreamReader::PrematureEndOfDocumentError) { xml->clear(); } } return error; }
/** * @brief Island-based genetic algorithm model running in different modes: Sequential, CPU or GPU only and Heterogeneous (full cooperation between all available OpenCL devices) * @param subpops The initial subpopulations * @param devicesObject Structure containing the OpenCL variables of a device * @param trDataBase The training database which will contain the instances and the features * @param selInstances The instances choosen as initial centroids * @param conf The structure with all configuration parameters */ void agIslands(Individual *const subpops, CLDevice *const devicesObject, const float *const trDataBase, const int *const selInstances, const Config *const conf) { /********** MPI variables ***********/ MPI_Datatype Individual_MPI_type; MPI_Datatype array_of_types[3] = {MPI_UNSIGNED_CHAR, MPI_FLOAT, MPI_INT}; int array_of_blocklengths[3] = {conf -> nFeatures, conf -> nObjectives + 1, 2}; MPI_Aint array_of_displacement[3]; MPI_Status status; /******* Measure and start the master-worker algorithm *******/ MPI_Barrier(MPI_COMM_WORLD); /******* Each process dinamically will request subpopulations *******/ // Master if (conf -> mpiRank == 0) { double timeStart = omp_get_wtime(); int *nIndsFronts0 = new int[conf -> nSubpopulations]; int finalFront0; // The master receives the number of subpopulations that each worker can process int workerCapacities[conf -> mpiSize - 1]; MPI_Request requests[conf -> mpiSize - 1]; for (int p = 1; p < conf -> mpiSize; ++p) { MPI_Irecv(&workerCapacities[p - 1], 1, MPI_INT, p, MPI_ANY_TAG, MPI_COMM_WORLD, &requests[p - 1]); } // The "Individual" datatype must be converted to a MPI datatype and commit it array_of_displacement[0] = (size_t) &(subpops[0].chromosome[0]) - (size_t) &(subpops[0]); array_of_displacement[1] = (size_t) &(subpops[0].fitness[0]) - (size_t) &(subpops[0]); array_of_displacement[2] = (size_t) &(subpops[0].rank) - (size_t) &(subpops[0]); MPI_Type_create_struct(3, array_of_blocklengths, array_of_displacement, array_of_types, &Individual_MPI_type); MPI_Type_commit(&Individual_MPI_type); MPI_Waitall(conf -> mpiSize - 1, requests, MPI_STATUSES_IGNORE); int maxChunk = std::min(*std::max_element(workerCapacities, workerCapacities + conf -> mpiSize - 1), conf -> nSubpopulations); /********** In each migration the individuals are exchanged between subpopulations of different nodes ***********/ for (int gMig = 0; gMig < conf -> nGlobalMigrations; ++gMig) { // Send some work to the workers int nextWork = 0; int sent = 0; int mpiTag = (gMig == 0) ? INITIALIZE : IGNORE_VALUE; for (int p = 1; p < conf -> mpiSize && nextWork < conf -> nSubpopulations; ++p) { int finallyWork = std::min(workerCapacities[p - 1], conf -> nSubpopulations - nextWork); int popIndex = nextWork * conf -> familySize; MPI_Isend(subpops + popIndex, finallyWork * conf -> familySize, Individual_MPI_type, p, mpiTag, MPI_COMM_WORLD, &requests[p - 1]); nextWork += finallyWork; ++sent; } MPI_Waitall(sent, requests, MPI_STATUSES_IGNORE); // Dynamically distribute the subpopulations int receivedWork = 0; int receivedPtr = 0; while (nextWork < conf -> nSubpopulations) { MPI_Recv(subpops + (receivedPtr * conf -> familySize), maxChunk * conf -> familySize, Individual_MPI_type, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Recv(nIndsFronts0 + receivedPtr, maxChunk, MPI_INT, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_INT, &receivedWork); receivedPtr += receivedWork; int finallyWork = std::min(workerCapacities[status.MPI_SOURCE - 1], conf -> nSubpopulations - nextWork); int popIndex = nextWork * conf -> familySize; MPI_Send(subpops + popIndex, finallyWork * conf -> familySize, Individual_MPI_type, status.MPI_SOURCE, mpiTag, MPI_COMM_WORLD); nextWork += finallyWork; } // Receive the remaining work while (receivedPtr < conf -> nSubpopulations) { MPI_Recv(subpops + (receivedPtr * conf -> familySize), maxChunk * conf -> familySize, Individual_MPI_type, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Recv(nIndsFronts0 + receivedPtr, maxChunk, MPI_INT, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_INT, &receivedWork); receivedPtr += receivedWork; } // Migration process between subpopulations of different nodes if (gMig != conf -> nGlobalMigrations - 1 && conf -> nSubpopulations > 1) { migration(subpops, conf -> nSubpopulations, nIndsFronts0, conf); #pragma omp parallel for for (int sp = 0; sp < conf -> nSubpopulations; ++sp) { int popIndex = sp * conf -> familySize; // The crowding distance of the subpopulation is initialized again for the next nonDominationSort for (int i = popIndex; i < popIndex + conf -> subpopulationSize; ++i) { subpops[i].crowding = 0.0f; } nonDominationSort(subpops + popIndex, conf -> subpopulationSize, conf); } } } // Notify to all workers that the work has finished for (int p = 1; p < conf -> mpiSize; ++p) { MPI_Isend(0, 0, MPI_INT, p, FINISH, MPI_COMM_WORLD, &requests[p - 1]); } /********** Recombination process ***********/ if (conf -> nSubpopulations > 1) { for (int sp = 0; sp < conf -> nSubpopulations; ++sp) { memcpy(subpops + (sp * conf -> subpopulationSize), subpops + (sp * conf -> familySize), conf -> subpopulationSize * sizeof(Individual)); } // The crowding distance of the subpopulation is initialized again for the next nonDominationSort #pragma omp parallel for for (int i = 0; i < conf -> worldSize; ++i) { subpops[i].crowding = 0.0f; } finalFront0 = std::min(conf -> subpopulationSize, nonDominationSort(subpops, conf -> worldSize, conf)); } else { finalFront0 = nIndsFronts0[0]; } // All process must reach this point in order to provide a real time measure MPI_Waitall(conf -> mpiSize - 1, requests, MPI_STATUSES_IGNORE); MPI_Barrier(MPI_COMM_WORLD); fprintf(stdout, "%.10g\n", (omp_get_wtime() - timeStart) * 1000.0); // Get the hypervolume fprintf(stdout, "%.6g\n", getHypervolume(subpops, finalFront0, conf)); // Generation of the data file for Gnuplot generateDataPlot(subpops, finalFront0, conf); // Exclusive variables used by the master are released delete[] nIndsFronts0; MPI_Type_free(&Individual_MPI_type); } // Workers else { // This is only for sequential benchmark const bool isSequential = (conf -> nDevices == 0 && conf -> ompThreads < 2); const int nDevices = (isSequential) ? conf -> nSubpopulations : std::max(1, conf -> nDevices + (conf -> ompThreads > 0)); int nChildren[nDevices]; int nIndsFronts0[nDevices]; MPI_Request requests[2]; // The worker tells to the master how many subpopulations can be processed MPI_Isend(&nDevices, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &(requests[0])); MPI_Request_free(&(requests[0])); // Each worker will compute as many subpopulations as OpenCL devices at most Individual *subpops = new Individual[nDevices * conf -> familySize]; // Create MPI datatype for the individuals and commit it array_of_displacement[0] = (size_t) &(subpops[0].chromosome[0]) - (size_t) &(subpops[0]); array_of_displacement[1] = (size_t) &(subpops[0].fitness[0]) - (size_t) &(subpops[0]); array_of_displacement[2] = (size_t) &(subpops[0].rank) - (size_t) &(subpops[0]); MPI_Type_create_struct(3, array_of_blocklengths, array_of_displacement, array_of_types, &Individual_MPI_type); MPI_Type_commit(&Individual_MPI_type); // The worker receives as many subpopulations as number of OpenCL devices at most MPI_Recv(subpops, nDevices * conf -> familySize, Individual_MPI_type, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); while (status.MPI_TAG != FINISH) { int receivedWork; MPI_Get_count(&status, Individual_MPI_type, &receivedWork); int nSubpopulations = receivedWork / conf -> familySize; int nThreads = (isSequential) ? 1 : std::min(nDevices, nSubpopulations); if (status.MPI_TAG == INITIALIZE) { /********** Multi-objective individuals evaluation over all subpopulations ***********/ omp_set_nested(1); #pragma omp parallel for num_threads(nThreads) schedule(dynamic, 1) for (int sp = 0; sp < nSubpopulations; ++sp) { int popIndex = sp * conf -> familySize; if (isSequential) { evaluationCPU(subpops + popIndex, conf -> subpopulationSize, trDataBase, selInstances, 1, conf); } else if (nSubpopulations == 1) { evaluationHET(subpops + popIndex, conf -> subpopulationSize, devicesObject, nDevices, trDataBase, selInstances, conf); } else { evaluationHET(subpops + popIndex, conf -> subpopulationSize, &devicesObject[omp_get_thread_num()], 1, trDataBase, selInstances, conf); } // Fitness normalization normalizeFitness(subpops + popIndex, conf -> subpopulationSize, conf); } /********** Sort each subpopulation with the "Non-Domination-Sort" method ***********/ #pragma omp parallel for for (int sp = 0; sp < nSubpopulations; ++sp) { int popIndex = sp * conf -> familySize; nIndsFronts0[sp] = nonDominationSort(subpops + popIndex, conf -> subpopulationSize, conf); } } /********** In each migration the individuals are exchanged between subpopulations of the same node ***********/ int nLocalMigrations = (nSubpopulations > 1) ? conf -> nLocalMigrations : 1; for (int lMig = 0; lMig < nLocalMigrations; ++lMig) { /********** Start the evolution process ***********/ for (int g = 0; g < conf -> nGenerations; ++g) { /********** Fill the mating pool and perform crossover ***********/ #pragma omp parallel for for (int sp = 0; sp < nSubpopulations; ++sp) { const int *const pool = getPool(conf); int popIndex = sp * conf -> familySize; nChildren[sp] = crossoverUniform(subpops + popIndex, pool, conf); // Local resources used are released delete[] pool; } /********** Multi-objective individuals evaluation over all subpopulations ***********/ #pragma omp parallel for num_threads(nThreads) schedule(dynamic, 1) for (int sp = 0; sp < nSubpopulations; ++sp) { int popIndex = sp * conf -> familySize; if (isSequential) { evaluationCPU(subpops + popIndex + conf -> subpopulationSize, nChildren[sp], trDataBase, selInstances, 1, conf); } else if (nSubpopulations == 1) { evaluationHET(subpops + popIndex + conf -> subpopulationSize, nChildren[sp], devicesObject, nDevices, trDataBase, selInstances, conf); } else { evaluationHET(subpops + popIndex + conf -> subpopulationSize, nChildren[sp], &devicesObject[omp_get_thread_num()], 1, trDataBase, selInstances, conf); } // Fitness normalization normalizeFitness(subpops + popIndex + conf -> subpopulationSize, nChildren[sp], conf); } /********** The crowding distance of the parents is initialized again for the next nonDominationSort ***********/ #pragma omp parallel for for (int sp = 0; sp < nSubpopulations; ++sp) { int popIndex = sp * conf -> familySize; for (int i = popIndex; i < popIndex + conf -> subpopulationSize; ++i) { subpops[i].crowding = 0.0f; } // Replace subpopulation // Parents and children are sorted by rank and crowding distance. // The first "subpopulationSize" individuals will advance the next generation nIndsFronts0[sp] = nonDominationSort(subpops + popIndex, conf -> subpopulationSize + nChildren[sp], conf); } } // Migration process between subpopulations of the same node if (lMig != nLocalMigrations - 1 && nSubpopulations > 1) { migration(subpops, nSubpopulations, nIndsFronts0, conf); #pragma omp parallel for for (int sp = 0; sp < nSubpopulations; ++sp) { int popIndex = sp * conf -> familySize; // The crowding distance of the subpopulation is initialized again for the next nonDominationSort for (int i = popIndex; i < popIndex + conf -> subpopulationSize; ++i) { subpops[i].crowding = 0.0f; } nonDominationSort(subpops + popIndex, conf -> subpopulationSize, conf); } } } // The worker send to the master the subpopulations already evaluated and will request new work MPI_Isend(subpops, receivedWork, Individual_MPI_type, 0, 0, MPI_COMM_WORLD, &(requests[0])); MPI_Isend(nIndsFronts0, nSubpopulations, MPI_INT, 0, 0, MPI_COMM_WORLD, &(requests[1])); MPI_Waitall(2, requests, MPI_STATUSES_IGNORE); MPI_Recv(subpops, nDevices * conf -> familySize, Individual_MPI_type, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); } // All process must reach this point in order to provide a real time measure MPI_Barrier(MPI_COMM_WORLD); // Exclusive variables used by the workers are released delete[] subpops; MPI_Type_free(&Individual_MPI_type); } }
Arc::MCC_Status ARexService::MigrateActivity(ARexGMConfig& config,Arc::XMLNode in,Arc::XMLNode out,const std::string& clientid) { /* MigrateActivity ActivityIdentifier (wsa:EndpointReferenceType) ActivityDocument jsdl:JobDefinition ForceMigration MigrateActivityResponse ActivityIdentifier (wsa:EndpointReferenceType) ActivityDocument jsdl:JobDefinition NotAuthorizedFault NotAcceptingNewActivitiesFault UnsupportedFeatureFault InvalidRequestMessageFault */ { std::string s; in.GetXML(s); logger_.msg(Arc::VERBOSE, "MigrateActivity: request = \n%s", s); }; Arc::WSAEndpointReference id(in["ActivityIdentifier"]); if(!(Arc::XMLNode)id) { // Wrong request logger_.msg(Arc::ERROR, "MigrateActivitys: no ActivityIdentifier found"); Arc::SOAPFault fault(out.Parent(),Arc::SOAPFault::Sender,"Can't find ActivityIdentifier element in request"); InvalidRequestMessageFault(fault,"jsdl:ActivityIdentifier","Element is missing"); out.Destroy(); return Arc::MCC_Status(); }; std::string migrateid = Arc::WSAEndpointReference(id).Address() + "/" + (std::string)Arc::WSAEndpointReference(id).ReferenceParameters()["a-rex:JobID"]; if(migrateid.empty()) { // EPR is wrongly formated or not an A-REX EPR logger_.msg(Arc::ERROR, "MigrateActivity: EPR contains no JobID"); Arc::SOAPFault fault(out.Parent(),Arc::SOAPFault::Sender,"Can't find JobID element in ActivityIdentifier"); InvalidRequestMessageFault(fault,"a-rex:JobID","Element is missing"); out.Destroy(); return Arc::MCC_Status(); }; // HPC Basic Profile 1.0 comply (these fault handlings are defined in the KnowARC standards // conformance roadmap 2nd release) // End of the HPC BP 1.0 fault handling part std::string delegation; Arc::XMLNode delegated_token = in["arcdeleg:DelegatedToken"]; if(delegated_token) { // Client wants to delegate credentials if(!delegation_stores_.DelegatedToken(config.GmConfig().DelegationDir(),delegated_token,config.GridName(),delegation)) { // Failed to accept delegation (report as bad request) logger_.msg(Arc::ERROR, "MigrateActivity: Failed to accept delegation"); Arc::SOAPFault fault(out.Parent(),Arc::SOAPFault::Sender,"Failed to accept delegation"); InvalidRequestMessageFault(fault,"arcdeleg:DelegatedToken","This token does not exist"); out.Destroy(); return Arc::MCC_Status(); }; }; if( !(in["ActivityDocument"]["JobDefinition"])) { /* // First try to get job desc from old cluster logger_.msg(Arc::VERBOSE, "MigrateActivity: no job description found try to get it from old cluster"); Arc::MCCConfig cfg; // TODO: //if (!proxyPath.empty()) cfg.AddProxy(delegation); //if (!certificatePath.empty()) //cfg.AddCertificate(certificatePath); //if (!keyPath.empty()) //cfg.AddPrivateKey(keyPath); //if (!caCertificatesDir.empty()) //cfg.AddCADir(caCertificatesDir); Arc::URL url(migrateid); Arc::PathIterator pi(url.Path(), true); url.ChangePath(*pi); Arc::AREXClient ac(url, cfg); Arc::NS ns; ns["a-rex"] = "http://www.nordugrid.org/schemas/a-rex"; ns["bes-factory"] = "http://schemas.ggf.org/bes/2006/08/bes-factory"; ns["wsa"] = "http://www.w3.org/2005/08/addressing"; ns["jsdl"] = "http://schemas.ggf.org/jsdl/2005/11/jsdl"; ns["jsdl-posix"] = "http://schemas.ggf.org/jsdl/2005/11/jsdl-posix"; ns["jsdl-arc"] = "http://www.nordugrid.org/ws/schemas/jsdl-arc"; ns["jsdl-hpcpa"] = "http://schemas.ggf.org/jsdl/2006/07/jsdl-hpcpa"; Arc::XMLNode id(ns, "ActivityIdentifier"); id.NewChild("wsa:Address") = url.str(); id.NewChild("wsa:ReferenceParameters").NewChild("a-rex:JobID") = pi.Rest(); std::string idstr; id.GetXML(idstr); std::string desc_str; if (ac.getdesc(idstr,desc_str)){ Arc::JobDescription desc; desc.setSource(desc_str); if (desc.isValid()) { logger_.msg(Arc::INFO,"Valid job description obtained"); if ( !( in["ActivityDocument"] ) ) in.NewChild("bes-factory:ActivityDocument"); Arc::XMLNode XMLdesc; desc.getXML(XMLdesc); in["ActivityDocument"].NewChild(XMLdesc); } else { // Wrongly formatted job description logger_.msg(Arc::ERROR, "MigrateActivity: job description could not be fetch from old cluster"); Arc::SOAPFault fault(out.Parent(),Arc::SOAPFault::Sender,"Can't find JobDefinition element in request"); InvalidRequestMessageFault(fault,"jsdl:JobDefinition","Element is missing"); out.Destroy(); return Arc::MCC_Status(); } } */ //else { // Not able to get job description logger_.msg(Arc::ERROR, "MigrateActivity: no job description found"); //logger_.msg(Arc::ERROR, "MigrateActivity: job description could not be fetch from old cluster"); Arc::SOAPFault fault(out.Parent(),Arc::SOAPFault::Sender,"Can't find JobDefinition element in request"); InvalidRequestMessageFault(fault,"jsdl:JobDefinition","Element is missing"); out.Destroy(); return Arc::MCC_Status(); //} }; Arc::XMLNode jsdl = in["ActivityDocument"]["JobDefinition"]; Arc::NS ns; // Creating migration XMLNode Arc::XMLNode migration(ns, "Migration"); migration.NewChild("ActivityIdentifier") = migrateid; if( (bool)in["ForceMigration"]){ migration.NewChild("ForceMigration") = (std::string)in["ForceMigration"]; } else { migration.NewChild("ForceMigration") = "true"; } std::string migrationStr; migration.GetDoc(migrationStr, true); logger_.msg(Arc::INFO, "Migration XML sent to AREXJob: %s", migrationStr); JobIDGeneratorARC idgenerator(config.Endpoint()); ARexJob job(jsdl,config,delegation,clientid,logger_,idgenerator,migration); if(!job) { ARexJobFailure failure_type = job; std::string failure = job.Failure(); switch(failure_type) { case ARexJobDescriptionUnsupportedError: { Arc::SOAPFault fault(out.Parent(),Arc::SOAPFault::Sender,"Unsupported feature in job description"); UnsupportedFeatureFault(fault,failure); }; break; case ARexJobDescriptionMissingError: { Arc::SOAPFault fault(out.Parent(),Arc::SOAPFault::Sender,"Missing needed element in job description"); UnsupportedFeatureFault(fault,failure); }; break; case ARexJobDescriptionLogicalError: { std::string element; std::string::size_type pos = failure.find(' '); if(pos != std::string::npos) { element=failure.substr(0,pos); failure=failure.substr(pos+1); }; Arc::SOAPFault fault(out.Parent(),Arc::SOAPFault::Sender,"Logical error in job description"); InvalidRequestMessageFault(fault,element,failure); }; break; default: { logger_.msg(Arc::ERROR, "MigrateActivity: Failed to migrate new job: %s",failure); // Failed to migrate new job (no corresponding BES fault defined - using generic SOAP error) logger_.msg(Arc::ERROR, "MigrateActivity: Failed to migrate new job"); Arc::SOAPFault fault(out.Parent(),Arc::SOAPFault::Sender,("Failed to migrate new activity: "+failure).c_str()); GenericFault(fault); }; break; }; out.Destroy(); return Arc::MCC_Status(); }; // Make SOAP response Arc::WSAEndpointReference identifier(out.NewChild("bes-factory:ActivityIdentifier")); // Make job's ID identifier.Address(config.Endpoint()); // address of service identifier.ReferenceParameters().NewChild("a-rex:JobID")=job.ID(); identifier.ReferenceParameters().NewChild("a-rex:JobSessionDir")=config.Endpoint()+"/"+job.ID(); out.NewChild(in["ActivityDocument"]); logger_.msg(Arc::VERBOSE, "MigrateActivity finished successfully"); { std::string s; out.GetXML(s); logger_.msg(Arc::VERBOSE, "MigrateActivity: response = \n%s", s); }; /* Needs to kill old job */ return Arc::MCC_Status(Arc::STATUS_OK); }
void problem_init(int argc, char* argv[]){ /* Setup constants */ boxsize = 3; // in AU integrator = WHFAST; integrator_whfast_corrector = 0; integrator_whfast_synchronize_manually = 0; tmax = atof(argv[2]); // in year/(2*pi) Keplername = argv[1]; //Kepler system being investigated, Must be first string after ./nbody! p_suppress = 0; //If = 1, suppress all print statements double RT = 0.06; //Resonance Threshold - if abs(P2/2*P1 - 1) < RT, then close enough to resonance double timefac = 25.0; //Number of kicks per orbital period (of closest planet) /* Migration constants */ mig_forces = 1; //If ==0, no migration. K = 100; //tau_a/tau_e ratio. I.e. Lee & Peale (2002) e_ini = atof(argv[3]); //atof(argv[3]); //initial eccentricity of the planets afac = atof(argv[4]); //Factor to increase 'a' of OUTER planets by. double iptmig_fac = atof(argv[5]); //reduction factor of inner planet's t_mig (lower value = more eccentricity) double Cin = atof(argv[6]); //migration speed of outer planet inwards. Nominal is 6 /* Tide constants */ tides_on = 1; //If ==0, then no tidal torques on planets. tide_force = 0; //if ==1, implement tides as *forces*, not as e' and a'. double k2fac = atof(argv[7]); //multiply k2 by this factor inner_only = 0; //if =1, allow only the inner planet to evolve under tidal influence //k2fac_check(Keplername,&k2fac); //For special systems, make sure that if k2fac is set too high, it's reduced. #ifdef OPENGL display_wire = 1; #endif // OPENGL init_box(); printf("%f k2fac \n \n \n",k2fac); //Naming naming(Keplername, txt_file, K, iptmig_fac, e_ini, k2fac, tide_force); // Initial vars if(p_suppress == 0) printf("You have chosen: %s \n",Keplername); double Ms,Rs,a,mp,rp,k2,Q,max_t_mig=0, P_temp; int char_val; //Star & Planet 1 readplanets(Keplername,txt_file,&char_val,&_N,&Ms,&Rs,&mp,&rp,&P_temp,p_suppress); if(mig_forces == 0 && p_suppress == 0) printf("--> Migration is *off* \n"); if(tides_on == 0 && p_suppress == 0) printf("--> Tides are *off* \n"); struct particle star; //Star MUST be the first particle added. star.x = 0; star.y = 0; star.z = 0; star.vx = 0; star.vy = 0; star.vz = 0; star.ax = 0; star.ay = 0; star.az = 0; star.m = Ms; star.r = Rs; particles_add(star); //timestep - units of 2pi*yr (required) dt = 2.*M_PI*P_temp/(365.*timefac); if(p_suppress == 0) printf("The timestep used for this simulation is (2pi*years): %f \n",dt); //Arrays, Extra slot for star, calloc sets values to 0 already. tau_a = calloc(sizeof(double),_N+1); //migration speed of semi-major axis tau_e = calloc(sizeof(double),_N+1); //migration (damp) speed of eccentricity lambda = calloc(sizeof(double),_N+1); //resonant angle for each planet omega = calloc(sizeof(double),_N+1); //argument of periapsis for each planet expmigfac = calloc(sizeof(double),_N+1); t_mig = calloc(sizeof(double),_N+1); t_damp = calloc(sizeof(double),_N+1); phi_i = calloc(sizeof(int),_N+1); //phi index (for outputting resonance angles) if(tide_force == 1){ //tidetau_a = calloc(sizeof(double),_N+1); tidetauinv_e = calloc(sizeof(double),_N+1); } double P[_N+1]; //array of period values, only needed locally P[1] = P_temp; if(inner_only == 1) planets_with_tides = 1; else planets_with_tides = _N+1; //planet 1 calcsemi(&a,Ms,P[1]); //I don't trust archive values. Make it all consistent migration(Keplername,tau_a, t_mig, t_damp, &expmigfac[1], 0, &max_t_mig, P, 1, RT, Ms, mp, iptmig_fac, a, afac, p_suppress, Cin); struct particle p = tools_init_orbit2d(Ms, mp, a*afac, e_ini, 0, 0.); tau_e[1] = tau_a[1]/K; assignk2Q(&k2, &Q, k2fac, rp); p.Q=Q; p.k2=k2; p.r = rp; particles_add(p); //print/writing stuff printf("System Properties: # planets=%d, Rs=%f, Ms=%f \n",_N, Rs, Ms); printwrite(1,txt_file,a,P[1],e_ini,mp,rp,k2/Q,tau_a[1],t_mig[1],t_damp[1],afac,p_suppress); //outer planets (i=0 is star) for(int i=2;i<_N+1;i++){ extractplanets(&char_val,&mp,&rp,&P[i],p_suppress); calcsemi(&a,Ms,P[i]); migration(Keplername,tau_a, t_mig, t_damp, &expmigfac[i], &phi_i[i], &max_t_mig, P, i, RT, Ms, mp, iptmig_fac, a, afac, p_suppress, Cin); struct particle p = tools_init_orbit2d(Ms, mp, a*afac, e_ini, 0, i*M_PI/4.); tau_e[i] = tau_a[i]/K; assignk2Q(&k2, &Q, k2fac, rp); p.Q = Q; p.k2 = k2; p.r = rp; particles_add(p); printwrite(i,txt_file,a,P[i],e_ini,mp,rp,k2/Q,tau_a[i],t_mig[i],t_damp[i],afac,p_suppress); } //tidal delay if(max_t_mig < 20000)tide_delay = 20000.; else tide_delay = max_t_mig + 20000.; //Have at least 30,000 years grace before turning on tides. double tide_delay_output = 0; if(tides_on == 1) tide_delay_output = tide_delay; FILE *write; write=fopen(txt_file, "a"); fprintf(write, "%f \n",tide_delay_output); fclose(write); tide_print = 0; problem_additional_forces = problem_migration_forces; //Set function pointer to add dissipative forces. integrator_force_is_velocitydependent = 1; if (integrator != WH){ // The WH integrator assumes a heliocentric coordinate system. tools_move_to_center_of_momentum(); } }