diff --git a/irit.gaml.extensions.database/src/msi/gama/database/geosql/GamaSqlConnection.java b/irit.gaml.extensions.database/src/msi/gama/database/geosql/GamaSqlConnection.java index 384ac9647f..6572a809ea 100644 --- a/irit.gaml.extensions.database/src/msi/gama/database/geosql/GamaSqlConnection.java +++ b/irit.gaml.extensions.database/src/msi/gama/database/geosql/GamaSqlConnection.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * GamaSqlConnection.java, in irit.gaml.extensions.database, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * GamaSqlConnection.java, in irit.gaml.extensions.database, is part of the source code of the GAMA modeling and + * simulation platform (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.database.geosql; @@ -55,34 +55,34 @@ public class GamaSqlConnection extends GamaGisFile { /** The Constant MYSQL. */ private static final String MYSQL = "mysql"; - + /** The Constant POSTGRES. */ private static final String POSTGRES = "postgres"; - + /** The Constant POSTGIS. */ private static final String POSTGIS = "postgis"; - + /** The Constant MSSQL. */ private static final String MSSQL = "sqlserver"; - + /** The Constant SQLITE. */ private static final String SQLITE = "spatialite"; - + /** The dbtype. */ private String dbtype = ""; - + /** The host. */ private String host = ""; - + /** The port. */ private String port = ""; - + /** The database. */ private String database = ""; - + /** The user. */ private String user = ""; - + /** The passwd. */ private String passwd = ""; @@ -93,7 +93,8 @@ public class GamaSqlConnection extends GamaGisFile { /** * Instantiates a new gama sql connection. * - * @param scope the scope + * @param scope + * the scope */ public GamaSqlConnection(final IScope scope) { super(scope, FileUtils.constructAbsoluteFilePath(scope, "getfun.shp", false), 0); @@ -103,8 +104,10 @@ public GamaSqlConnection(final IScope scope) { /** * Instantiates a new gama sql connection. * - * @param scope the scope - * @param params the params + * @param scope + * the scope + * @param params + * the params */ private GamaSqlConnection(final IScope scope, final Map params) { super(scope, FileUtils.constructAbsoluteFilePath(scope, "getfun.shp", false), 0); @@ -115,7 +118,8 @@ private GamaSqlConnection(final IScope scope, final Map params) /** * Sets the params. * - * @param scope the new params + * @param scope + * the new params */ private void setParams(final IScope scope) { setConnectionParameters(scope); @@ -124,7 +128,8 @@ private void setParams(final IScope scope) { /** * Sets the params. * - * @param params the params + * @param params + * the params */ private void setParams(final Map params) { setConnectionParameters(params); @@ -133,7 +138,8 @@ private void setParams(final Map params) { /** * Sets the connection parameters. * - * @param scope the new connection parameters + * @param scope + * the new connection parameters */ private void setConnectionParameters(final IScope scope) { final Map params = (Map) scope.getArg("params", IType.MAP); @@ -148,7 +154,8 @@ private void setConnectionParameters(final IScope scope) { /** * Sets the connection parameters. * - * @param params the params + * @param params + * the params */ private void setConnectionParameters(final Map params) { this.dbtype = (String) params.get("dbtype"); @@ -162,14 +169,15 @@ private void setConnectionParameters(final Map params) { /** * Creates the connection params. * - * @param scope the scope + * @param scope + * the scope * @return the map */ // Connect connection parameters with connection attributes of the object private Map createConnectionParams(final IScope scope) { final Map connectionParameters = new HashMap<>(); - if (dbtype.equalsIgnoreCase(GamaSqlConnection.POSTGRES) || dbtype.equalsIgnoreCase(GamaSqlConnection.POSTGIS)) { + if (GamaSqlConnection.POSTGRES.equalsIgnoreCase(dbtype) || GamaSqlConnection.POSTGIS.equalsIgnoreCase(dbtype)) { connectionParameters.put("host", host); connectionParameters.put("dbtype", dbtype); connectionParameters.put("port", port); @@ -178,14 +186,14 @@ private Map createConnectionParams(final IScope scope) { connectionParameters.put("passwd", passwd); // advanced - } else if (dbtype.equalsIgnoreCase(GamaSqlConnection.MYSQL)) { + } else if (GamaSqlConnection.MYSQL.equalsIgnoreCase(dbtype)) { connectionParameters.put(MySQLDataStoreFactory.DBTYPE.key, dbtype); connectionParameters.put(JDBCDataStoreFactory.HOST.key, host); connectionParameters.put(MySQLDataStoreFactory.PORT.key, Integer.valueOf(port)); connectionParameters.put(JDBCDataStoreFactory.DATABASE.key, database); connectionParameters.put(JDBCDataStoreFactory.USER.key, user); connectionParameters.put(JDBCDataStoreFactory.PASSWD.key, passwd); - } else if (dbtype.equalsIgnoreCase(GamaSqlConnection.MSSQL)) { + } else if (GamaSqlConnection.MSSQL.equalsIgnoreCase(dbtype)) { connectionParameters.put("host", host); connectionParameters.put("dbtype", dbtype); connectionParameters.put("port", port); @@ -193,7 +201,7 @@ private Map createConnectionParams(final IScope scope) { connectionParameters.put("user", user); connectionParameters.put("passwd", passwd); - } else if (dbtype.equalsIgnoreCase(GamaSqlConnection.SQLITE)) { + } else if (GamaSqlConnection.SQLITE.equalsIgnoreCase(dbtype)) { final String DBRelativeLocation = FileUtils.constructAbsoluteFilePath(scope, database, true); // String EXTRelativeLocation = // GamaPreferences.LIB_SPATIALITE.value(scope).getPath(); @@ -207,9 +215,11 @@ private Map createConnectionParams(final IScope scope) { /** * Connect. * - * @param scope the scope + * @param scope + * the scope * @return the data store - * @throws Exception the exception + * @throws Exception + * the exception */ /* * Create a connection to database with current connection parameter of the GamaSqlConnection object @@ -227,32 +237,33 @@ public DataStore Connect(final IScope scope) throws Exception { /** * Close. * - * @param scope the scope - * @throws GamaRuntimeException the gama runtime exception + * @param scope + * the scope + * @throws GamaRuntimeException + * the gama runtime exception */ /* * Close the current connection of of the GamaSqlConnection object */ public void close(final IScope scope) throws GamaRuntimeException { - if (dataStore != null) { - dataStore.dispose(); - } else + if (dataStore == null) throw GamaRuntimeException.error("The connection to " + this.database + " is not opened ", scope); + dataStore.dispose(); } /** * Sets the data store. * - * @param dataStore the new data store + * @param dataStore + * the new data store */ - public void setDataStore(final DataStore dataStore) { - this.dataStore = dataStore; - } + public void setDataStore(final DataStore dataStore) { this.dataStore = dataStore; } /** * Read table. * - * @param scope the scope + * @param scope + * the scope */ private void readTable(final IScope scope) { final String tableName = (String) scope.getArg("table", IType.STRING); @@ -263,9 +274,12 @@ private void readTable(final IScope scope) { /** * Read table. * - * @param scope the scope - * @param tableName the table name - * @param filterStr the filter str + * @param scope + * the scope + * @param tableName + * the table name + * @param filterStr + * the filter str */ private void readTable(final IScope scope, final String tableName, final String filterStr) { @@ -280,7 +294,7 @@ private void readTable(final IScope scope, final String tableName, final String // reader = store.getFeatureReader(); // final int i = 0; while (reader.hasNext()) { - scope.getGui().getStatus(scope).setSubStatusCompletion(index++ / (double) size); + scope.getGui().getStatus().setSubStatusCompletion(index++ / (double) size); final Feature feature = reader.next(); // DEBUG.LOG("Record " + i++ + ": " + @@ -299,7 +313,7 @@ private void readTable(final IScope scope, final String tableName, final String } catch (final Exception e) { throw GamaRuntimeException.create(e, scope); } finally { - scope.getGui().getStatus(scope).endSubStatus("Reading table " + tableName); + scope.getGui().getStatus().endSubStatus("Reading table " + tableName); } } @@ -316,7 +330,8 @@ protected void fillBuffer(final IScope scope) throws GamaRuntimeException { /** * Read. * - * @param scope the scope + * @param scope + * the scope */ public void read(final IScope scope) { fillBuffer(scope); @@ -335,20 +350,24 @@ private static class QueryInfo { /** The item number. */ private final int itemNumber; // Number of records - + /** The env. */ private final Envelope3D env; - + /** The features. */ private final SimpleFeatureCollection features; // data/recordsets /** * Instantiates a new query info. * - * @param scope the scope - * @param dStore the d store - * @param tableName the table name - * @param filterStr the filter str + * @param scope + * the scope + * @param dStore + * the d store + * @param tableName + * the table name + * @param filterStr + * the filter str */ QueryInfo(final IScope scope, final DataStore dStore, final String tableName, final String filterStr) { @@ -404,27 +423,21 @@ private static class QueryInfo { * * @return the size */ - public int getSize() { - return itemNumber; - } + public int getSize() { return itemNumber; } /** * Gets the envelope. * * @return the envelope */ - public Envelope3D getEnvelope() { - return env; - } + public Envelope3D getEnvelope() { return env; } /** * Gets the record set. * * @return the record set */ - public SimpleFeatureCollection getRecordSet() { - return features; - } + public SimpleFeatureCollection getRecordSet() { return features; } }// end of class QueryInfo @Override diff --git a/msi.gama.core/src/msi/gama/common/interfaces/IGui.java b/msi.gama.core/src/msi/gama/common/interfaces/IGui.java index 0e9ea9633d..82830e8734 100644 --- a/msi.gama.core/src/msi/gama/common/interfaces/IGui.java +++ b/msi.gama.core/src/msi/gama/common/interfaces/IGui.java @@ -1,12 +1,11 @@ /******************************************************************************************************* * - * IGui.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * IGui.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.common.interfaces; @@ -133,7 +132,7 @@ public interface IGui { * the scope * @return the status */ - IStatusDisplayer getStatus(IScope scope); + IStatusDisplayer getStatus(); /** * Gets the console. diff --git a/msi.gama.core/src/msi/gama/common/util/FileUtils.java b/msi.gama.core/src/msi/gama/common/util/FileUtils.java index 596f2deb19..29597c74c3 100644 --- a/msi.gama.core/src/msi/gama/common/util/FileUtils.java +++ b/msi.gama.core/src/msi/gama/common/util/FileUtils.java @@ -533,7 +533,7 @@ public static String fetchToTempFile(final IScope scope, final URL url) { String pathName = constructRelativeTempFilePath(scope, url); final String urlPath = url.toExternalForm(); final String status = "Downloading file " + urlPath.substring(urlPath.lastIndexOf(SEPARATOR)); - scope.getGui().getStatus(scope).beginSubStatus(status); + scope.getGui().getStatus().beginSubStatus(status); final Webb web = WEB.get(); try { try (InputStream in = web.get(urlPath).ensureSuccess() @@ -550,7 +550,7 @@ public static String fetchToTempFile(final IScope scope, final URL url) { } catch (final IOException | WebbException e) { throw GamaRuntimeException.create(e, scope); } finally { - scope.getGui().getStatus(scope).endSubStatus(status); + scope.getGui().getStatus().endSubStatus(status); } return pathName; } diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/AbstractExperimentScheduler.java b/msi.gama.core/src/msi/gama/kernel/experiment/AbstractExperimentScheduler.java deleted file mode 100644 index 9bc6586f06..0000000000 --- a/msi.gama.core/src/msi/gama/kernel/experiment/AbstractExperimentScheduler.java +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************************************* - * - * AbstractExperimentScheduler.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation - * platform (v.1.8.2). - * - * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) - * - * Visit https://github.com/gama-platform/gama for license information and contacts. - * - ********************************************************************************************************/ -package msi.gama.kernel.experiment; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -import msi.gama.common.interfaces.IStepable; -import msi.gama.runtime.GAMA; -import msi.gama.runtime.IScope; -import msi.gama.runtime.exceptions.GamaRuntimeException; - -/** - * The Class AbstractExperimentScheduler. - */ -public abstract class AbstractExperimentScheduler implements IExperimentScheduler { - - /** The to step. */ - protected final Map toStep = Collections.synchronizedMap(new LinkedHashMap<>()); - /** The to stop. */ - protected final Set toStop = new CopyOnWriteArraySet<>(); - - /** - * Dispose. - */ - @Override - public void dispose() { - toStop.clear(); - toStep.clear(); - } - - /** - * Schedule. - * - * @param stepable - * the stepable - * @param scope - * the scope - */ - @Override - public void schedule(final IStepable stepable, final IScope scope) { - toStep.put(stepable, scope); - try { - if (!scope.init(stepable).passed()) { - toStop.add(stepable); - scope.setInterrupted(); - } - } catch (final Throwable e) { - if (scope != null && scope.interrupted()) { - toStop.add(stepable); - } else if (!(e instanceof GamaRuntimeException)) { - GAMA.reportError(scope, GamaRuntimeException.create(e, scope), true); - } - } - - } - - /** - * Step. - * - * @throws InterruptedException - */ - protected void step() { - try { - toStep.forEach((stepable, scope) -> { - if (!scope.step(stepable).passed()) { - toStop.add(stepable); - scope.setInterrupted(); - } - }); - } catch (RuntimeException e) { - e.printStackTrace(); - } - // Cleaning - if (toStop.isEmpty()) return; - for (final IStepable s : toStop) { toStep.remove(s); } - if (toStep.isEmpty()) { this.pause(); } - toStop.clear(); - } - -} diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/ActionExecuter.java b/msi.gama.core/src/msi/gama/kernel/experiment/ActionExecuter.java index af494c8b09..c2b2934b46 100644 --- a/msi.gama.core/src/msi/gama/kernel/experiment/ActionExecuter.java +++ b/msi.gama.core/src/msi/gama/kernel/experiment/ActionExecuter.java @@ -1,19 +1,19 @@ /******************************************************************************************************* * - * ActionExecuter.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * ActionExecuter.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.kernel.experiment; -import java.util.ArrayList; -import java.util.List; +import java.util.Collection; import msi.gama.runtime.IScope; +import msi.gama.util.Collector; import msi.gaml.statements.IExecutable; /** @@ -23,26 +23,28 @@ public class ActionExecuter { /** The Constant BEGIN. */ private static final int BEGIN = 0; - + /** The Constant END. */ private static final int END = 1; - + /** The Constant DISPOSE. */ private static final int DISPOSE = 2; - + /** The Constant ONE_SHOT. */ private static final int ONE_SHOT = 3; /** The actions. */ - @SuppressWarnings ("unchecked") final List[] actions = new List[4]; - + @SuppressWarnings ("unchecked") final Collection[] actions = + new Collection[] { Collector.getList(), Collector.getList(), Collector.getList(), Collector.getList() }; + /** The scope. */ protected final IScope scope; /** * Instantiates a new action executer. * - * @param scope the scope + * @param scope + * the scope */ public ActionExecuter(final IScope scope) { this.scope = scope.copy("of ActionExecuter"); @@ -51,24 +53,22 @@ public ActionExecuter(final IScope scope) { /** * Insert action. * - * @param action the action - * @param type the type + * @param action + * the action + * @param type + * the type * @return the i executable */ private IExecutable insertAction(final IExecutable action, final int type) { - List list = actions[type]; - if (list == null) { - list = new ArrayList<>(); - actions[type] = list; - } - if (list.add(action)) { return action; } + if (actions[type].add(action)) return action; return null; } /** * Insert dispose action. * - * @param action the action + * @param action + * the action * @return the i executable */ public IExecutable insertDisposeAction(final IExecutable action) { @@ -78,7 +78,8 @@ public IExecutable insertDisposeAction(final IExecutable action) { /** * Insert end action. * - * @param action the action + * @param action + * the action * @return the i executable */ public IExecutable insertEndAction(final IExecutable action) { @@ -88,7 +89,8 @@ public IExecutable insertEndAction(final IExecutable action) { /** * Insert one shot action. * - * @param action the action + * @param action + * the action * @return the i executable */ public IExecutable insertOneShotAction(final IExecutable action) { @@ -99,7 +101,7 @@ public IExecutable insertOneShotAction(final IExecutable action) { * Execute end actions. */ public void executeEndActions() { - if (scope.interrupted()) { return; } + if (scope.interrupted()) return; executeActions(END); } @@ -114,35 +116,29 @@ public void executeDisposeActions() { * Execute one shot actions. */ public void executeOneShotActions() { - if (scope.interrupted()) { return; } + if (scope.interrupted()) return; try { executeActions(ONE_SHOT); } finally { - actions[ONE_SHOT] = null; + actions[ONE_SHOT].clear(); } } /** * Execute actions. * - * @param type the type + * @param type + * the type */ private void executeActions(final int type) { - if (actions[type] == null) { return; } - final int size = actions[type].size(); - if (size == 0) { return; } - final IExecutable[] array = actions[type].toArray(new IExecutable[size]); - for (final IExecutable action : array) { - if (!scope.interrupted()) { - action.executeOn(scope); - } - } + for (final IExecutable action : actions[type]) { if (!scope.interrupted()) { action.executeOn(scope); } } } /** * Execute one action. * - * @param action the action + * @param action + * the action */ public synchronized void executeOneAction(final IExecutable action) { final boolean paused = scope.isPaused(); @@ -157,7 +153,7 @@ public synchronized void executeOneAction(final IExecutable action) { * Execute begin actions. */ public void executeBeginActions() { - if (scope.interrupted()) { return; } + if (scope.interrupted()) return; executeActions(BEGIN); } diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/BatchAgent.java b/msi.gama.core/src/msi/gama/kernel/experiment/BatchAgent.java index 4d42f1dcd7..17bbc97279 100644 --- a/msi.gama.core/src/msi/gama/kernel/experiment/BatchAgent.java +++ b/msi.gama.core/src/msi/gama/kernel/experiment/BatchAgent.java @@ -85,7 +85,7 @@ public class BatchAgent extends ExperimentAgent { /** The tracked values. */ // GENERIC OUTPUTS final Map trackedValues = new HashMap<>(); - + /** Keep simulations between ''runs'' */ private boolean simDispose; @@ -241,7 +241,7 @@ public boolean step(final IScope scope) { getSpecies().getExplorationAlgorithm().run(scope); // Once the algorithm has finished exploring the solutions, the agent is // killed. - scope.getGui().getStatus(scope).informStatus(endStatus()); + scope.getGui().getStatus().informStatus(endStatus()); // Issue #2426: the agent is killed too soon getScope().setInterrupted(); // dispose(); @@ -358,7 +358,7 @@ public IMap>> launchSimulationsWithSolut } } // We then verify that the front scheduler has not been paused - while (getSpecies().getController().getScheduler().paused() && !dead) { + while (getSpecies().getController().isPaused() && !dead) { try { Thread.sleep(100); } catch (final InterruptedException e) { @@ -467,7 +467,8 @@ public Map> launchSimulationsWithSolution(final ParametersS final boolean mustStop = stopConditionMet || agent.dead() || agent.getScope().isPaused(); if (mustStop) { pop.unscheduleSimulation(agent); - Map out = manageOutputAndCloseSimulation(agent, currentSolution, true, simDispose); + Map out = + manageOutputAndCloseSimulation(agent, currentSolution, true, simDispose); for (String out_vars : out.keySet()) { if (!outputs.containsKey(out_vars)) { outputs.put(out_vars, GamaListFactory.create()); } outputs.get(out_vars).add(out.get(out_vars)); @@ -476,7 +477,7 @@ public Map> launchSimulationsWithSolution(final ParametersS } // We inform the status line if (!dead) { - getScope().getGui().getStatus(getScope()) + getScope().getGui().getStatus() .setStatus( "Run " + runNumber + " | " + repeatIndex + "/" + seeds.length + " simulations (using " + pop.getNumberOfActiveThreads() + " threads)", @@ -484,7 +485,7 @@ public Map> launchSimulationsWithSolution(final ParametersS } if (++i == 20) { i = 0; } // We then verify that the front scheduler has not been paused - while (getSpecies().getController().getScheduler().paused() && !dead) { + while (getSpecies().getController().isPaused() && !dead) { try { Thread.sleep(100); } catch (final InterruptedException e) { @@ -634,11 +635,18 @@ public String value() { * the new seeds */ public void setSeeds(final Double[] seeds) { this.seeds = seeds; } - - /* - * Decide or not to keep simulation between Gama Batch runs (a coherent set of parameter set launched as simulations) + + /** + * Sets the keep simulations. + * + * @param keepSim + * the new keep simulations */ - public void setKeepSimulations(boolean keepSim) { this.simDispose = !keepSim; } + /* + * Decide or not to keep simulation between Gama Batch runs (a coherent set of parameter set launched as + * simulations) + */ + public void setKeepSimulations(final boolean keepSim) { this.simDispose = !keepSim; } @Override public void closeSimulations() { diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentAgent.java b/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentAgent.java index 7125eb463f..d107d6abdf 100644 --- a/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentAgent.java +++ b/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentAgent.java @@ -239,7 +239,6 @@ public void reset() { ownClock.reset(); // We close any simulation that might be running closeSimulations(); - initialize(); } @@ -276,7 +275,7 @@ public void closeSimulations() { if (!getSpecies().isBatch()) { ownScope.getGui().setSelectedAgent(null); ownScope.getGui().setHighlightedAgent(null); - ownScope.getGui().getStatus(ownScope).resumeStatus(); + ownScope.getGui().getStatus().resumeStatus(); // AD: Fix for issue #1342 -- verify that it does not break // something else in the dynamics of closing/opening ownScope.getGui().closeDialogs(ownScope); @@ -335,7 +334,7 @@ public boolean init(final IScope scope) { super.init(scope); final IOutputManager outputs = getOutputManager(); if (outputs != null) { outputs.init(scope); } - scope.getGui().getStatus(scope).informStatus("Experiment ready"); + scope.getGui().getStatus().informStatus("Experiment ready"); scope.getGui().updateExperimentState(scope); return true; } @@ -379,8 +378,7 @@ public ParametersSet getParameterValues() { public void schedule(final IScope scope) { scheduled = true; // The experiment agent is scheduled in the global scheduler - final IExperimentScheduler sche = getSpecies().getController().getScheduler(); - sche.schedule(this, this.ownScope); + getSpecies().getController().schedule(this); } /** @@ -734,20 +732,19 @@ protected boolean preStep(final IScope scope) { @Override protected void postStep(final IScope scope) { - super.postStep(scope); + // super.postStep(scope); executer.executeEndActions(); executer.executeOneShotActions(); final IOutputManager outputs = getOutputManager(); if (outputs != null) { outputs.step(scope); } - ownClock.step(this.ownScope); + ownClock.step(); informStatus(); } @Override public void informStatus() { - if (!getSpecies().isBatch() && getSimulation() != null) { - getScope().getGui().getStatus(getScope()).informStatus(null, "status.clock"); - } + if (isHeadless() || isBatch() || getSimulation() == null) return; + ownScope.getGui().getStatus().informStatus(null, "status.clock"); } /** @@ -966,4 +963,11 @@ public boolean canStepBack() { @Override public boolean isHeadless() { return getSpecies().isHeadless(); } + /** + * Checks if is batch. + * + * @return true, if is batch + */ + public boolean isBatch() { return getSpecies().isBatch(); } + } \ No newline at end of file diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentController.java b/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentController.java index 20d4b490c9..aec8c16517 100644 --- a/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentController.java +++ b/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentController.java @@ -11,6 +11,7 @@ package msi.gama.kernel.experiment; import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.Semaphore; import msi.gama.common.interfaces.IGui; import msi.gama.runtime.GAMA; @@ -22,11 +23,37 @@ /** * The Class ExperimentController. */ -public class ExperimentController implements Runnable, IExperimentController { +public class ExperimentController implements IExperimentController { + + /** The scope. */ + IScope scope; + + /** + * Alive. Flag indicating that the scheduler is running (it should be alive unless the application is shutting down) + */ + protected volatile boolean experimentAlive = true; + + /** + * Paused. Flag indicating that the experiment is set to pause (used in stepping the experiment) + **/ + protected volatile boolean paused = true; + + /** AcceptingCommands. A flag indicating that the command thread is accepting commands */ + protected volatile boolean acceptingCommands = true; + + /** The lock. Used to pause the experiment */ + protected final Semaphore lock = new Semaphore(1); + + /** The execution thread. */ + private final Thread executionThread = + new Thread(() -> { while (experimentAlive) { step(); } }, "Front end scheduler"); /** The experiment. */ private final IExperimentPlan experiment; + /** The agent. */ + private IExperimentAgent agent; + /** The disposing. */ private boolean disposing; @@ -34,13 +61,13 @@ public class ExperimentController implements Runnable, IExperimentController { protected volatile ArrayBlockingQueue commands; /** The command thread. */ - public volatile Thread commandThread; - - /** The running. */ - protected volatile boolean running = true; - - /** The scheduler. */ - private final IExperimentScheduler scheduler; + private final Thread commandThread = new Thread(() -> { + while (acceptingCommands) { + try { + processUserCommand(commands.take()); + } catch (final Exception e) {} + } + }, "Front end controller"); /** * Instantiates a new experiment controller. @@ -49,25 +76,15 @@ public class ExperimentController implements Runnable, IExperimentController { * the experiment */ public ExperimentController(final IExperimentPlan experiment) { - this.scheduler = - experiment.isHeadless() ? new NonThreadedExperimentScheduler() : new ThreadedExperimentScheduler(experiment); commands = new ArrayBlockingQueue<>(10); this.experiment = experiment; - } - - /** - * Launch command thread. - */ - private void launchCommandThread() { - if (commandThread != null) return; - if (experiment.isHeadless()) { - commandThread = null; - } else { - commandThread = new Thread(this, "Front end controller"); - commandThread.setUncaughtExceptionHandler(GamaExecutorService.EXCEPTION_HANDLER); - commandThread.start(); - } - + executionThread.setUncaughtExceptionHandler(GamaExecutorService.EXCEPTION_HANDLER); + commandThread.setUncaughtExceptionHandler(GamaExecutorService.EXCEPTION_HANDLER); + try { + lock.acquire(); + } catch (final InterruptedException e) {} + commandThread.start(); + executionThread.start(); } @Override @@ -76,33 +93,15 @@ private void launchCommandThread() { @Override public IExperimentPlan getExperiment() { return experiment; } - @Override - public void run() { - while (running) { - try { - final Integer i = commands.take(); - if (i == null) throw new InterruptedException("Internal error. Please retry"); - processUserCommand(i); - } catch (final Exception e) { - e.printStackTrace(); - } - } - commandThread = null; - } - /** * Offer. * * @param command * the command */ - public void offer(final int command) { - if (isDisposing()) return; - if (commandThread == null || !commandThread.isAlive()) { - processUserCommand(command); - } else { - commands.offer(command); - } + private void offer(final int command) { + if (experiment == null || isDisposing()) return; + commands.offer(command); } /** @@ -111,65 +110,57 @@ public void offer(final int command) { * @param command * the command */ - protected void processUserCommand(final int command) { - final IScope scope = experiment.getExperimentScope(); + private void processUserCommand(final int command) { + final IScope scope = getScope(); switch (command) { - case IExperimentController._OPEN: - - experiment.getExperimentScope().getGui().updateExperimentState(scope, IGui.NOTREADY); + case _OPEN: + scope.getGui().updateExperimentState(scope, IGui.NOTREADY); try { - launchCommandThread(); - // Needs to run in the controller thread - if (commandThread == null) { - experiment.open(); - } else { - new Thread(() -> experiment.open()).start(); - - } + new Thread(() -> experiment.open()).start(); } catch (final Exception e) { DEBUG.ERR("Error when opening the experiment: " + e.getMessage()); closeExperiment(e); } break; - case IExperimentController._START: + case _START: try { - scheduler.start(); + start(); } catch (final GamaRuntimeException e) { closeExperiment(e); } finally { - experiment.getExperimentScope().getGui().updateExperimentState(scope, IGui.RUNNING); + scope.getGui().updateExperimentState(scope, IGui.RUNNING); } break; - case IExperimentController._PAUSE: - if (!disposing) { experiment.getExperimentScope().getGui().updateExperimentState(scope, IGui.PAUSED); } - scheduler.pause(); + case _PAUSE: + if (!disposing) { scope.getGui().updateExperimentState(scope, IGui.PAUSED); } + pause(); break; - case IExperimentController._STEP: - experiment.getExperimentScope().getGui().updateExperimentState(scope, IGui.PAUSED); - scheduler.stepByStep(); + case _STEP: + scope.getGui().updateExperimentState(scope, IGui.PAUSED); + stepByStep(); break; - case IExperimentController._BACK: - experiment.getExperimentScope().getGui().updateExperimentState(scope, IGui.PAUSED); - scheduler.stepBack(); + case _BACK: + scope.getGui().updateExperimentState(scope, IGui.PAUSED); + stepBack(); break; - case IExperimentController._RELOAD: - experiment.getExperimentScope().getGui().updateExperimentState(scope, IGui.NOTREADY); + case _RELOAD: + scope.getGui().updateExperimentState(scope, IGui.NOTREADY); try { - final boolean wasRunning = !scheduler.paused() && !experiment.isAutorun(); - scheduler.pause(); - GAMA.getGui().getStatus(scope).waitStatus("Reloading..."); + final boolean wasRunning = !isPaused() && !experiment.isAutorun(); + pause(); + scope.getGui().getStatus().waitStatus("Reloading..."); experiment.reload(); if (wasRunning) { - processUserCommand(IExperimentController._START); + processUserCommand(_START); } else { - experiment.getExperimentScope().getGui().getStatus(scope).informStatus("Experiment reloaded"); + scope.getGui().getStatus().informStatus("Experiment reloaded"); } } catch (final GamaRuntimeException e) { closeExperiment(e); } catch (final Throwable e) { - closeExperiment(GamaRuntimeException.create(e, experiment.getExperimentScope())); + closeExperiment(GamaRuntimeException.create(e, scope)); } finally { - experiment.getExperimentScope().getGui().updateExperimentState(scope); + scope.getGui().updateExperimentState(scope); } break; } @@ -178,42 +169,38 @@ protected void processUserCommand(final int command) { @Override public void userPause() { // TODO Should maybe be done directly (so as to pause immediately) - offer(IExperimentController._PAUSE); + offer(_PAUSE); } @Override public void directPause() { - processUserCommand(IExperimentController._PAUSE); + processUserCommand(_PAUSE); } @Override public void userStep() { - if (experiment == null) return; - offer(IExperimentController._STEP); + offer(_STEP); } @Override - public void stepBack() { - if (experiment == null) return; - offer(IExperimentController._BACK); + public void userStepBack() { + offer(_BACK); } @Override public void userReload() { // TODO Should maybe be done directly (so as to reload immediately) - if (experiment == null) return; - // GAMA.getGui().openSimulationPerspective(null, null); - offer(IExperimentController._RELOAD); + offer(_RELOAD); } @Override public void directOpenExperiment() { - processUserCommand(IExperimentController._OPEN); + processUserCommand(_OPEN); } @Override public void userStart() { - offer(IExperimentController._START); + offer(_START); } @Override @@ -223,30 +210,28 @@ public void userOpen() { @Override public void dispose() { + scope = null; + agent = null; if (experiment != null) { - // DEBUG.OUT("Contoller.dipose BEGIN"); - final IScope scope = experiment.getExperimentScope(); try { - scheduler.pause(); - experiment.getExperimentScope().getGui().updateExperimentState(scope, IGui.NOTREADY); - experiment.getExperimentScope().getGui().closeDialogs(scope); + pause(); + getScope().getGui().updateExperimentState(getScope(), IGui.NOTREADY); + getScope().getGui().closeDialogs(getScope()); // Dec 2015 This method is normally now called from // ExperimentPlan.dispose() - // experiment.dispose(); - // experiment = null; } finally { - running = false; - scheduler.dispose(); - experiment.getExperimentScope().getGui().updateExperimentState(scope, IGui.NONE); + acceptingCommands = false; + experimentAlive = false; + lock.release(); + getScope().getGui().updateExperimentState(getScope(), IGui.NONE); if (commandThread != null && commandThread.isAlive()) { commands.offer(-1); } - // DEBUG.OUT("Contoller.dipose END"); } } } @Override public void startPause() { - if (experiment == null) {} else if (scheduler.paused()) { + if (isPaused()) { userStart(); } else { userPause(); @@ -266,13 +251,98 @@ public void close() { */ public void closeExperiment(final Exception e) { disposing = true; - // DEBUG.LOG("CloseExperiment : disposing = true"); - if (e != null) { GAMA.getGui().getStatus(getExperiment().getExperimentScope()).errorStatus(e.getMessage()); } - + if (e != null) { getScope().getGui().getStatus().errorStatus(e.getMessage()); } experiment.dispose(); // will call own dispose() later } + /** + * Checks if is paused. + * + * @return true, if is paused + */ + @Override + public boolean isPaused() { return paused; } + + /** + * Schedule. + * + * @param scope + * the scope + * @param agent + * the agent + */ @Override - public IExperimentScheduler getScheduler() { return scheduler; } + public void schedule(final ExperimentAgent agent) { + this.agent = agent; + scope = agent.getScope(); + try { + if (!scope.init(agent).passed()) { scope.setInterrupted(); } + } catch (final Throwable e) { + if (scope != null && scope.interrupted()) {} else if (!(e instanceof GamaRuntimeException)) { + GAMA.reportError(scope, GamaRuntimeException.create(e, scope), true); + } + } + } + + /** + * Step by step. + */ + public void stepByStep() { + pause(); + lock.release(); + } + + /** + * Start. + */ + public void start() { + paused = false; + lock.release(); + } + + /** + * Step. + */ + protected void step() { + if (paused) { + try { + lock.acquire(); + } catch (InterruptedException e) { + experimentAlive = false; + } + } + try { + if (scope == null) return; + if (!scope.step(agent).passed()) { + scope.setInterrupted(); + this.pause(); + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + /** + * Pause. + */ + private void pause() { + paused = true; + } + + /** + * Step back. + */ + // TODO : c'est moche ..... + private void stepBack() { + pause(); + experiment.getAgent().backward(getScope());// ?? scopes[0]); + } + + /** + * Gets the scope. + * + * @return the scope + */ + IScope getScope() { return scope == null ? experiment.getExperimentScope() : scope; } } diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentPlan.java b/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentPlan.java index 4adac376ca..64d6169a36 100644 --- a/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentPlan.java +++ b/msi.gama.core/src/msi/gama/kernel/experiment/ExperimentPlan.java @@ -1,16 +1,18 @@ /******************************************************************************************************* * - * ExperimentPlan.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * ExperimentPlan.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.kernel.experiment; +import static msi.gama.common.interfaces.IKeyword.MEMORIZE; import static msi.gama.common.interfaces.IKeyword.TEST; +import static msi.gama.runtime.GAMA.getGui; import java.util.ArrayList; import java.util.Arrays; @@ -500,8 +502,7 @@ public void setChildren(final Iterable children) { } else { originalSimulationOutputs = (SimulationOutputManager) s; } - } else if (s instanceof IParameter.Batch) { - final IParameter.Batch pb = (IParameter.Batch) s; + } else if (s instanceof IParameter.Batch pb) { if (isBatch() && pb.canBeExplored()) { pb.setEditable(false); addExplorableParameter(pb); @@ -559,14 +560,12 @@ public synchronized void open(final Double seed) { createAgent(seed); myScope.getGui().prepareForExperiment(myScope, this); - agent.schedule(agent.getScope()); - if (isHeadless()) { - // Always auto start in headless mode - this.getController().userStart(); - } else if (isBatch()) { - agent.getScope().getGui().getStatus(agent.getScope()) + IScope scope = agent.getScope(); + agent.schedule(scope); + if (isBatch()) { + getGui().getStatus() .informStatus(isTest() ? "Tests ready. Click run to begin." : " Batch ready. Click run to begin."); - agent.getScope().getGui().updateExperimentState(agent.getScope()); + getGui().updateExperimentState(scope); } } @@ -583,26 +582,10 @@ public synchronized void open() { open(seed); } - /* - * @Override public synchronized void open() { - * - * createAgent(); myScope.getGui().prepareForExperiment(myScope, this); agent.schedule(agent.getScope()); if - * (isBatch()) { agent.getScope().getGui().getStatus(agent.getScope()) .informStatus(isTest() ? - * "Tests ready. Click run to begin." : " Batch ready. Click run to begin."); - * agent.getScope().getGui().updateExperimentState(agent.getScope()); } } - */ @Override public void reload() { - // if (isBatch()) { agent.dispose(); open(); - // } else { - // agent.reset(); - // agent.getScope().getGui().getConsole(agent.getScope()).eraseConsole(false); - // agent.init(agent.getScope()); - // - // agent.getScope().getGui().updateParameterView(agent.getScope(), this); - // } } @Override @@ -618,10 +601,7 @@ public boolean hasParametersOrUserCommands() { public boolean isTest() { return TEST.equals(getExperimentType()); } @Override - public boolean isMemorize() { return IKeyword.MEMORIZE.equals(getExperimentType()); } - - @Override - public boolean isGui() { return true; } + public boolean isMemorize() { return MEMORIZE.equals(getExperimentType()); } @Override public IScope getExperimentScope() { return myScope; } @@ -830,7 +810,9 @@ public void addExplorableParameter(final IParameter.Batch p) { */ @Override public IExperimentController getController() { - if (controller == null) { controller = new ExperimentController(this); } + if (controller == null) { + controller = isHeadless ? new HeadlessExperimentController(this) : new ExperimentController(this); + } return controller; } diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/HeadlessExperimentController.java b/msi.gama.core/src/msi/gama/kernel/experiment/HeadlessExperimentController.java new file mode 100644 index 0000000000..a71c8de05d --- /dev/null +++ b/msi.gama.core/src/msi/gama/kernel/experiment/HeadlessExperimentController.java @@ -0,0 +1,56 @@ +/******************************************************************************************************* + * + * HeadlessExperimentController.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation + * platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ +package msi.gama.kernel.experiment; + +import msi.gama.runtime.GAMA; +import msi.gama.runtime.IScope; +import msi.gama.runtime.exceptions.GamaRuntimeException; + +/** + * The Class HeadlessExperimentController. + */ +public class HeadlessExperimentController implements IExperimentController { + + /** The experiment. */ + private final IExperimentPlan experiment; + + /** + * Instantiates a new headless experiment controller. + * + * @param experiment + * the experiment. + */ + public HeadlessExperimentController(final IExperimentPlan experiment) { + this.experiment = experiment; + } + + @Override + public IExperimentPlan getExperiment() { return experiment; } + + @Override + public void close() { + experiment.dispose(); // will call own dispose() later + } + + @Override + public void schedule(final ExperimentAgent agent) { + IScope scope = agent.getScope(); + try { + if (!scope.init(agent).passed()) { scope.setInterrupted(); } + } catch (final Throwable e) { + if (!(e instanceof GamaRuntimeException)) { + GAMA.reportError(scope, GamaRuntimeException.create(e, scope), true); + } + } + + } + +} diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentController.java b/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentController.java index d5acf65819..125c21f9ba 100644 --- a/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentController.java +++ b/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentController.java @@ -43,70 +43,82 @@ public interface IExperimentController { IExperimentPlan getExperiment(); /** - * @return + * */ - IExperimentScheduler getScheduler(); + default void userStep() {} /** * */ - void userStep(); + default void userStepBack() {} /** * */ - void stepBack(); + default void startPause() {} /** * */ - void startPause(); + default void close() {} /** * */ - void close(); + default void userStart() {} /** * */ - void userStart(); + default void directPause() {} /** * */ - void directPause(); + default void dispose() {} /** * */ - void dispose(); + default void directOpenExperiment() {} /** * */ - void directOpenExperiment(); + default void userReload() {} /** * */ - void userReload(); + default void userPause() {} /** * */ - void userPause(); + default void userOpen() {} /** + * Checks if is disposing. * + * @return true, if is disposing */ - void userOpen(); + default boolean isDisposing() { return false; } /** - * Checks if is disposing. + * Checks if is paused. * - * @return true, if is disposing + * @return true, if is paused + */ + default boolean isPaused() { return false; } + + /** + * Schedule. + * + * @param scope + * the scope + * @param agent + * the agent */ - boolean isDisposing(); + default void schedule(final ExperimentAgent agent) {} } \ No newline at end of file diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentPlan.java b/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentPlan.java index 0d6d893121..6ddc128029 100644 --- a/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentPlan.java +++ b/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentPlan.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * IExperimentPlan.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * IExperimentPlan.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.kernel.experiment; @@ -32,13 +32,13 @@ public interface IExperimentPlan extends ISpecies { /** The batch category name. */ String BATCH_CATEGORY_NAME = "Exploration method"; - + /** The test category name. */ String TEST_CATEGORY_NAME = "Configuration of tests"; - + /** The explorable category name. */ String EXPLORABLE_CATEGORY_NAME = "Parameters to explore"; - + /** The system category prefix. */ String SYSTEM_CATEGORY_PREFIX = "Random number generation"; @@ -52,7 +52,8 @@ public interface IExperimentPlan extends ISpecies { /** * Sets the model. * - * @param model the new model + * @param model + * the new model */ void setModel(final IModel model); @@ -100,17 +101,11 @@ public interface IExperimentPlan extends ISpecies { */ IOutputManager getExperimentOutputs(); - /** - * Checks if is gui. - * - * @return true, if is gui - */ - boolean isGui(); - /** * Checks for parameter. * - * @param name the name + * @param name + * the name * @return true, if successful */ boolean hasParameter(String name); @@ -203,7 +198,8 @@ public interface IExperimentPlan extends ISpecies { /** * Sets the headless. * - * @param headless the new headless + * @param headless + * the new headless */ void setHeadless(boolean headless); diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentScheduler.java b/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentScheduler.java deleted file mode 100644 index a03b64cb4f..0000000000 --- a/msi.gama.core/src/msi/gama/kernel/experiment/IExperimentScheduler.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************************************* - * - * IExperimentScheduler.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform - * (v.1.8.2). - * - * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) - * - * Visit https://github.com/gama-platform/gama for license information and contacts. - * - ********************************************************************************************************/ -package msi.gama.kernel.experiment; - -import msi.gama.common.interfaces.IStepable; -import msi.gama.runtime.IScope; - -/** - * The Interface IExperimentScheduler. - */ -public interface IExperimentScheduler { - - /** - * Start. - */ - void start(); - - /** - * Pause. - */ - default void pause() {} - - /** - * Unpause. - */ - default void resume() {} - - /** - * Step by step. - */ - default void stepByStep() {} - - /** - * Step back. - */ - default void stepBack() {} - - /** - * Dispose. - */ - void dispose(); - - /** - * Checks if is paused. - * - * @return true, if is paused - */ - default boolean paused() { - return false; - } - - /** - * Schedule. - * - * @param experimentAgent - * the experiment agent - * @param ownScope - * the own scope - */ - void schedule(IStepable experimentAgent, IScope ownScope); - -} \ No newline at end of file diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/NonThreadedExperimentScheduler.java b/msi.gama.core/src/msi/gama/kernel/experiment/NonThreadedExperimentScheduler.java deleted file mode 100644 index 05cc37ed9a..0000000000 --- a/msi.gama.core/src/msi/gama/kernel/experiment/NonThreadedExperimentScheduler.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************************************* - * - * ExperimentSchedulerForHeadless.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation - * platform (v.1.8.2). - * - * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) - * - * Visit https://github.com/gama-platform/gama for license information and contacts. - * - ********************************************************************************************************/ -package msi.gama.kernel.experiment; - -/** - * The Class ExperimentScheduler. - */ -public class NonThreadedExperimentScheduler extends AbstractExperimentScheduler { - - @Override - public void stepByStep() { - step(); - } - - /** - * Start. - */ - @Override - public void start() { - step(); - } - -} diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/ThreadedExperimentScheduler.java b/msi.gama.core/src/msi/gama/kernel/experiment/ThreadedExperimentScheduler.java deleted file mode 100644 index bc193d8f9e..0000000000 --- a/msi.gama.core/src/msi/gama/kernel/experiment/ThreadedExperimentScheduler.java +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************************************* - * - * ThreadedExperimentScheduler.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). - * - * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) - * - * Visit https://github.com/gama-platform/gama for license information and contacts. - * - ********************************************************************************************************/ -package msi.gama.kernel.experiment; - -import java.util.concurrent.Semaphore; - -import msi.gama.runtime.concurrent.GamaExecutorService; - -/** - * The Class ExperimentScheduler. - */ -public class ThreadedExperimentScheduler extends AbstractExperimentScheduler { - - /** The experiment. */ - protected final IExperimentPlan experiment; - - /** - * Alive. Flag indicating that the scheduler is running (it should be alive unless the application is shutting down) - */ - protected volatile boolean alive = true; - - /** - * Paused. Flag indicating that the experiment is set to pause (used in stepping the experiment) - **/ - protected volatile boolean paused = true; - - /** The lock. */ - protected final Semaphore lock = new Semaphore(1); - - /** The execution thread. */ - private final Thread executionThread = new Thread(() -> { while (alive) { step(); } }, "Front end scheduler"); - - /** - * Instantiates a new experiment scheduler. - * - * @param experiment - * the experiment - */ - ThreadedExperimentScheduler(final IExperimentPlan experiment) { - this.experiment = experiment; - executionThread.setUncaughtExceptionHandler(GamaExecutorService.EXCEPTION_HANDLER); - try { - lock.acquire(); - } catch (final InterruptedException e) {} - executionThread.start(); - } - - /** - * Step by step. - */ - @Override - public void stepByStep() { - pause(); - lock.release(); - } - - /** - * Start. - */ - @Override - public void start() { - resume(); - lock.release(); - } - - @Override - protected void step() { - if (paused) { - try { - lock.acquire(); - } catch (InterruptedException e) { - alive = false; - } - } - super.step(); - } - - @Override - public void dispose() { - alive = false; - super.dispose(); - lock.release(); - } - - @Override - public boolean paused() { - return paused; - } - - /** - * Pause. - */ - @Override - public void pause() { - paused = true; - } - - /** - * Unpause. - */ - @Override - public void resume() { - paused = false; - } - - /** - * Step back. - */ - // TODO : c'est moche ..... - @Override - public void stepBack() { - pause(); - experiment.getAgent().backward(experiment.getExperimentScope());// ?? scopes[0]); - } -} diff --git a/msi.gama.core/src/msi/gama/kernel/simulation/SimulationAgent.java b/msi.gama.core/src/msi/gama/kernel/simulation/SimulationAgent.java index 4801be3633..38d0fb4da7 100644 --- a/msi.gama.core/src/msi/gama/kernel/simulation/SimulationAgent.java +++ b/msi.gama.core/src/msi/gama/kernel/simulation/SimulationAgent.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * SimulationAgent.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * SimulationAgent.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.kernel.simulation; @@ -172,66 +172,68 @@ public class SimulationAgent extends GamlAgent implements ITopLevelAgent { /** The Constant DURATION. */ public static final String DURATION = "duration"; - + /** The Constant TOTAL_DURATION. */ public static final String TOTAL_DURATION = "total_duration"; - + /** The Constant AVERAGE_DURATION. */ public static final String AVERAGE_DURATION = "average_duration"; - + /** The Constant CYCLE. */ public static final String CYCLE = "cycle"; - + /** The Constant TIME. */ public static final String TIME = "time"; - + /** The Constant CURRENT_DATE. */ public static final String CURRENT_DATE = "current_date"; - + /** The Constant STARTING_DATE. */ public static final String STARTING_DATE = "starting_date"; - + /** The Constant PAUSED. */ public static final String PAUSED = "paused"; - + /** The Constant USAGE. */ public static final String USAGE = "rng_usage"; /** The own clock. */ final SimulationClock ownClock; - + /** The color. */ GamaColor color; /** The own scope. */ final IScope ownScope = new ExecutionScope(this); - + /** The outputs. */ private SimulationOutputManager outputs; - + /** The projection factory. */ final ProjectionFactory projectionFactory; - + /** The scheduled. */ private Boolean scheduled = false; - + /** The is on user hold. */ private volatile boolean isOnUserHold; - + /** The random. */ private RandomUtils random; - + /** The executer. */ private final ActionExecuter executer; - + /** The topology. */ private RootTopology topology; /** * Instantiates a new simulation agent. * - * @param pop the pop - * @param index the index + * @param pop + * the pop + * @param index + * the index */ public SimulationAgent(final IPopulation pop, final int index) { this((SimulationPopulation) pop, index); @@ -240,9 +242,12 @@ public SimulationAgent(final IPopulation pop, final int index) /** * Instantiates a new simulation agent. * - * @param pop the pop - * @param index the index - * @throws GamaRuntimeException the gama runtime exception + * @param pop + * the pop + * @param index + * the index + * @throws GamaRuntimeException + * the gama runtime exception */ public SimulationAgent(final SimulationPopulation pop, final int index) throws GamaRuntimeException { super(pop, index); @@ -275,7 +280,8 @@ public IExperimentAgent getExperiment() { /** * Sets the topology. * - * @param topology2 the new topology + * @param topology2 + * the new topology */ public void setTopology(final RootTopology topology2) { if (topology != null) { topology.dispose(); } @@ -286,8 +292,10 @@ public void setTopology(final RootTopology topology2) { /** * Sets the topology. * - * @param scope the scope - * @param shape the shape + * @param scope + * the scope + * @param shape + * the shape */ public void setTopology(final IScope scope, final IShape shape) { // A topology has already been computed. We update it and updates all @@ -319,7 +327,8 @@ public void setName(final String name) { /** * Sets the scheduled. * - * @param scheduled the new scheduled + * @param scheduled + * the new scheduled */ public void setScheduled(final Boolean scheduled) { this.scheduled = scheduled; } @@ -340,7 +349,8 @@ public GamaColor getColor() { /** * Sets the color. * - * @param color the new color + * @param color + * the new color */ @setter (IKeyword.COLOR) public void setColor(final GamaColor color) { this.color = color; } @@ -363,7 +373,7 @@ protected void postStep(final IScope scope) { executer.executeEndActions(); executer.executeOneShotActions(); if (outputs != null) { outputs.step(this.getScope()); } - ownClock.step(this.getScope()); + ownClock.step(); } @Override @@ -489,7 +499,8 @@ public IPopulation getPopulationFor(final String speciesName) /** * Gets the cycle. * - * @param scope the scope + * @param scope + * the scope * @return the cycle */ @getter (CYCLE) @@ -502,7 +513,8 @@ public Integer getCycle(final IScope scope) { /** * Checks if is paused. * - * @param scope the scope + * @param scope + * the scope * @return true, if is paused */ @getter (PAUSED) @@ -515,8 +527,10 @@ public boolean isPaused(final IScope scope) { /** * Sets the paused. * - * @param scope the scope - * @param state the state + * @param scope + * the scope + * @param state + * the state */ @setter (PAUSED) public void setPaused(final IScope scope, final boolean state) { @@ -540,7 +554,8 @@ public void setPaused(final IScope scope, final boolean state) { /** * Gets the time step. * - * @param scope the scope + * @param scope + * the scope * @return the time step */ @getter ( @@ -555,9 +570,12 @@ public double getTimeStep(final IScope scope) { /** * Sets the time step. * - * @param scope the scope - * @param t the t - * @throws GamaRuntimeException the gama runtime exception + * @param scope + * the scope + * @param t + * the t + * @throws GamaRuntimeException + * the gama runtime exception */ @setter (IKeyword.STEP) public void setTimeStep(final IScope scope, final double t) throws GamaRuntimeException { @@ -571,7 +589,8 @@ public void setTimeStep(final IScope scope, final double t) throws GamaRuntimeEx /** * Gets the time. * - * @param scope the scope + * @param scope + * the scope * @return the time */ @getter (TIME) @@ -584,9 +603,12 @@ public double getTime(final IScope scope) { /** * Sets the time. * - * @param scope the scope - * @param t the t - * @throws GamaRuntimeException the gama runtime exception + * @param scope + * the scope + * @param t + * the t + * @throws GamaRuntimeException + * the gama runtime exception */ @setter (TIME) public void setTime(final IScope scope, final double t) throws GamaRuntimeException { @@ -632,8 +654,10 @@ public void setTime(final IScope scope, final double t) throws GamaRuntimeExcept /** * Sets the machine time. * - * @param t the new machine time - * @throws GamaRuntimeException the gama runtime exception + * @param t + * the new machine time + * @throws GamaRuntimeException + * the gama runtime exception */ @setter (PlatformAgent.MACHINE_TIME) public void setMachineTime(final Double t) throws GamaRuntimeException { @@ -643,8 +667,10 @@ public void setMachineTime(final Double t) throws GamaRuntimeException { /** * Sets the current date. * - * @param d the new current date - * @throws GamaRuntimeException the gama runtime exception + * @param d + * the new current date + * @throws GamaRuntimeException + * the gama runtime exception */ @setter (CURRENT_DATE) public void setCurrentDate(final GamaDate d) throws GamaRuntimeException { @@ -662,8 +688,10 @@ public void setCurrentDate(final GamaDate d) throws GamaRuntimeException { /** * Sets the starting date. * - * @param d the new starting date - * @throws GamaRuntimeException the gama runtime exception + * @param d + * the new starting date + * @throws GamaRuntimeException + * the gama runtime exception */ @setter (STARTING_DATE) public void setStartingDate(final GamaDate d) throws GamaRuntimeException { @@ -683,7 +711,8 @@ public void setStartingDate(final GamaDate d) throws GamaRuntimeException { /** * Pause. * - * @param scope the scope + * @param scope + * the scope * @return the object */ @action ( @@ -698,7 +727,8 @@ public Object pause(final IScope scope) { /** * Resume. * - * @param scope the scope + * @param scope + * the scope * @return the object */ @action ( @@ -713,7 +743,8 @@ public Object resume(final IScope scope) { /** * Halt. * - * @param scope the scope + * @param scope + * the scope * @return the object */ @action ( @@ -746,17 +777,16 @@ public String getShortUserFriendlyName() { public String buildPostfix() { final boolean noName = !GamaPreferences.Interface.CORE_SIMULATION_NAME.getValue(); if (!noName) return " (" + getName() + ")"; - if (getPopulation().size() > 1) - return " (S" + getIndex() + ")"; - else - return ""; + if (getPopulation().size() > 1) return " (S" + getIndex() + ")"; + return ""; } /** * Sets the outputs. * - * @param iOutputManager the new outputs + * @param iOutputManager + * the new outputs */ public void setOutputs(final IOutputManager iOutputManager) { if (iOutputManager == null) return; @@ -817,7 +847,8 @@ public Integer getUsage() { /** * Sets the usage. * - * @param s the new usage + * @param s + * the new usage */ @setter (SimulationAgent.USAGE) public void setUsage(final Integer s) { @@ -843,7 +874,8 @@ public Double getSeed() { /** * Sets the seed. * - * @param s the new seed + * @param s + * the new seed */ @setter (IKeyword.SEED) public void setSeed(final Double s) { @@ -870,7 +902,8 @@ public void setSeed(final Double s) { /** * Sets the rng. * - * @param newRng the new rng + * @param newRng + * the new rng */ @setter (IKeyword.RNG) public void setRng(final String newRng) { @@ -887,14 +920,16 @@ public void setRng(final String newRng) { /** * Sets the random generator. * - * @param rng the new random generator + * @param rng + * the new random generator */ public void setRandomGenerator(final RandomUtils rng) { random = rng; } /** * Prepare gui for simulation. * - * @param s the s + * @param s + * the s */ public void prepareGuiForSimulation(final IScope s) { s.getGui().clearErrors(s); @@ -1038,9 +1073,12 @@ public void updateWith(final IScope scope, final SavedAgent sa) { /** * Update references. * - * @param scope the scope - * @param list_ref the list ref - * @param sim the sim + * @param scope + * the scope + * @param list_ref + * the list ref + * @param sim + * the sim */ private void updateReferences(final IScope scope, final List list_ref, final SimulationAgent sim) { // list_ref.stream().forEach( @@ -1053,7 +1091,8 @@ private void updateReferences(final IScope scope, final List list_re /** * Adopt topology of. * - * @param root the root + * @param root + * the root */ public void adoptTopologyOf(final SimulationAgent root) { final RootTopology rt = root.getTopology(); diff --git a/msi.gama.core/src/msi/gama/kernel/simulation/SimulationClock.java b/msi.gama.core/src/msi/gama/kernel/simulation/SimulationClock.java index d9a13ad0ad..a797fcee8c 100644 --- a/msi.gama.core/src/msi/gama/kernel/simulation/SimulationClock.java +++ b/msi.gama.core/src/msi/gama/kernel/simulation/SimulationClock.java @@ -1,15 +1,17 @@ /******************************************************************************************************* * - * SimulationClock.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * SimulationClock.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.kernel.simulation; +import static msi.gaml.operators.Dates.asDuration; + import java.time.DateTimeException; import java.time.temporal.ChronoUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -35,9 +37,6 @@ */ public class SimulationClock { - /** The info string builder. */ - final StringBuilder infoStringBuilder = new StringBuilder(); - /** The number of simulation cycles elapsed so far. */ private volatile AtomicInteger cycle = new AtomicInteger(0); @@ -80,12 +79,12 @@ public class SimulationClock { /** The starting date. */ private GamaDate startingDate = null; - + /** The current date. */ private GamaDate currentDate = null; /** The output current date as duration. */ - private final boolean outputCurrentDateAsDuration; + private final boolean outputAsDuration; /** The clock scope. */ private final IScope clockScope; @@ -93,12 +92,12 @@ public class SimulationClock { /** * Instantiates a new simulation clock. * - * @param scope the scope + * @param scope + * the scope */ public SimulationClock(final IScope scope) { final IModel model = scope.getModel(); - outputCurrentDateAsDuration = - model == null ? true : !((ModelDescription) model.getDescription()).isStartingDateDefined(); + outputAsDuration = model == null ? true : !((ModelDescription) model.getDescription()).isStartingDateDefined(); this.clockScope = scope; } @@ -113,14 +112,11 @@ public SimulationClock(final IScope scope) { // well, so as to allow writing // "cycle <- cycle + 1" in GAML and have the correct information computed. public void setCycle(final int i) throws GamaRuntimeException { - if (i < 0) { - throw GamaRuntimeException.error("The current cycle of a simulation cannot be negative", clockScope); - } + if (i < 0) throw GamaRuntimeException.error("The current cycle of a simulation cannot be negative", clockScope); // TODO check backward final int previous = cycle.get(); - if (i < previous && !clockScope.getExperiment().canStepBack()) { + if (i < previous && !clockScope.getExperiment().canStepBack()) throw GamaRuntimeException.error("The current cycle of a simulation cannot be set backwards", clockScope); - } cycle.set(i); setCurrentDate(getCurrentDate().plus(getStepInMillis(), i - previous, ChronoUnit.MILLIS)); } @@ -145,9 +141,7 @@ public void resetCycles() { /** * Returns the current value of cycle */ - public int getCycle() { - return cycle.get(); - } + public int getCycle() { return cycle.get(); } /** * Sets the value of the current time of the simulation. Cannot be negative. @@ -187,10 +181,8 @@ public double getTimeElapsedInSeconds() { */ public void setStep(final double exp) throws GamaRuntimeException { - if (exp <= 0) { - throw GamaRuntimeException - .error("The interval between two cycles of a simulation cannot be negative or null", clockScope); - } + if (exp <= 0) throw GamaRuntimeException + .error("The interval between two cycles of a simulation cannot be negative or null", clockScope); step = exp; // step = i <= 0 ? 1 : i; @@ -201,18 +193,14 @@ public void setStep(final double exp) throws GamaRuntimeException { * * @return a positive double */ - public double getStepInSeconds() { - return step; - } + public double getStepInSeconds() { return step; } /** * Gets the step in millis. * * @return the step in millis */ - public long getStepInMillis() { - return (long) (step * 1000); - } + public long getStepInMillis() { return (long) (step * 1000); } /** * Initializes start at the beginning of a step @@ -244,9 +232,7 @@ private void computeDuration() { * * @return a duration in milliseconds */ - public long getDuration() { - return duration; - } + public long getDuration() { return duration; } /** * Gets the average duration (in milliseconds) over @@ -254,7 +240,7 @@ public long getDuration() { * @return a duration in milliseconds */ public double getAverageDuration() { - if (cycle.get() == 0) { return 0; } + if (cycle.get() == 0) return 0; return totalDuration / (double) cycle.get(); } @@ -263,16 +249,15 @@ public double getAverageDuration() { * * @return a duration in milliseconds */ - public long getTotalDuration() { - return totalDuration; - } + public long getTotalDuration() { return totalDuration; } /** * Step. * - * @param scope the scope + * @param scope + * the scope */ - public void step(final IScope scope) { + public void step() { incrementCycle(); computeDuration(); waitDelay(); @@ -283,9 +268,9 @@ public void step(final IScope scope) { */ public void waitDelay() { final double delay = getDelayInMilliseconds(); - if (delay == 0d) { return; } + if (delay == 0d) return; try { - if (duration >= delay) { return; } + if (duration >= delay) return; Thread.sleep((long) delay - duration); } catch (final InterruptedException e) { e.printStackTrace(); @@ -295,7 +280,8 @@ public void waitDelay() { /** * Reset. * - * @throws GamaRuntimeException the gama runtime exception + * @throws GamaRuntimeException + * the gama runtime exception */ public void reset() throws GamaRuntimeException { resetCycles(); @@ -310,23 +296,23 @@ public void beginCycle() { } /** - * Gets the info. + * Gets the info appended to an existing StringBuilder * + * @param sb + * the info string builder * @return the info */ - public String getInfo() { - final int currentCycle = getCycle(); + public StringBuilder getInfo(final StringBuilder sb) { + final int c = getCycle(); final ITopLevelAgent agent = clockScope.getRoot(); - infoStringBuilder.setLength(0); - infoStringBuilder.append(agent.getName()).append(": ").append(currentCycle) - .append(currentCycle == 1 ? " cycle " : " cycles ").append("elapsed "); - + sb.append(agent.getName()).append(": ").append(c).append(c == 1 ? " cycle " : " cycles ").append("elapsed "); try { - final String date = outputCurrentDateAsDuration ? Dates.asDuration(getStartingDate(), getCurrentDate()) - : getCurrentDate().toString("yyyy-MM-dd HH:mm:ss", "en"); - infoStringBuilder.append("[").append(date).append("]"); + GamaDate d = getCurrentDate(); + final String date = + outputAsDuration ? asDuration(getStartingDate(), d) : d.toString("yyyy-MM-dd HH:mm:ss", "en"); + sb.append("[").append(date).append("]"); } catch (final DateTimeException e) {} - return infoStringBuilder.toString(); + return sb; } /** @@ -337,7 +323,8 @@ public static class ExperimentClock extends SimulationClock { /** * Instantiates a new experiment clock. * - * @param scope the scope + * @param scope + * the scope */ public ExperimentClock(final IScope scope) { super(scope); @@ -349,25 +336,21 @@ public void waitDelay() {} /** * @param totalDuration */ - public void setTotalDuration(final long totalDuration) { - this.totalDuration = totalDuration; - } + public void setTotalDuration(final long totalDuration) { this.totalDuration = totalDuration; } /** * Sets the last duration. * - * @param duration the new last duration + * @param duration + * the new last duration */ - public void setLastDuration(final long duration) { - this.duration = duration; - } + public void setLastDuration(final long duration) { this.duration = duration; } @Override - public String getInfo() { - final int cycle = getCycle(); - return "Experiment: " + cycle + (cycle == 1 ? " cycle " : " cycles ") + "elapsed"; + public StringBuilder getInfo(final StringBuilder sb) { + final int c = getCycle(); + return sb.append("Experiment: ").append(c).append(c == 1 ? " cycle " : " cycles ").append("elapsed"); } - } /** @@ -375,9 +358,7 @@ public String getInfo() { * * @return the delay in milliseconds */ - public double getDelayInMilliseconds() { - return clockScope.getExperiment().getMinimumDuration() * 1000; - } + public double getDelayInMilliseconds() { return clockScope.getExperiment().getMinimumDuration() * 1000; } /** * Gets the current date. @@ -385,9 +366,7 @@ public double getDelayInMilliseconds() { * @return the current date */ public GamaDate getCurrentDate() { - if (currentDate == null) { - currentDate = getStartingDate(); - } + if (currentDate == null) { currentDate = getStartingDate(); } return currentDate; } @@ -397,16 +376,15 @@ public GamaDate getCurrentDate() { * @return the starting date */ public GamaDate getStartingDate() { - if (startingDate == null) { - setStartingDate(Dates.DATES_STARTING_DATE.getValue()); - } + if (startingDate == null) { setStartingDate(Dates.DATES_STARTING_DATE.getValue()); } return startingDate; } /** * Sets the starting date. * - * @param starting_date the new starting date + * @param starting_date + * the new starting date */ public void setStartingDate(final GamaDate starting_date) { this.startingDate = starting_date; @@ -417,10 +395,9 @@ public void setStartingDate(final GamaDate starting_date) { /** * Sets the current date. * - * @param date the new current date + * @param date + * the new current date */ - public void setCurrentDate(final GamaDate date) { - currentDate = date; - } + public void setCurrentDate(final GamaDate date) { currentDate = date; } } diff --git a/msi.gama.core/src/msi/gama/kernel/simulation/SimulationPopulation.java b/msi.gama.core/src/msi/gama/kernel/simulation/SimulationPopulation.java index 3f49d52388..8ec84a50a0 100644 --- a/msi.gama.core/src/msi/gama/kernel/simulation/SimulationPopulation.java +++ b/msi.gama.core/src/msi/gama/kernel/simulation/SimulationPopulation.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * SimulationPopulation.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * SimulationPopulation.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.kernel.simulation; @@ -43,15 +43,17 @@ public class SimulationPopulation extends GamaPopulation { /** The current simulation. */ private SimulationAgent currentSimulation; - + /** The runner. */ private final SimulationRunner runner; /** * Instantiates a new simulation population. * - * @param agent the agent - * @param species the species + * @param agent + * the agent + * @param species + * the species */ public SimulationPopulation(final ExperimentAgent agent, final ISpecies species) { super(agent, species); @@ -104,7 +106,7 @@ public IList createAgents(final IScope scope, final int number, final IList result = GamaListFactory.create(SimulationAgent.class); for (int i = 0; i < number; i++) { - scope.getGui().getStatus(scope).waitStatus("Initializing simulation"); + scope.getGui().getStatus().waitStatus("Initializing simulation"); // Model do not only rely on SimulationAgent final IAgentConstructor constr = species.getDescription().getAgentConstructor(); @@ -126,18 +128,25 @@ public IList createAgents(final IScope scope, final int number, /** * Inits the simulation. * - * @param scope the scope - * @param sim the sim - * @param initialValues the initial values - * @param index the index - * @param isRestored the is restored - * @param toBeScheduled the to be scheduled - * @param sequence the sequence + * @param scope + * the scope + * @param sim + * the sim + * @param initialValues + * the initial values + * @param index + * the index + * @param isRestored + * the is restored + * @param toBeScheduled + * the to be scheduled + * @param sequence + * the sequence */ private void initSimulation(final IScope scope, final SimulationAgent sim, final List> initialValues, final int index, final boolean isRestored, final boolean toBeScheduled, final RemoteSequence sequence) { - scope.getGui().getStatus(scope).waitStatus("Instantiating agents"); + scope.getGui().getStatus().waitStatus("Instantiating agents"); if (toBeScheduled) { sim.prepareGuiForSimulation(scope); } final Map firstInitValues = initialValues.isEmpty() ? null : initialValues.get(index); @@ -171,9 +180,7 @@ protected boolean allowVarInitToBeOverridenByExternalInit(final IVariable var) { } @Override - public ExperimentAgent getHost() { - return (ExperimentAgent) super.getHost(); - } + public ExperimentAgent getHost() { return (ExperimentAgent) super.getHost(); } @Override public SimulationAgent getAgent(final IScope scope, final GamaPoint value) { @@ -183,11 +190,10 @@ public SimulationAgent getAgent(final IScope scope, final GamaPoint value) { /** * Sets the host. * - * @param agent the new host + * @param agent + * the new host */ - public void setHost(final ExperimentAgent agent) { - host = agent; - } + public void setHost(final ExperimentAgent agent) { host = agent; } @Override public void computeTopology(final IScope scope) throws GamaRuntimeException { @@ -215,9 +221,7 @@ public void unscheduleSimulation(final SimulationAgent sim) { * * @return the number of active threads */ - public int getNumberOfActiveThreads() { - return runner.getActiveThreads(); - } + public int getNumberOfActiveThreads() { return runner.getActiveThreads(); } /** * @return diff --git a/msi.gama.core/src/msi/gama/metamodel/agent/AbstractAgent.java b/msi.gama.core/src/msi/gama/metamodel/agent/AbstractAgent.java index 71ed3b49b5..02821fc2e5 100644 --- a/msi.gama.core/src/msi/gama/metamodel/agent/AbstractAgent.java +++ b/msi.gama.core/src/msi/gama/metamodel/agent/AbstractAgent.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * AbstractAgent.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * AbstractAgent.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.metamodel.agent; @@ -14,11 +14,8 @@ import java.util.Map; import java.util.Map.Entry; -import org.locationtech.jts.geom.Geometry; - import com.google.common.primitives.Ints; -import msi.gama.common.geometry.Envelope3D; import msi.gama.common.interfaces.BiConsumerWithPruning; import msi.gama.common.interfaces.IKeyword; import msi.gama.kernel.model.IModel; @@ -72,17 +69,18 @@ public abstract class AbstractAgent implements IAgent { /** The index. */ private final int index; - + /** The dead. */ protected volatile boolean dead = false; - + /** The dying. */ protected volatile boolean dying = false; /** * Instantiates a new abstract agent. * - * @param index the index + * @param index + * the index */ public AbstractAgent(final int index) { this.index = index; @@ -94,81 +92,6 @@ public AbstractAgent(final int index) { @Override public void setAgent(final IAgent agent) {} - @Override - public boolean isPoint() { return getGeometry().isPoint(); } - - @Override - public boolean isLine() { return getGeometry().isLine(); } - - /** - * @see msi.gama.interfaces.IShape#getInnerGeometry() - */ - @Override - public Geometry getInnerGeometry() { return getGeometry().getInnerGeometry(); } - - /** - * Returns the envelope of the geometry of the agent, or null if the geometry has not yet been defined - * - * @see msi.gama.interfaces.IShape#getEnvelope() - */ - @Override - public Envelope3D getEnvelope() { - final IShape g = getGeometry(); - return g == null ? null : g.getEnvelope(); - } - - /** - * @see msi.gama.interfaces.IShape#covers(msi.gama.interfaces.IGeometry) - */ - @Override - public boolean covers(final IShape g) { - return getGeometry().covers(g); - } - - /** - * @see msi.gama.interfaces.IShape#euclidianDistanceTo(msi.gama.interfaces.IGeometry) - */ - @Override - public double euclidianDistanceTo(final IShape g) { - return getGeometry().euclidianDistanceTo(g); - } - - @Override - public double euclidianDistanceTo(final GamaPoint g) { - return getGeometry().euclidianDistanceTo(g); - } - - /** - * @see msi.gama.interfaces.IGeometry#intersects(msi.gama.interfaces.IGeometry) - */ - @Override - public boolean intersects(final IShape g) { - return getGeometry().intersects(g); - } - - @Override - public boolean partiallyOverlaps(final IShape g) { - return getGeometry().partiallyOverlaps(g); - } - - @Override - public boolean touches(final IShape g) { - return getGeometry().touches(g); - } - - @Override - public boolean crosses(final IShape g) { - return getGeometry().crosses(g); - } - - /** - * @see msi.gama.common.interfaces.IGeometry#setInnerGeometry(org.locationtech.jts.geom.Geometry) - */ - @Override - public void setInnerGeometry(final Geometry geom) { - getGeometry().setInnerGeometry(geom); - } - @Override public void dispose() { if (dead) return; @@ -285,7 +208,8 @@ protected boolean doStep(final IScope scope) { /** * Inits the sub populations. * - * @param scope the scope + * @param scope + * the scope * @return true, if successful */ protected boolean initSubPopulations(final IScope scope) { @@ -295,7 +219,8 @@ protected boolean initSubPopulations(final IScope scope) { /** * Step sub populations. * - * @param scope the scope + * @param scope + * the scope * @return true, if successful */ protected boolean stepSubPopulations(final IScope scope) { @@ -503,9 +428,11 @@ public final Object primDebug(final IScope scope) throws GamaRuntimeException { /** * Prim write. * - * @param scope the scope + * @param scope + * the scope * @return the object - * @throws GamaRuntimeException the gama runtime exception + * @throws GamaRuntimeException + * the gama runtime exception */ @action ( name = "write", @@ -526,9 +453,11 @@ public final Object primWrite(final IScope scope) throws GamaRuntimeException { /** * Prim error. * - * @param scope the scope + * @param scope + * the scope * @return the object - * @throws GamaRuntimeException the gama runtime exception + * @throws GamaRuntimeException + * the gama runtime exception */ @action ( name = IKeyword.ERROR, @@ -545,9 +474,11 @@ public final Object primError(final IScope scope) throws GamaRuntimeException { /** * Prim tell. * - * @param scope the scope + * @param scope + * the scope * @return the object - * @throws GamaRuntimeException the gama runtime exception + * @throws GamaRuntimeException + * the gama runtime exception */ @action ( name = "tell", @@ -564,9 +495,11 @@ public final Object primTell(final IScope scope) throws GamaRuntimeException { /** * Prim die. * - * @param scope the scope + * @param scope + * the scope * @return the object - * @throws GamaRuntimeException the gama runtime exception + * @throws GamaRuntimeException + * the gama runtime exception */ @action ( name = "die", @@ -611,27 +544,11 @@ public Object getFromIndicesList(final IScope scope, final IList indices /** * Sets the defining plugin. * - * @param plugin the new defining plugin + * @param plugin + * the new defining plugin */ public void setDefiningPlugin(final String plugin) {} - /** - * Method getPoints() - * - * @see msi.gama.metamodel.shape.IShape#getPoints() - */ - @Override - public IList getPoints() { - if (getGeometry() == null) return GamaListFactory.EMPTY_LIST; - return getGeometry().getPoints(); - } - - @Override - public void setDepth(final double depth) { - if (getGeometry() == null) return; - getGeometry().setDepth(depth); - } - @Override public void updateWith(final IScope scope, final SavedAgent sa) { // Update attributes diff --git a/msi.gama.core/src/msi/gama/metamodel/agent/GamlAgent.java b/msi.gama.core/src/msi/gama/metamodel/agent/GamlAgent.java index e15caeb46e..fd741c77d7 100644 --- a/msi.gama.core/src/msi/gama/metamodel/agent/GamlAgent.java +++ b/msi.gama.core/src/msi/gama/metamodel/agent/GamlAgent.java @@ -1,12 +1,11 @@ /******************************************************************************************************* * - * GamlAgent.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * GamlAgent.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.metamodel.agent; @@ -48,7 +47,7 @@ public class GamlAgent extends MinimalAgent implements IMacroAgent { /** The micro populations. */ // micropopulations protected IPopulation[] microPopulations; - + /** The Constant NO_POP. */ static final IPopulation[] NO_POP = new IPopulation[0]; @@ -73,12 +72,13 @@ public GamlAgent(final IPopulation gridPopulation, final int i /** * Checks if is population. * - * @param populationName the population name + * @param populationName + * the population name * @return the boolean */ private Boolean isPopulation(final String populationName) { final IVariable v = getSpecies().getVar(populationName); - if (v == null) { return false; } + if (v == null) return false; return v.isMicroPopulation(); } @@ -87,9 +87,7 @@ public IPopulation[] getMicroPopulations() { if (microPopulations == null) { final List> pops = new ArrayList<>(); forEachAttribute((s, o) -> { - if (isPopulation(s)) { - pops.add((IPopulation) o); - } + if (isPopulation(s)) { pops.add((IPopulation) o); } return true; }); microPopulations = pops.toArray(new IPopulation[pops.size()]); @@ -102,9 +100,10 @@ public IPopulation[] getMicroPopulations() { return microPopulations; } + @Override protected boolean initSubPopulations(final IScope scope) { for (final IPopulation pop : getMicroPopulations()) { - if (!scope.init(pop).passed()) { return false; } + if (!scope.init(pop).passed()) return false; } return true; } @@ -112,7 +111,7 @@ protected boolean initSubPopulations(final IScope scope) { @Override protected boolean stepSubPopulations(final IScope scope) { for (final IPopulation pop : getMicroPopulations()) { - if (!scope.step(pop).passed()) { return false; } + if (!scope.step(pop).passed()) return false; } return true; } @@ -121,16 +120,13 @@ protected boolean stepSubPopulations(final IScope scope) { public IList captureMicroAgents(final IScope scope, final ISpecies microSpecies, final IList microAgents) throws GamaRuntimeException { if (microAgents == null || microAgents.isEmpty() || microSpecies == null - || !this.getSpecies().getMicroSpecies().contains(microSpecies)) { + || !this.getSpecies().getMicroSpecies().contains(microSpecies)) return GamaListFactory.EMPTY_LIST; - } try (final ICollector candidates = Collector.getList(); final Collector.AsList capturedAgents = Collector.getList()) { for (final IAgent a : microAgents.iterable(scope)) { - if (this.canCapture(a, microSpecies)) { - candidates.add(a); - } + if (this.canCapture(a, microSpecies)) { candidates.add(a); } } final IPopulation microSpeciesPopulation = this.getPopulationFor(microSpecies); for (final IAgent micro : candidates) { @@ -183,9 +179,7 @@ public IList migrateMicroAgents(final IScope scope, final IList final List immigrantCandidates = GamaListFactory.create(Types.AGENT); for (final IAgent m : microAgents.iterable(scope)) { - if (m.getSpecies().isPeer(newMicroSpecies)) { - immigrantCandidates.add(m); - } + if (m.getSpecies().isPeer(newMicroSpecies)) { immigrantCandidates.add(m); } } final IList immigrants = GamaListFactory.create(Types.AGENT); @@ -234,15 +228,19 @@ public void initializeMicroPopulation(final IScope scope, final String name) { final IPopulation microPop = GamaPopulation.createPopulation(scope, this, microSpec); registerMicropopulation(scope, microSpec, microPop); } - + /** * Register micropopulation. * - * @param scope the scope - * @param microSpec the micro spec - * @param microPop the micro pop + * @param scope + * the scope + * @param microSpec + * the micro spec + * @param microPop + * the micro pop */ - protected void registerMicropopulation(IScope scope, ISpecies microSpec, IPopulation microPop) { + protected void registerMicropopulation(final IScope scope, final ISpecies microSpec, + final IPopulation microPop) { setAttribute(microSpec.getName(), microPop); microPop.initializeFor(scope); } @@ -250,11 +248,9 @@ protected void registerMicropopulation(IScope scope, ISpecies microSpec, IPopula @SuppressWarnings ("rawtypes") @Override public void dispose() { - if (dead) { return; } + if (dead) return; final IPopulation[] microPops = getMicroPopulations(); - for (final IPopulation pop : microPops) { - pop.dispose(); - } + for (final IPopulation pop : microPops) { pop.dispose(); } final Object graph = getAttribute("attached_graph"); if (graph instanceof GamaGraph) { @@ -267,7 +263,7 @@ public void dispose() { @Override public synchronized IPopulation getMicroPopulation(final String microSpeciesName) { final Object o = getAttribute(microSpeciesName); - if (o instanceof IPopulation) { return (IPopulation) o; } + if (o instanceof IPopulation) return (IPopulation) o; return null; } @@ -279,25 +275,15 @@ public IPopulation getMicroPopulation(final ISpecies microSpec @Override public boolean hasMembers() { - if (dead()) { return false; } - for (final IPopulation pop : getMicroPopulations()) { - if (pop.size() > 0) { return true; } - } + if (dead()) return false; + for (final IPopulation pop : getMicroPopulations()) { if (pop.size() > 0) return true; } return false; } @Override public IContainer getMembers(final IScope scope) { - if (dead()) { return GamaListFactory.EMPTY_LIST; } - final MetaPopulation mp = new MetaPopulation(getMicroPopulations()); - // forEachAttribute((s, pop) -> { - // if (pop instanceof IPopulation && ((IPopulation) pop).size() > 0) { - // mp.addPopulation((IPopulation) pop); - // } - // return true; - // }); - - return mp; + if (dead()) return GamaListFactory.EMPTY_LIST; + return new MetaPopulation(getMicroPopulations()); } @Override @@ -328,15 +314,13 @@ public void setAgents(final IList agents) { @Override public IList getAgents(final IScope scope) { - if (!hasMembers()) { return GamaListFactory.EMPTY_LIST; } + if (!hasMembers()) return GamaListFactory.EMPTY_LIST; final IContainer members = getMembers(scope); final IList agents = GamaListFactory.create(Types.AGENT); agents.addAll(members.listValue(scope, Types.NO_TYPE, false)); for (final IAgent m : members.iterable(scope)) { - if (m instanceof IMacroAgent) { - agents.addAll(((IMacroAgent) m).getAgents(scope)); - } + if (m instanceof IMacroAgent) { agents.addAll(((IMacroAgent) m).getAgents(scope)); } } return agents; @@ -351,9 +335,7 @@ public IPopulation getPopulationFor(final ISpecies species) { IPopulation microPopulation = null; if (main.getMicroModel(micro.getAlias()) == null) { microPopulation = this.getMicroPopulation(species); - if (microPopulation == null && getHost() != null) { - microPopulation = getHost().getPopulationFor(species); - } + if (microPopulation == null && getHost() != null) { microPopulation = getHost().getPopulationFor(species); } } else { microPopulation = this.getScope().getSimulation() .getExternMicroPopulationFor(micro.getAlias() + "." + species.getName()); @@ -365,7 +347,7 @@ public IPopulation getPopulationFor(final ISpecies species) { @Override public IPopulation getPopulationFor(final String speciesName) { final IPopulation microPopulation = this.getMicroPopulation(speciesName); - if (microPopulation == null && getHost() != null) { return getHost().getPopulationFor(speciesName); } + if (microPopulation == null && getHost() != null) return getHost().getPopulationFor(speciesName); return microPopulation; } @@ -379,11 +361,10 @@ public IPopulation getPopulationFor(final String speciesName) */ @Override public boolean canCapture(final IAgent other, final ISpecies newSpecies) { - if (other == null || other.dead() || newSpecies == null || !this.getSpecies().containMicroSpecies(newSpecies)) { + if (other == null || other.dead() || newSpecies == null || !this.getSpecies().containMicroSpecies(newSpecies)) return false; - } - if (this.getMacroAgents().contains(other)) { return false; } - return !other.getHost().equals(this); + if (this.getMacroAgents().contains(other)) return false; + return !this.equals(other.getHost()); } @Override @@ -396,32 +377,8 @@ public void addExternMicroPopulation(final String expName, final IPopulation getExternMicroPopulationFor(final String expName) { - if (externMicroPopulations != null) { return externMicroPopulations.get(expName); } + if (externMicroPopulations != null) return externMicroPopulations.get(expName); return null; } - // - // @Override - // public GamaMap> - // getExternMicroPopulations() { - // if (externMicroPopulations == null) { - // return GamaMapFactory.create(); - // } - // return externMicroPopulations; - // } - - // @Override - // public int getNbAgents() { - // return nbSubAgents; - // } - // - // @Override - // public void addSubAgents(final int nb) { - // nbSubAgents += nb; - // } - // - // @Override - // public void removeAgent() { - // nbSubAgents--; - // } } diff --git a/msi.gama.core/src/msi/gama/metamodel/agent/IAgent.java b/msi.gama.core/src/msi/gama/metamodel/agent/IAgent.java index 70dba8c8fe..6c958b81e4 100644 --- a/msi.gama.core/src/msi/gama/metamodel/agent/IAgent.java +++ b/msi.gama.core/src/msi/gama/metamodel/agent/IAgent.java @@ -1,17 +1,19 @@ /******************************************************************************************************* * - * IAgent.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * IAgent.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.metamodel.agent; import java.util.List; +import org.locationtech.jts.geom.Geometry; + +import msi.gama.common.geometry.Envelope3D; import msi.gama.common.interfaces.IKeyword; import msi.gama.common.interfaces.INamed; import msi.gama.common.interfaces.IScoped; @@ -20,6 +22,7 @@ import msi.gama.kernel.model.IModel; import msi.gama.metamodel.population.IPopulation; import msi.gama.metamodel.shape.GamaPoint; +import msi.gama.metamodel.shape.GamaShape; import msi.gama.metamodel.shape.IShape; import msi.gama.metamodel.topology.ITopology; import msi.gama.precompiler.GamlAnnotations.doc; @@ -30,6 +33,7 @@ import msi.gama.precompiler.ITypeProvider; import msi.gama.runtime.IScope; import msi.gama.runtime.exceptions.GamaRuntimeException; +import msi.gama.util.GamaListFactory; import msi.gama.util.IContainer; import msi.gama.util.IList; import msi.gaml.species.ISpecies; @@ -81,7 +85,8 @@ public interface IAgent extends /* ISkill, */ IShape, INamed, Comparable /** * Sets the peers. * - * @param peers the new peers + * @param peers + * the new peers */ @setter (IKeyword.PEERS) void setPeers(IList peers); @@ -108,7 +113,8 @@ public interface IAgent extends /* ISkill, */ IShape, INamed, Comparable /** * Sets the name. * - * @param name the new name + * @param name + * the new name */ @Override @setter (IKeyword.NAME) @@ -128,7 +134,8 @@ public interface IAgent extends /* ISkill, */ IShape, INamed, Comparable /** * Sets the location. * - * @param l the l + * @param l + * the l * @return the gama point */ @Override @@ -136,7 +143,7 @@ public interface IAgent extends /* ISkill, */ IShape, INamed, Comparable GamaPoint setLocation(final GamaPoint l); /** - * Gets the geometry. + * Gets the getGeometry(). * * @return the geometry */ @@ -145,9 +152,10 @@ public interface IAgent extends /* ISkill, */ IShape, INamed, Comparable IShape getGeometry(); /** - * Sets the geometry. + * Sets the getGeometry(). * - * @param newGeometry the new geometry + * @param newGeometry + * the new geometry */ @Override @setter (IKeyword.SHAPE) @@ -171,7 +179,8 @@ public interface IAgent extends /* ISkill, */ IShape, INamed, Comparable /** * Sets the host. * - * @param macroAgent the new host + * @param macroAgent + * the new host */ @setter (IKeyword.HOST) void setHost(final IMacroAgent macroAgent); @@ -179,7 +188,8 @@ public interface IAgent extends /* ISkill, */ IShape, INamed, Comparable /** * Schedule. * - * @param scope the scope + * @param scope + * the scope */ void schedule(IScope scope); @@ -214,8 +224,10 @@ public interface IAgent extends /* ISkill, */ IShape, INamed, Comparable /** * Checks if is instance of. * - * @param s the s - * @param direct the direct + * @param s + * the s + * @param direct + * the direct * @return true, if is instance of */ boolean isInstanceOf(final ISpecies s, boolean direct); @@ -223,20 +235,27 @@ public interface IAgent extends /* ISkill, */ IShape, INamed, Comparable /** * Gets the direct var value. * - * @param scope the scope - * @param s the s + * @param scope + * the scope + * @param s + * the s * @return the direct var value - * @throws GamaRuntimeException the gama runtime exception + * @throws GamaRuntimeException + * the gama runtime exception */ Object getDirectVarValue(IScope scope, String s) throws GamaRuntimeException; /** * Sets the direct var value. * - * @param scope the scope - * @param s the s - * @param v the v - * @throws GamaRuntimeException the gama runtime exception + * @param scope + * the scope + * @param s + * the s + * @param v + * the v + * @throws GamaRuntimeException + * the gama runtime exception */ void setDirectVarValue(IScope scope, String s, Object v) throws GamaRuntimeException; @@ -269,8 +288,10 @@ default void notifyVarValueChange(final String varName, final Object newValue) { /** * Checks if is instance of. * - * @param skill the skill - * @param direct the direct + * @param skill + * the skill + * @param direct + * the direct * @return true, if is instance of */ boolean isInstanceOf(String skill, boolean direct); @@ -305,8 +326,259 @@ default void notifyVarValueChange(final String varName, final Object newValue) { /** * Update with. * - * @param s the s - * @param sa the sa + * @param s + * the s + * @param sa + * the sa */ void updateWith(final IScope s, final SavedAgent sa); + + /*** + * All the methods of IShape are delegated by default to getGeometry() + */ + + /** + * Method getArea(). Simply delegates to the geometry + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getArea() + */ + @Override + default Double getArea() { return getGeometry().getArea(); } + + /** + * Method getVolume(). Simply delegates to the geometry + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getVolume() + */ + @Override + default Double getVolume() { return getGeometry().getVolume(); } + + /** + * Method getPerimeter() + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getPerimeter() + */ + @Override + default double getPerimeter() { return getGeometry().getPerimeter(); } + + /** + * Method getHoles() + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getHoles() + */ + @Override + default IList getHoles() { return getGeometry().getHoles(); } + + /** + * Method getCentroid() + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getCentroid() + */ + @Override + default GamaPoint getCentroid() { return getGeometry().getCentroid(); } + + /** + * Method getExteriorRing() + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getExteriorRing() + */ + @Override + default GamaShape getExteriorRing(final IScope scope) { + return getGeometry().getExteriorRing(scope); + } + + /** + * Method getWidth() + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getWidth() + */ + @Override + default Double getWidth() { return getGeometry().getWidth(); } + + /** + * Method getHeight() + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getDepth() + */ + @Override + default Double getHeight() { return getGeometry().getHeight(); } + + /** + * Method getDepth() + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getDepth() + */ + @Override + default Double getDepth() { return getGeometry().getDepth(); } + + /** + * Method getGeometricEnvelope() + * + * @see msi.gama.metamodel.shape.IGeometricalShape#getGeometricEnvelope() + */ + @Override + default GamaShape getGeometricEnvelope() { return getGeometry().getGeometricEnvelope(); } + + /** + * Gets the geometries. + * + * @return the geometries + */ + @Override + default IList getGeometries() { return getGeometry().getGeometries(); } + + /** + * Method isMultiple() + * + * @see msi.gama.metamodel.shape.IShape#isMultiple() + */ + @Override + default boolean isMultiple() { return getGeometry().isMultiple(); } + + /** + * Checks if is point. + * + * @return true, if is point + */ + @Override + default boolean isPoint() { return getGeometry().isPoint(); } + + /** + * Checks if is line. + * + * @return true, if is line + */ + @Override + default boolean isLine() { return getGeometry().isLine(); } + + /** + * @see msi.gama.interfaces.IShape#getInnerGeometry() + */ + @Override + default Geometry getInnerGeometry() { return getGeometry().getInnerGeometry(); } + + /** + * Returns the envelope of the geometry of the agent, or null if the geometry has not yet been defined + * + * @see msi.gama.interfaces.IShape#getEnvelope() + */ + @Override + default Envelope3D getEnvelope() { + final IShape g = getGeometry(); + return g == null ? null : g.getEnvelope(); + } + + /** + * @see msi.gama.interfaces.IShape#covers(msi.gama.interfaces.IGeometry) + */ + @Override + default boolean covers(final IShape g) { + return getGeometry().covers(g); + } + + /** + * @see msi.gama.interfaces.IShape#euclidianDistanceTo(msi.gama.interfaces.IGeometry) + */ + @Override + default double euclidianDistanceTo(final IShape g) { + return getGeometry().euclidianDistanceTo(g); + } + + /** + * Euclidian distance to. + * + * @param g + * the g + * @return the double + */ + @Override + default double euclidianDistanceTo(final GamaPoint g) { + return getGeometry().euclidianDistanceTo(g); + } + + /** + * @see msi.gama.interfaces.IGeometry#intersects(msi.gama.interfaces.IGeometry) + */ + @Override + default boolean intersects(final IShape g) { + return getGeometry().intersects(g); + } + + /** + * Partially overlaps. + * + * @param g + * the g + * @return true, if successful + */ + @Override + default boolean partiallyOverlaps(final IShape g) { + return getGeometry().partiallyOverlaps(g); + } + + /** + * Touches. + * + * @param g + * the g + * @return true, if successful + */ + @Override + default boolean touches(final IShape g) { + return getGeometry().touches(g); + } + + /** + * Crosses. + * + * @param g + * the g + * @return true, if successful + */ + @Override + default boolean crosses(final IShape g) { + return getGeometry().crosses(g); + } + + /** + * @see msi.gama.common.interfaces.IGeometry#setInnerGeometry(org.locationtech.jts.geom.Geometry) + */ + @Override + default void setInnerGeometry(final Geometry geom) { + getGeometry().setInnerGeometry(geom); + } + + /** + * Method getPoints() + * + * @see msi.gama.metamodel.shape.IShape#getPoints() + */ + @Override + default IList getPoints() { + if (getGeometry() == null) return GamaListFactory.EMPTY_LIST; + return getGeometry().getPoints(); + } + + /** + * Sets the depth. + * + * @param depth + * the new depth + */ + @Override + default void setDepth(final double depth) { + if (getGeometry() == null) return; + getGeometry().setDepth(depth); + } + + /** + * Sets the geometrical type. + * + * @param t the new geometrical type + */ + @Override + default void setGeometricalType(final Type t) { + getGeometry().setGeometricalType(t); + } + } \ No newline at end of file diff --git a/msi.gama.core/src/msi/gama/metamodel/agent/MinimalAgent.java b/msi.gama.core/src/msi/gama/metamodel/agent/MinimalAgent.java index 3a565bd744..9927fa849c 100644 --- a/msi.gama.core/src/msi/gama/metamodel/agent/MinimalAgent.java +++ b/msi.gama.core/src/msi/gama/metamodel/agent/MinimalAgent.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * MinimalAgent.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * MinimalAgent.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.metamodel.agent; @@ -26,7 +26,6 @@ import msi.gama.precompiler.GamlAnnotations.doc; import msi.gama.precompiler.GamlAnnotations.species; import msi.gama.runtime.IScope; -import msi.gama.util.IList; import msi.gama.util.graph.GamaGraph; import msi.gaml.species.GamlSpecies; import msi.gaml.species.ISpecies; @@ -49,13 +48,13 @@ public class MinimalAgent extends AbstractAgent { /** The population that this agent belongs to. */ protected final IPopulation population; - + /** The name. */ protected String name; - + /** The geometry. */ protected final IShape geometry; - + /** The hash code. */ private final int hashCode; @@ -70,9 +69,12 @@ public MinimalAgent(final IPopulation s, final int index) { /** * Instantiates a new minimal agent. * - * @param population the population that this agent belongs to. - * @param index the index - * @param geometry the geometry + * @param population + * the population that this agent belongs to. + * @param index + * the index + * @param geometry + * the geometry */ protected MinimalAgent(final IPopulation population, final int index, final IShape geometry) { super(index); @@ -83,19 +85,10 @@ protected MinimalAgent(final IPopulation population, final int } @Override - public void setGeometricalType(final Type t) { - geometry.setGeometricalType(t); - } - - @Override - public IPopulation getPopulation() { - return population; - } + public IPopulation getPopulation() { return population; } @Override - public IShape getGeometry() { - return geometry; - } + public IShape getGeometry() { return geometry; } @Override public/* synchronized */void setGeometry(final IShape newGeometry) { @@ -143,10 +136,8 @@ public IShape getGeometry() { @Override public String getName() { if (name == null) { name = super.getName(); } - if (dead()) - return name + " (dead)"; - else - return name; + if (dead()) return name + " (dead)"; + return name; } @Override @@ -249,8 +240,8 @@ public boolean doStep(final IScope scope) { if (!getPopulation().isStepOverriden()) { super.doStep(scope); return !scope.interrupted(); - } else - return scope.execute(getSpecies().getAction(ISpecies.stepActionName), this, null).passed(); + } + return scope.execute(getSpecies().getAction(ISpecies.stepActionName), this, null).passed(); } /** @@ -267,8 +258,10 @@ public Object _init_(final IScope scope) { } /** - * The default step of agents consists in calling the super implementation of doStep() in order to realize the - * default step sequence + * The default step of agents consists in calling the super implementation of step() in order to realize the default + * step sequence + * + * TODO verify this sequence as _step_() is NEVER called (only from GAML if done explicitly) * * @param scope * @return @@ -279,121 +272,6 @@ public Object _step_(final IScope scope) { return super.step(scope); } - /** - * Method getArea(). Simply delegates to the geometry - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getArea() - */ - @Override - public Double getArea() { - return geometry.getArea(); - } - - /** - * Method getVolume(). Simply delegates to the geometry - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getVolume() - */ - @Override - public Double getVolume() { - return geometry.getVolume(); - } - - /** - * Method getPerimeter() - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getPerimeter() - */ - @Override - public double getPerimeter() { - return geometry.getPerimeter(); - } - - /** - * Method getHoles() - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getHoles() - */ - @Override - public IList getHoles() { - return geometry.getHoles(); - } - - /** - * Method getCentroid() - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getCentroid() - */ - @Override - public GamaPoint getCentroid() { - return geometry.getCentroid(); - } - - /** - * Method getExteriorRing() - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getExteriorRing() - */ - @Override - public GamaShape getExteriorRing(final IScope scope) { - return geometry.getExteriorRing(scope); - } - - /** - * Method getWidth() - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getWidth() - */ - @Override - public Double getWidth() { - return geometry.getWidth(); - } - - /** - * Method getHeight() - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getDepth() - */ - @Override - public Double getHeight() { - return geometry.getHeight(); - } - - /** - * Method getDepth() - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getDepth() - */ - @Override - public Double getDepth() { - return geometry.getDepth(); - } - - /** - * Method getGeometricEnvelope() - * - * @see msi.gama.metamodel.shape.IGeometricalShape#getGeometricEnvelope() - */ - @Override - public GamaShape getGeometricEnvelope() { - return geometry.getGeometricEnvelope(); - } - - @Override - public IList getGeometries() { - return geometry.getGeometries(); - } - - /** - * Method isMultiple() - * - * @see msi.gama.metamodel.shape.IShape#isMultiple() - */ - @Override - public boolean isMultiple() { - return geometry.isMultiple(); - } - @Override public final int hashCode() { return hashCode; diff --git a/msi.gama.core/src/msi/gama/outputs/SimulationOutputManager.java b/msi.gama.core/src/msi/gama/outputs/SimulationOutputManager.java index 860ff27f84..1513d4d2b9 100644 --- a/msi.gama.core/src/msi/gama/outputs/SimulationOutputManager.java +++ b/msi.gama.core/src/msi/gama/outputs/SimulationOutputManager.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * SimulationOutputManager.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * SimulationOutputManager.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation + * platform (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.outputs; @@ -72,7 +72,8 @@ public static SimulationOutputManager createEmpty() { /** * Instantiates a new simulation output manager. * - * @param desc the desc + * @param desc + * the desc */ public SimulationOutputManager(final IDescription desc) { super(desc); @@ -80,22 +81,22 @@ public SimulationOutputManager(final IDescription desc) { @Override public boolean init(final IScope scope) { - scope.getGui().getStatus(scope).waitStatus(" Building outputs "); + scope.getGui().getStatus().waitStatus(" Building outputs "); final boolean result = super.init(scope); updateDisplayOutputsName(scope.getSimulation()); - scope.getGui().getStatus(scope).informStatus(" " + scope.getRoot().getName() + " ready"); + scope.getGui().getStatus().informStatus(" " + scope.getRoot().getName() + " ready"); return result; } /** * Update display outputs name. * - * @param agent the agent + * @param agent + * the agent */ public void updateDisplayOutputsName(final SimulationAgent agent) { for (final IOutput out : this) { - if (out instanceof IDisplayOutput) { - final IDisplayOutput display = (IDisplayOutput) out; + if (out instanceof IDisplayOutput display) { GAMA.getGui().updateViewTitle(display, agent); } } diff --git a/msi.gama.core/src/msi/gama/runtime/ExecutionScope.java b/msi.gama.core/src/msi/gama/runtime/ExecutionScope.java index ac67d570e5..b87b5152d8 100644 --- a/msi.gama.core/src/msi/gama/runtime/ExecutionScope.java +++ b/msi.gama.core/src/msi/gama/runtime/ExecutionScope.java @@ -946,7 +946,7 @@ public boolean isPaused() { final IExperimentPlan plan = exp.getSpecies(); if (plan != null) { final IExperimentController controller = plan.getController(); - if (controller != null) return controller.getScheduler().paused() || isOnUserHold(); + if (controller != null) return controller.isPaused() || isOnUserHold(); } } return isOnUserHold(); diff --git a/msi.gama.core/src/msi/gama/runtime/GAMA.java b/msi.gama.core/src/msi/gama/runtime/GAMA.java index af93ba19f7..43a7b16702 100644 --- a/msi.gama.core/src/msi/gama/runtime/GAMA.java +++ b/msi.gama.core/src/msi/gama/runtime/GAMA.java @@ -113,7 +113,7 @@ public static void runGuiExperiment(final String id, final IModel model) { if (controller != null) { final IExperimentPlan existingExperiment = controller.getExperiment(); if (existingExperiment != null) { - controller.getScheduler().pause(); + controller.directPause(); if (!getGui().confirmClose(existingExperiment)) return; } } @@ -346,7 +346,7 @@ public static void stepFrontmostExperiment() { * Step back frontmost experiment. */ public static void stepBackFrontmostExperiment() { - for (final IExperimentController controller : controllers) { controller.stepBack(); } + for (final IExperimentController controller : controllers) { controller.userStepBack(); } } /** @@ -394,7 +394,7 @@ public static void startFrontmostExperiment() { public static boolean isPaused() { final IExperimentController controller = getFrontmostController(); if (controller == null || controller.getExperiment() == null) return true; - return controller.getScheduler().paused(); + return controller.isPaused(); } diff --git a/msi.gama.core/src/msi/gama/runtime/HeadlessListener.java b/msi.gama.core/src/msi/gama/runtime/HeadlessListener.java index 7038e63953..1ca7537284 100644 --- a/msi.gama.core/src/msi/gama/runtime/HeadlessListener.java +++ b/msi.gama.core/src/msi/gama/runtime/HeadlessListener.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * HeadlessListener.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * HeadlessListener.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.runtime; @@ -411,9 +411,7 @@ public void eraseConsole(final boolean setToNull) {} }; @Override - public IStatusDisplayer getStatus(final IScope scope) { - return status; - } + public IStatusDisplayer getStatus() { return status; } @Override public IConsoleDisplayer getConsole() { return console; } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaCSVFile.java b/msi.gama.core/src/msi/gama/util/file/GamaCSVFile.java index 78c79376ca..94a40fb2d7 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaCSVFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaCSVFile.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * GamaCSVFile.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * GamaCSVFile.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.file; @@ -481,7 +481,7 @@ private CSVInfo getInfo(final IScope scope, final String CSVSep) { public void fillBuffer(final IScope scope) { if (getBuffer() != null) return; if (csvSeparator == null || contentsType == null || userSize == null) { - scope.getGui().getStatus(scope).beginSubStatus("Opening file " + getName(scope)); + scope.getGui().getStatus().beginSubStatus("Opening file " + getName(scope)); final CSVInfo stats = getInfo(scope, csvSeparator); csvSeparator = csvSeparator == null ? "" + stats.delimiter : csvSeparator; contentsType = contentsType == null ? stats.type : contentsType; @@ -490,7 +490,7 @@ public void fillBuffer(final IScope scope) { // AD We take the decision for the modeler is he/she hasn't // specified if the header must be read or not. hasHeader = hasHeader == null ? stats.header : hasHeader; - scope.getGui().getStatus(scope).endSubStatus(""); + scope.getGui().getStatus().endSubStatus(""); } CsvReader reader = null; try { @@ -541,14 +541,14 @@ private IMatrix createMatrixFrom(final IScope scope, final CsvReader reader) thr double percentage = 0; IMatrix matrix; try { - scope.getGui().getStatus(scope).beginSubStatus("Reading file " + getName(scope)); + scope.getGui().getStatus().beginSubStatus("Reading file " + getName(scope)); if (t == IType.INT) { matrix = new GamaIntMatrix(userSize); final int[] m = ((GamaIntMatrix) matrix).getMatrix(); int i = 0; while (reader.readRecord()) { percentage = reader.getCurrentRecord() / userSize.y; - scope.getGui().getStatus(scope).setSubStatusCompletion(percentage); + scope.getGui().getStatus().setSubStatusCompletion(percentage); int nbC = 0; for (final String s : reader.getValues()) { m[i++] = Cast.asInt(scope, s); @@ -565,7 +565,7 @@ private IMatrix createMatrixFrom(final IScope scope, final CsvReader reader) thr int i = 0; while (reader.readRecord()) { percentage = reader.getCurrentRecord() / userSize.y; - scope.getGui().getStatus(scope).setSubStatusCompletion(percentage); + scope.getGui().getStatus().setSubStatusCompletion(percentage); int nbC = 0; for (final String s : reader.getValues()) { m[i++] = Cast.asFloat(scope, s); @@ -582,7 +582,7 @@ private IMatrix createMatrixFrom(final IScope scope, final CsvReader reader) thr int i = 0; while (reader.readRecord()) { percentage = reader.getCurrentRecord() / userSize.y; - scope.getGui().getStatus(scope).setSubStatusCompletion(percentage); + scope.getGui().getStatus().setSubStatusCompletion(percentage); int nbC = 0; for (final String s : reader.getValues()) { @@ -603,7 +603,7 @@ private IMatrix createMatrixFrom(final IScope scope, final CsvReader reader) thr return matrix; } finally { - scope.getGui().getStatus(scope).endSubStatus("Reading CSV File"); + scope.getGui().getStatus().endSubStatus("Reading CSV File"); } } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaFile.java b/msi.gama.core/src/msi/gama/util/file/GamaFile.java index 4dbabe79b8..0a9bb1a058 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaFile.java @@ -1,12 +1,11 @@ /******************************************************************************************************* * - * GamaFile.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * GamaFile.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.file; @@ -47,28 +46,31 @@ public abstract class GamaFile matrixValue(final IScope scope, final IType contentsType, fina /** * Matrix value. * - * @param scope the scope - * @param contentsType the contents type - * @param preferredSize the preferred size - * @param copy the copy + * @param scope + * the scope + * @param contentsType + * the contents type + * @param preferredSize + * the preferred size + * @param copy + * the copy * @return the i matrix - * @throws GamaRuntimeException the gama runtime exception + * @throws GamaRuntimeException + * the gama runtime exception */ protected IMatrix _matrixValue(final IScope scope, final IType contentsType, final GamaPoint preferredSize, final boolean copy) throws GamaRuntimeException { @@ -538,7 +561,8 @@ public Contents anyValue(final IScope scope) { /** * Gets the file. * - * @param scope the scope + * @param scope + * the scope * @return the file */ public File getFile(final IScope scope) { @@ -547,18 +571,15 @@ public File getFile(final IScope scope) { } @Override - public Container getBuffer() { - return buffer; - } + public Container getBuffer() { return buffer; } /** * Sets the buffer. * - * @param buffer the new buffer + * @param buffer + * the new buffer */ - protected void setBuffer(final Container buffer) { - this.buffer = buffer; - } + protected void setBuffer(final Container buffer) { this.buffer = buffer; } /** * Invalidate contents. diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGridFile.java b/msi.gama.core/src/msi/gama/util/file/GamaGridFile.java index 77d5afce8a..3ffc46b988 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGridFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGridFile.java @@ -389,7 +389,7 @@ private void privateCreateCoverage(final IScope scope, final InputStream fis) coverage = store.read(null); } finally { if (store != null) { store.dispose(); } - scope.getGui().getStatus(scope).endSubStatus("Opening file " + getName(scope)); + scope.getGui().getStatus().endSubStatus("Opening file " + getName(scope)); } } @@ -436,7 +436,7 @@ private InputStream fixFileHeader(final IScope scope) { void read(final IScope scope, final boolean readAll, final boolean createGeometries) { try { - scope.getGui().getStatus(scope).beginSubStatus("Reading file " + getName(scope)); + scope.getGui().getStatus().beginSubStatus("Reading file " + getName(scope)); final Envelope envP = gis.getProjectedEnvelope(); final double cellHeight = envP.getHeight() / numRows; @@ -468,7 +468,7 @@ void read(final IScope scope, final boolean readAll, final boolean createGeometr records.y = new double[numRows * numCols]; // y records.bands.add(new double[numRows * numCols]); // data for (int i = 0, n = numRows * numCols; i < n; i++) { - scope.getGui().getStatus(scope).setSubStatusCompletion(i / (double) n); + scope.getGui().getStatus().setSubStatusCompletion(i / (double) n); final int yy = i / numCols; final int xx = i - yy * numCols; @@ -524,7 +524,7 @@ void read(final IScope scope, final boolean readAll, final boolean createGeometr } catch (final Exception e) { throw error("The format of " + getName(scope) + " is not correct. Error: " + e.getMessage(), scope); } finally { - scope.getGui().getStatus(scope).endSubStatus("Reading file " + getName(scope)); + scope.getGui().getStatus().endSubStatus("Reading file " + getName(scope)); } } diff --git a/msi.gama.core/src/msi/gama/util/file/ProgressCounter.java b/msi.gama.core/src/msi/gama/util/file/ProgressCounter.java index 16603b5334..4935f0e403 100644 --- a/msi.gama.core/src/msi/gama/util/file/ProgressCounter.java +++ b/msi.gama.core/src/msi/gama/util/file/ProgressCounter.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * ProgressCounter.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * ProgressCounter.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.file; @@ -29,18 +29,20 @@ public class ProgressCounter implements ProgressListener, IIOReadProgressListene /** The scope. */ final IScope scope; - + /** The name. */ final String name; - + /** The progress. */ float progress; /** * Instantiates a new progress counter. * - * @param scope the scope - * @param name the name + * @param scope + * the scope + * @param name + * the name */ public ProgressCounter(final IScope scope, final String name) { this.scope = scope; @@ -52,7 +54,7 @@ public ProgressCounter(final IScope scope, final String name) { * * @return the displayer */ - IStatusDisplayer getDisplayer() { return scope.getGui().getStatus(scope); } + IStatusDisplayer getDisplayer() { return scope.getGui().getStatus(); } @Override public void complete() { diff --git a/msi.gama.core/src/msi/gaml/compilation/GAML.java b/msi.gama.core/src/msi/gaml/compilation/GAML.java index 9d34c9051e..7385b3470b 100644 --- a/msi.gama.core/src/msi/gaml/compilation/GAML.java +++ b/msi.gama.core/src/msi/gaml/compilation/GAML.java @@ -33,6 +33,7 @@ import com.google.common.collect.SetMultimap; import msi.gama.common.interfaces.ISkill; +import msi.gama.kernel.experiment.IExperimentPlan; import msi.gama.kernel.experiment.ITopLevelAgent; import msi.gama.metamodel.agent.IAgent; import msi.gama.runtime.GAMA; @@ -267,8 +268,9 @@ public static IExpression compileExpression(final String expression, final IAgen * @return the model context */ public static ModelDescription getModelContext() { - if (GAMA.getFrontmostController() == null) return null; - return (ModelDescription) GAMA.getFrontmostController().getExperiment().getModel().getDescription(); + IExperimentPlan experiment = GAMA.getExperiment(); + if (experiment == null) return null; + return (ModelDescription) experiment.getModel().getDescription(); } /** diff --git a/msi.gama.core/src/msi/gaml/statements/StatusStatement.java b/msi.gama.core/src/msi/gaml/statements/StatusStatement.java index bcc5a3e38e..7a52779854 100644 --- a/msi.gama.core/src/msi/gaml/statements/StatusStatement.java +++ b/msi.gama.core/src/msi/gaml/statements/StatusStatement.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * StatusStatement.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * StatusStatement.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.statements; @@ -30,9 +30,9 @@ /** * Written by drogoul Modified on 6 févr. 2010 - * + * * @todo Description - * + * */ @symbol ( @@ -69,14 +69,15 @@ public String getTrace(final IScope scope) { /** The message. */ final IExpression message; - + /** The color. */ final IExpression color; /** * Instantiates a new status statement. * - * @param desc the desc + * @param desc + * the desc */ public StatusStatement(final IDescription desc) { super(desc); @@ -91,8 +92,7 @@ public Object privateExecuteIn(final IScope scope) throws GamaRuntimeException { if (agent != null && !agent.dead()) { final Object o = message.value(scope); final String msg = o == null ? null : Cast.asString(scope, o); - scope.getGui().getStatus(scope).setStatus(msg, - color == null ? null : Cast.asColor(scope, color.value(scope))); + scope.getGui().getStatus().setStatus(msg, color == null ? null : Cast.asColor(scope, color.value(scope))); } return mes; } diff --git a/msi.gama.headless/src/msi/gama/headless/batch/ModelLibraryTester.java b/msi.gama.headless/src/msi/gama/headless/batch/ModelLibraryTester.java index 67509929e1..23fb482c34 100644 --- a/msi.gama.headless/src/msi/gama/headless/batch/ModelLibraryTester.java +++ b/msi.gama.headless/src/msi/gama/headless/batch/ModelLibraryTester.java @@ -126,7 +126,7 @@ public void test(final GamlModelBuilder builder, final int[] count, final int[] System.setOut(nullStream); final TestAgent agent = (TestAgent) exp.getAgent(); exp.setHeadless(true); - exp.getController().getScheduler().resume(); + // exp.getController().getScheduler().resume(); exp.getAgent().step(agent.getScope()); code[0] += agent.getSummary().countTestsWith(TestState.FAILED); code[0] += agent.getSummary().countTestsWith(TestState.ABORTED); diff --git a/msi.gama.headless/src/msi/gama/headless/core/Experiment.java b/msi.gama.headless/src/msi/gama/headless/core/Experiment.java index 9c098f478e..e921526d42 100644 --- a/msi.gama.headless/src/msi/gama/headless/core/Experiment.java +++ b/msi.gama.headless/src/msi/gama/headless/core/Experiment.java @@ -120,7 +120,7 @@ public long step() { // + BATCH SIMULATION ] // AD commented this // currentExperiment.getAgent().getSimulation().removeAgent(); - currentExperiment.getController().getScheduler().resume(); + // currentExperiment.getController().getScheduler().resume(); currentExperiment.getAgent().step(currentExperiment.getAgent().getScope()); } else { currentExperiment.getAgent().step(this.getScope()); @@ -132,7 +132,7 @@ public long step() { @Override public void setParameter(final String parameterName, final Object value) { - // if (this.params.containsKey(parameterName)) { this.params.remove(parameterName); } + // if (this.params.containsKey(parameterName)) { this.params.remove(parameterName); } this.params.put(parameterName, value); } diff --git a/ummisco.gama.ui.experiment/src/ummisco/gama/ui/controls/StatusControlContribution.java b/ummisco.gama.ui.experiment/src/ummisco/gama/ui/controls/StatusControlContribution.java index 036f037817..8077d9a4f7 100644 --- a/ummisco.gama.ui.experiment/src/ummisco/gama/ui/controls/StatusControlContribution.java +++ b/ummisco.gama.ui.experiment/src/ummisco/gama/ui/controls/StatusControlContribution.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * StatusControlContribution.java, in ummisco.gama.ui.experiment, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * StatusControlContribution.java, in ummisco.gama.ui.experiment, is part of the source code of the GAMA modeling and + * simulation platform (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package ummisco.gama.ui.controls; @@ -51,40 +51,40 @@ public class StatusControlContribution extends WorkbenchWindowControlContributio /** The is updating. */ volatile boolean isUpdating; - + /** The label. */ FlatButton label; - + /** The popup. */ private Popup2 popup; - + /** The state. */ int state; - + /** The main task name. */ volatile String mainTaskName; - + /** The sub task name. */ volatile String subTaskName; - + /** The in sub task. */ volatile boolean inSubTask = false; - + /** The in user status. */ volatile boolean inUserStatus = false; - + /** The sub task completion. */ volatile Double subTaskCompletion; - + /** The Constant WIDTH. */ private final static int WIDTH = 400; - + /** The color. */ private GamaUIColor color; - + /** The agent index. */ int agentIndex; // 0 for experiments, > 0 for simulation(s) - + /** The text. */ StringBuilder text = new StringBuilder(2000); @@ -96,9 +96,7 @@ public class StatusControlContribution extends WorkbenchWindowControlContributio * * @return single instance of StatusControlContribution */ - public static StatusControlContribution getInstance() { - return INSTANCE; - } + public static StatusControlContribution getInstance() { return INSTANCE; } /** * Instantiates a new status control contribution. @@ -110,7 +108,8 @@ public StatusControlContribution() { /** * Instantiates a new status control contribution. * - * @param id the id + * @param id + * the id */ public StatusControlContribution(final String id) { // NO_UCD (unused code) super(id); @@ -123,9 +122,7 @@ protected int computeWidth(final Control control) { } @Override - public boolean isBusy() { - return isUpdating; - } + public boolean isBusy() { return isUpdating; } @Override protected Control createControl(final Composite parent) { @@ -159,9 +156,7 @@ public void mouseDown(final MouseEvent e) { } @Override - public boolean isDisposed() { - return label.isDisposed(); - } + public boolean isDisposed() { return label.isDisposed(); } /** * Gets the status agent. @@ -213,9 +208,7 @@ public PopupText getPopupText() { } final IAgent[] simulations = pop.toArray(); - for (final IAgent a : simulations) { - appendPopupTextFor((SimulationAgent) a, result); - } + for (final IAgent a : simulations) { appendPopupTextFor((SimulationAgent) a, result); } return result; } @@ -223,14 +216,16 @@ public PopupText getPopupText() { /** * Append popup text for. * - * @param exp the exp - * @param result the result + * @param exp + * the exp + * @param result + * the result */ void appendPopupTextFor(final ITopLevelAgent exp, final PopupText result) { text.setLength(0); text.append(Strings.LN); final SimulationClock clock = exp.getClock(); - text.append(clock.getInfo()).append(Strings.LN); + clock.getInfo(text).append(Strings.LN); text.append("Durations: cycle ").append(clock.getDuration()).append("ms; average ") .append((int) clock.getAverageDuration()).append("ms; total ").append(clock.getTotalDuration()) .append("ms"); @@ -249,19 +244,13 @@ public GamaUIColor getPopupBackground() { } @Override - public Shell getControllingShell() { - return label.getShell(); - } + public Shell getControllingShell() { return label.getShell(); } @Override - public Point getAbsoluteOrigin() { - return label.toDisplay(new Point(label.getLocation().x, label.getSize().y)); - } + public Point getAbsoluteOrigin() { return label.toDisplay(new Point(label.getLocation().x, label.getSize().y)); } @Override - public int getPopupWidth() { - return label.getSize().x; - } + public int getPopupWidth() { return label.getSize().x; } /** * Method updateWith() @@ -343,32 +332,30 @@ public void updateWith(final IStatusMessage m) { /** * Gets the clock message. * - * @param agent the agent + * @param agent + * the agent * @return the clock message */ private String getClockMessage(final ITopLevelAgent agent) { if (agent == null) return ""; - final StringBuilder sb = new StringBuilder(200); - sb.append(agent.getClock().getInfo()); + // final StringBuilder text = new StringBuilder(200); + text.setLength(0); + agent.getClock().getInfo(text); final IExperimentAgent exp = agent.getExperiment(); final int nbThreads = exp.getSimulationPopulation().getNumberOfActiveThreads(); if (agent.getScope().isOnUserHold()) { - sb.append(" (waiting)"); - } else if (nbThreads > 1) { sb.append(" (" + nbThreads + " threads)"); } + text.append(" (waiting)"); + } else if (nbThreads > 1) { text.append(" (" + nbThreads + " threads)"); } final IExperimentPlan plan = exp.getSpecies(); - if (plan.shouldBeBenchmarked()) { sb.append(" [benchmarking]"); } - return sb.toString(); + if (plan.shouldBeBenchmarked()) { text.append(" [benchmarking]"); } + return text.toString(); } @Override - public int getCurrentState() { - return state; - } + public int getCurrentState() { return state; } @Override - public boolean isDynamic() { - return false; - } + public boolean isDynamic() { return false; } /** * Method resume() diff --git a/ummisco.gama.ui.modeling/src/msi/gama/lang/gaml/ui/utils/ModelRunner.java b/ummisco.gama.ui.modeling/src/msi/gama/lang/gaml/ui/utils/ModelRunner.java index 3788bdb3ad..dc76f9ae7f 100644 --- a/ummisco.gama.ui.modeling/src/msi/gama/lang/gaml/ui/utils/ModelRunner.java +++ b/ummisco.gama.ui.modeling/src/msi/gama/lang/gaml/ui/utils/ModelRunner.java @@ -112,7 +112,7 @@ public List runHeadlessTests(final Object object) { if (exp != null) { exp.setHeadless(true); final TestAgent agent = (TestAgent) exp.getAgent(); - exp.getController().getScheduler().resume(); + // exp.getController().getScheduler().resume(); agent.step(agent.getScope()); result.add(((WithTestSummary) agent).getSummary()); GAMA.closeExperiment(exp); diff --git a/ummisco.gama.ui.shared/src/ummisco/gama/ui/utils/SwtGui.java b/ummisco.gama.ui.shared/src/ummisco/gama/ui/utils/SwtGui.java index 3c164d6fbe..1ee94af168 100644 --- a/ummisco.gama.ui.shared/src/ummisco/gama/ui/utils/SwtGui.java +++ b/ummisco.gama.ui.shared/src/ummisco/gama/ui/utils/SwtGui.java @@ -435,55 +435,52 @@ public void setSelectedAgent(final IAgent a) { @Override public void prepareForExperiment(final IScope scope, final IExperimentPlan exp) { - if (exp.isGui()) { - // hideScreen(); - final IOpenGLInitializer initializer = WorkbenchHelper.getService(IOpenGLInitializer.class); - if (initializer != null && !initializer.isDone()) { initializer.run(); } - WorkbenchHelper.setWorkbenchWindowTitle(exp.getName() + " - " + exp.getModel().getFilePath()); - final ExperimentAgent agent = exp.getAgent(); - final ExperimentOutputManager manager = (ExperimentOutputManager) agent.getOutputManager(); - Symbol layout = manager.getLayout(); - if (layout == null) { layout = manager; } - final Boolean keepTabs = layout.getFacetValue(scope, "tabs", true); - final Boolean keepToolbars = layout.getFacetValue(scope, "toolbars", null); - final Boolean showParameters = layout.getFacetValue(scope, "parameters", null); - final Boolean showConsoles = layout.getFacetValue(scope, "consoles", null); - final Boolean showNavigator = layout.getFacetValue(scope, "navigator", null); - final Boolean showControls = layout.getFacetValue(scope, "controls", null); - final Boolean keepTray = layout.getFacetValue(scope, "tray", null); - boolean showEditors; - if (layout.hasFacet("editors")) { - showEditors = layout.getFacetValue(scope, "editors", false); + // hideScreen(); + final IOpenGLInitializer initializer = WorkbenchHelper.getService(IOpenGLInitializer.class); + if (initializer != null && !initializer.isDone()) { initializer.run(); } + WorkbenchHelper.setWorkbenchWindowTitle(exp.getName() + " - " + exp.getModel().getFilePath()); + final ExperimentAgent agent = exp.getAgent(); + final ExperimentOutputManager manager = (ExperimentOutputManager) agent.getOutputManager(); + Symbol layout = manager.getLayout(); + if (layout == null) { layout = manager; } + final Boolean keepTabs = layout.getFacetValue(scope, "tabs", true); + final Boolean keepToolbars = layout.getFacetValue(scope, "toolbars", null); + final Boolean showParameters = layout.getFacetValue(scope, "parameters", null); + final Boolean showConsoles = layout.getFacetValue(scope, "consoles", null); + final Boolean showNavigator = layout.getFacetValue(scope, "navigator", null); + final Boolean showControls = layout.getFacetValue(scope, "controls", null); + final Boolean keepTray = layout.getFacetValue(scope, "tray", null); + boolean showEditors; + if (layout.hasFacet("editors")) { + showEditors = layout.getFacetValue(scope, "editors", false); + } else { + showEditors = !GamaPreferences.Modeling.EDITOR_PERSPECTIVE_HIDE.getValue(); + } + WorkbenchHelper.runInUI("Arranging views", 0, m -> { + WorkbenchHelper.getPage().setEditorAreaVisible(showEditors); + if (showConsoles != null && !showConsoles) { + hideView(IGui.CONSOLE_VIEW_ID); + hideView(IGui.INTERACTIVE_CONSOLE_VIEW_ID); } else { - showEditors = !GamaPreferences.Modeling.EDITOR_PERSPECTIVE_HIDE.getValue(); + getConsole().showConsoleView(exp.getAgent()); } - WorkbenchHelper.runInUI("Arranging views", 0, m -> { - WorkbenchHelper.getPage().setEditorAreaVisible(showEditors); - if (showConsoles != null && !showConsoles) { - hideView(IGui.CONSOLE_VIEW_ID); - hideView(IGui.INTERACTIVE_CONSOLE_VIEW_ID); - } else { - getConsole().showConsoleView(exp.getAgent()); - } - if (showParameters != null && !showParameters) { - hideView(IGui.PARAMETER_VIEW_ID); - } else { - updateParameterView(scope, exp); - } - if (showNavigator != null && !showNavigator) { hideView(IGui.NAVIGATOR_VIEW_ID); } - if (showControls != null) { WorkbenchHelper.getWindow().setCoolBarVisible(showControls); } - if (keepTray != null) { PerspectiveHelper.showBottomTray(WorkbenchHelper.getWindow(), keepTray); } - - final SimulationPerspectiveDescriptor sd = PerspectiveHelper.getActiveSimulationPerspective(); - if (sd != null) { - sd.keepTabs(keepTabs); - sd.keepToolbars(keepToolbars); - sd.keepControls(showControls); - sd.keepTray(keepTray); - } - }); - - } + if (showParameters != null && !showParameters) { + hideView(IGui.PARAMETER_VIEW_ID); + } else { + updateParameterView(scope, exp); + } + if (showNavigator != null && !showNavigator) { hideView(IGui.NAVIGATOR_VIEW_ID); } + if (showControls != null) { WorkbenchHelper.getWindow().setCoolBarVisible(showControls); } + if (keepTray != null) { PerspectiveHelper.showBottomTray(WorkbenchHelper.getWindow(), keepTray); } + + final SimulationPerspectiveDescriptor sd = PerspectiveHelper.getActiveSimulationPerspective(); + if (sd != null) { + sd.keepTabs(keepTabs); + sd.keepToolbars(keepToolbars); + sd.keepControls(showControls); + sd.keepTray(keepTray); + } + }); } @@ -571,7 +568,7 @@ public void closeSimulationViews(final IScope scope, final boolean openModelingP PerspectiveHelper.openModelingPerspective(immediately, false); } - getStatus(scope).neutralStatus("No simulation running"); + getStatus().neutralStatus("No simulation running"); }); } @@ -580,7 +577,7 @@ public void closeSimulationViews(final IScope scope, final boolean openModelingP public String getExperimentState(final String uid) { final IExperimentController controller = GAMA.getFrontmostController(); if (controller == null) return NONE; - if (controller.getScheduler().paused()) return PAUSED; + if (controller.isPaused()) return PAUSED; return RUNNING; } @@ -614,9 +611,7 @@ public void updateDecorator(final String id) { } @Override - public IStatusDisplayer getStatus(final IScope scope) { - return WorkbenchHelper.getService(IStatusDisplayer.class); - } + public IStatusDisplayer getStatus() { return WorkbenchHelper.getService(IStatusDisplayer.class); } @Override public IConsoleDisplayer getConsole() { return WorkbenchHelper.getService(IConsoleDisplayer.class); }