Skip to content

Commit

Permalink
fixed thread run (#1227)
Browse files Browse the repository at this point in the history
* fixed thread run

* update models
  • Loading branch information
EvenSol authored Jan 1, 2025
1 parent 37b29b4 commit b3c48b6
Show file tree
Hide file tree
Showing 5 changed files with 206 additions and 119 deletions.
2 changes: 1 addition & 1 deletion src/main/java/log4j2.properties
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
#appender.console.filter.threshold.level = DEBUG

# Root Logger
rootLogger.level = OFF
rootLogger.level = DEBUG
rootLogger.appenderRef.stdout.ref = STDOUT
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ && getOutletPressure() == getOutletStream().getPressure()) {
* @param percentValveOpening Percentage valve opening (0 to 100).
* @return Adjusted flow coefficient (Cv) in US gallons per minute (USG/min).
*/
private static double adjustCv(double Cv, double percentValveOpening) {
private double adjustCv(double Cv, double percentValveOpening) {
return Cv * (percentValveOpening / 100);
}

Expand All @@ -176,7 +176,7 @@ private static double adjustCv(double Cv, double percentValveOpening) {
* @param percentValveOpening Percentage valve opening (0 to 100).
* @return Mass flow rate in kilograms per hour (kg/h).
*/
public static double liquidValveMassFlow(double P1, double P2, double rho, double Cv, double Fp,
public double liquidValveMassFlow(double P1, double P2, double rho, double Cv, double Fp,
double percentValveOpening) {
// Equation unit conversion constant
final double N1 = 0.0865;
Expand Down Expand Up @@ -211,8 +211,8 @@ public static double liquidValveMassFlow(double P1, double P2, double rho, doubl
* @param Fp The piping geometry factor (dimensionless).
* @return The percent valve opening.
*/
public static double calcPercentValveOpeningLiquid(double massFlowRate, double P1, double P2,
double rho, double Cv, double Fp) {
public double calcPercentValveOpeningLiquid(double massFlowRate, double P1, double P2, double rho,
double Cv, double Fp) {
// Equation unit conversion constant
final double N1 = 0.0865;

Expand Down Expand Up @@ -244,7 +244,7 @@ public static double calcPercentValveOpeningLiquid(double massFlowRate, double P
* @param percentValveOpening Percentage valve opening (0 to 100).
* @return Downstream pressure in bar.
*/
public static double liquidValvePout(double P1, double m, double rho, double Cv, double Fp,
public double liquidValvePout(double P1, double m, double rho, double Cv, double Fp,
double percentValveOpening) {
// Equation unit conversion constant
final double N1 = 0.0865;
Expand Down Expand Up @@ -281,7 +281,7 @@ public static double liquidValvePout(double P1, double m, double rho, double Cv,
* @param percentValveOpening Percentage valve opening (0 to 100).
* @return Flow coefficient (Cv) in US gallons per minute (USG/min).
*/
public static double liquidValveCv(double P1, double P2, double rho, double m, double Fp,
public double liquidValveCv(double P1, double P2, double rho, double m, double Fp,
double percentValveOpening) {
// Equation unit conversion constant
final double N1 = 0.0865;
Expand Down
89 changes: 50 additions & 39 deletions src/main/java/neqsim/process/processmodel/ProcessModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,41 +12,32 @@
*
* Manages a collection of processes that can be run in steps or continuously.
*
* @author Even Solbraa
* @version $Id: $Id
*
*/
public class ProcessModel implements Runnable {

static Logger logger = LogManager.getLogger(ProcessModel.class);
private Map<String, ProcessSystem> processes = new LinkedHashMap<>();

private boolean runStep = false;
private int maxIterations = 50;
private int iterations = 0;

/**
* Checks if the model is running in step mode.
*
* @return true if running in step mode, false otherwise.
*/
public boolean isRunStep() {
return runStep;
}

/**
* Sets the step mode for the process.
*
* @param runStep true to enable step mode, false to disable.
*/
public void setRunStep(boolean runStep) {
this.runStep = runStep;
}

/**
* Adds a process to the model.
*
* @param name the name of the process.
* @param process the process to add.
* @return true if the process was added successfully.
*/
public boolean add(String name, ProcessSystem process) {
if (name == null || name.isEmpty()) {
Expand All @@ -65,55 +56,72 @@ public boolean add(String name, ProcessSystem process) {

/**
* Retrieves a process by its name.
*
* @param name the name of the process.
* @return the corresponding process, or null if not found.
*/
public ProcessSystem get(String name) {
return processes.get(name);
}

/**
* Removes a process by its name.
*
* @param name the name of the process to remove.
* @return true if the process was removed, false otherwise.
*/
public boolean remove(String name) {
return processes.remove(name) != null;
}

/**
* Executes all processes, either continuously or in steps based on mode.
* The core run method.
*
* - If runStep == true, each process is run in "step" mode exactly once. - Otherwise (continuous
* mode), it loops up to maxIterations or until all processes are finished (isFinished() == true).
*/
@Override
public void run() {
for (ProcessSystem process : processes.values()) {
try {
if (runStep) {
if (runStep) {
// Step mode: just run each process once in step mode
for (ProcessSystem process : processes.values()) {
try {
if (Thread.currentThread().isInterrupted()) {
logger.debug("Thread was interrupted, exiting run()...");
return;
}
process.run_step();
} else {
process.run();
} catch (Exception e) {
System.err.println("Error running process step: " + e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("Error running process: " + e.getMessage());
e.printStackTrace();
}
}
if (!runStep) {
if (!isFinished() && iterations < maxIterations) {
iterations += 1;
run();
} else {
iterations = 0;
} else {
int iterations = 0;
while (!Thread.currentThread().isInterrupted() && !isFinished()
&& iterations < maxIterations) {
for (ProcessSystem process : processes.values()) {
if (Thread.currentThread().isInterrupted()) {
logger.debug("Thread was interrupted, exiting run()...");
return;
}
try {
process.run(); // the process's continuous run
} catch (Exception e) {
System.err.println("Error running process: " + e.getMessage());
e.printStackTrace();
}
}
iterations++;
}
}
}

/**
* Starts this model in a new thread and returns that thread.
*/
public Thread runAsThread() {
Thread processThread = new Thread(this);
processThread.start();
return processThread;
}

/**
* Checks if all processes are finished.
*
* @return true if all processes are solved, false otherwise.
*/
public boolean isFinished() {
for (ProcessSystem process : processes.values()) {
Expand All @@ -125,11 +133,15 @@ public boolean isFinished() {
}

/**
* Executes all processes in a single step.
* Runs all processes in a single step (used outside of the thread model).
*/
public void runStep() {
for (ProcessSystem process : processes.values()) {
try {
if (Thread.currentThread().isInterrupted()) {
logger.debug("Thread was interrupted, exiting run()...");
return;
}
process.run_step();
} catch (Exception e) {
System.err.println("Error in runStep: " + e.getMessage());
Expand All @@ -139,20 +151,19 @@ public void runStep() {
}

/**
* Runs the model as a separate thread.
* (Optional) Creates separate threads for each process (if you need them).
*/
public Map<String, Thread> getThreads() {
Map<String, Thread> threads = new LinkedHashMap<>();
try {
for (ProcessSystem process : processes.values()) {
Thread thread = new Thread(process);
thread.setName(process.getName() + " thread");
threads.put(process.getName(), thread);
}

} catch (Exception ex) {
logger.debug(ex.getMessage(), ex);
}
return threads;
}

}
16 changes: 13 additions & 3 deletions src/main/java/neqsim/process/processmodel/ProcessSystem.java
Original file line number Diff line number Diff line change
Expand Up @@ -425,14 +425,20 @@ public void run(UUID id) {
iter++;
isConverged = true;
for (int i = 0; i < unitOperations.size(); i++) {
if (Thread.currentThread().isInterrupted()) {
logger.debug("Process simulation was interrupted, exiting run()..." + getName());
break;
}
if (!unitOperations.get(i).getClass().getSimpleName().equals("Recycle")) {
try {
if (iter == 1 || unitOperations.get(i).needRecalculation()) {
unitOperations.get(i).run(id);
}
} catch (Exception ex) {
// String error = ex.getMessage();
logger.error(ex.getMessage(), ex);
logger.error("error running unit uperation " + unitOperations.get(i).getName() + " "
+ ex.getMessage(), ex);
ex.printStackTrace();
}
}
if (unitOperations.get(i).getClass().getSimpleName().equals("Recycle")
Expand Down Expand Up @@ -476,7 +482,8 @@ public void run(UUID id) {
* signalDB[timeStepNumber][3 * i + 3] = ((MeasurementDeviceInterface)
* measurementDevices.get(i)) .getUnit(); }
*/
} while (((!isConverged || (iter < 2 && hasRecycle)) && iter < 100) && !runStep);
} while (((!isConverged || (iter < 2 && hasRecycle)) && iter < 100) && !runStep
&& !Thread.currentThread().isInterrupted());

for (int i = 0; i < unitOperations.size(); i++) {
unitOperations.get(i).setCalculationIdentifier(id);
Expand All @@ -490,7 +497,10 @@ public void run(UUID id) {
public void run_step(UUID id) {
for (int i = 0; i < unitOperations.size(); i++) {
try {
// if (unitOperations.get(i).needRecalculation()) {
if (Thread.currentThread().isInterrupted()) {
logger.debug("Process simulation was interrupted, exiting run()..." + getName());
break;
}
unitOperations.get(i).run(id);
// }
} catch (Exception ex) {
Expand Down
Loading

0 comments on commit b3c48b6

Please sign in to comment.