Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions bindings/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,14 @@ ff["dumpMode"] = "kml"
ff.execute("print[circle.kml]")
```

A command that is unknown or fails only prints an error by default. Pass
`check=True` to raise `RuntimeError` instead. A command scheduled with `@t=`
is checked when it is scheduled, not when it runs.

```python
ff.execute("step[dt=1h]", check=True) # raises RuntimeError
```

### More advanced examples

For examples that use real-world data (fuel, topography, wind), see the scripts
Expand Down
10 changes: 7 additions & 3 deletions bindings/python/src/pyforefire/_pyforefire.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,14 @@ py::object PLibForeFire::getDataMatrixPy(char *name) {
return py::array_t<double>({rows, cols}, flat_data.data());
}

string PLibForeFire::execute(char *command)
string PLibForeFire::execute(char *command, bool check)
{
ostringstream stringOut;
Command::OutputCapture capture(&stringOut);
string smsg(command);
pyxecutor->ExecuteCommand(smsg);
int status = pyxecutor->ExecuteCommand(smsg);
if (check && status != Command::normal)
throw std::runtime_error("ForeFire command failed: " + smsg + "\n" + stringOut.str());
return stringOut.str();
}

Expand Down Expand Up @@ -278,7 +280,9 @@ PYBIND11_MODULE(_pyforefire, m) {
.def("getDouble", &PLibForeFire::getDouble)
.def("setString", &PLibForeFire::setString)
.def("getString", &PLibForeFire::getString)
.def("execute", &PLibForeFire::execute)
.def("execute", &PLibForeFire::execute, py::arg("command"), py::arg("check") = false,
"Run one ForeFire command and return its output. With check=True, "
"raise RuntimeError when the command is unknown or fails.")
.def("addScalarLayer", [](PLibForeFire& self, char *type, char *name, double x0 , double y0, double t0, double width , double height, double timespan, py::array_t<double> values) {
size_t nn[] = {1, 1, 1, 1};
const long* shape = values.shape();
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/src/pyforefire/_pyforefire.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class PLibForeFire {

public:
PLibForeFire();
std::string execute(char *);
std::string execute(char *, bool check = false);
void createDomain( int id
, int year, int month
, int day, double t
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/src/pyforefire/_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,12 @@ def _attach(self, conn, process):
self._process = process
self._lock = threading.Lock()

def _call(self, name, *args, fd=None):
def _call(self, name, *args, fd=None, kwargs=None):
with self._lock:
if self._conn is None:
raise WorkerDied("the runner is closed")
try:
self._conn.send((name, args))
self._conn.send((name, args, kwargs or {}))
if fd is not None:
send_handle(self._conn, fd, self._process.pid)
ok, value = self._conn.recv()
Expand All @@ -132,7 +132,7 @@ def _call(self, name, *args, fd=None):
def __getattr__(self, name):
if name.startswith("_"):
raise AttributeError(name)
return lambda *args: self._call(name, *args)
return lambda *args, **kwargs: self._call(name, *args, kwargs=kwargs)

def __getitem__(self, key):
return self._call("__getitem__", key)
Expand Down
4 changes: 2 additions & 2 deletions bindings/python/src/pyforefire/_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def _serve(conn):
return
if request is None:
return
name, args = request
name, args, kwargs = request
try:
if name == "__fork__":
copy = _fork(conn)
Expand All @@ -54,7 +54,7 @@ def _serve(conn):
continue
reply = (True, None)
else:
reply = (True, getattr(ff, name)(*args))
reply = (True, getattr(ff, name)(*args, **kwargs))
except Exception as e:
reply = (False, e)
try:
Expand Down
70 changes: 42 additions & 28 deletions src/Command.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,7 @@ namespace libforefire

// Optionally, set or use 'dom' as needed.
cout << "Domain string created: " << domCommand << endl;
ExecuteCommand(domCommand);
return normal;
return ExecuteCommand(domCommand);
} else {
cout << "Error: Unable to create domain string due to insufficient data." << endl;
}
Expand Down Expand Up @@ -982,7 +981,7 @@ namespace libforefire
int Command::stepSimulation(const string &arg, size_t &numTabs)
{
if (getDomain() == 0)
return normal;
return error;

double dt = getFloat("dt", arg);
if (dt == FLOATERROR || hasNonSecondUnit(getString("dt", arg)))
Expand All @@ -994,9 +993,7 @@ namespace libforefire
ostringstream etime;
etime.precision(numeric_limits<double>::digits10);
etime << "t=" << endTime;
goTo(etime.str().c_str(), numTabs);

return normal;
return goTo(etime.str().c_str(), numTabs);
}

int Command::goTo(const string &arg, size_t &numTabs)
Expand Down Expand Up @@ -1174,7 +1171,7 @@ namespace libforefire
int Command::printSimulation(const string &arg, size_t &/*numTabs*/)
{
if (getDomain() == 0)
return normal;
return error;

SimulationParameters *simParam = SimulationParameters::GetInstance();
string finalStr = "";
Expand Down Expand Up @@ -1338,7 +1335,7 @@ namespace libforefire
int Command::plotSimulation(const std::string &arg, size_t &/*numTabs*/)
{
if (getDomain() == nullptr)
return normal;
return error;

SimulationParameters *simParam = SimulationParameters::GetInstance();

Expand Down Expand Up @@ -1855,7 +1852,7 @@ namespace libforefire
int Command::addLayer(const std::string &arg, size_t &/*numTabs*/)
{
if (getDomain() == nullptr)
return normal;
return error;

if (arg.empty())
{
Expand Down Expand Up @@ -2006,11 +2003,13 @@ namespace libforefire
vector<string> tmpArgs;
string delimiter = ";";
tokenize(arg, tmpArgs, delimiter);
int status = normal;
for (size_t i = 0, size = tmpArgs.size(); i < size; ++i)
{
setParameter(tmpArgs[i], numTabs);
if (setParameter(tmpArgs[i], numTabs) != normal)
status = error;
}
return normal;
return status;
}

int Command::computeModelSpeed(const std::string &cmd, size_t &/*numTabs*/)
Expand Down Expand Up @@ -2477,14 +2476,15 @@ namespace libforefire
return normal;
}

void Command::executeLoop(ifstream* inputStream)
int Command::executeLoop(ifstream* inputStream)
{
// Support multiline commands whose arguments are wrapped in triple quotes (""").
// A block begins the first time we meet an *unmatched* \"\"\" and is closed by
// the corresponding second occurrence.
std::string line;
std::string bufferedCmd;
bool inTripleQuote = false;
int status = normal;

while (std::getline(*inputStream, line))
{
Expand Down Expand Up @@ -2516,14 +2516,16 @@ namespace libforefire
{
// Opening and closing on the same line → execute immediately
inTripleQuote = false;
ExecuteCommand(bufferedCmd);
if (ExecuteCommand(bufferedCmd) != normal)
status = error;
bufferedCmd.clear();
}
}
else
{
// Regular single‑line command
ExecuteCommand(line);
if (ExecuteCommand(line) != normal)
status = error;
}
}
else
Expand All @@ -2536,11 +2538,13 @@ namespace libforefire
{
// Closing delimiter reached → execute the whole buffered command
inTripleQuote = false;
ExecuteCommand(bufferedCmd);
if (ExecuteCommand(bufferedCmd) != normal)
status = error;
bufferedCmd.clear();
}
}
}
return status;
}

int Command::include(const string &arg, size_t &/*numTabs*/)
Expand All @@ -2551,14 +2555,12 @@ namespace libforefire
if (instream)
{
// If the file is successfully opened, execute the command loop
executeLoop(&instream);
int status = executeLoop(&instream);
instream.close();
return status;
}
else
{
cout << "wrong input file, check your settings..." << endl;
}
return normal;
cout << "wrong input file, check your settings..." << endl;
return error;
}

#ifdef FF_NO_NETCDF
Expand Down Expand Up @@ -3089,7 +3091,8 @@ namespace libforefire
com += oss.str();
}

ExecuteCommand(com);
if (ExecuteCommand(com) != normal)
return error;
#endif /* FF_NO_NETCDF */
}
if (args.size() == 1)
Expand Down Expand Up @@ -3412,7 +3415,7 @@ namespace libforefire
return arg;
}

void Command::ExecuteCommand(string &line)
int Command::ExecuteCommand(string &line)
{
/* The method 'ExecuteCommands' uses the 'tokenize' class
* to execute the command given by the user
Expand All @@ -3423,7 +3426,8 @@ namespace libforefire
// Getting all the arguments, using the 'tokenize' function

if (line.size() == 0)
return;
return normal;
int status = normal;
vector<string> command;
size_t numTabs;
string scmd;
Expand Down Expand Up @@ -3465,7 +3469,7 @@ namespace libforefire
}

// calling the right method using the 'translator'
if (((scmd)[0] == '#') || ((scmd)[0] == '*') || ((scmd)[0] == '\n') || ((scmd)[0] == '\r'))
if ((scmd.empty() && command.size() == 1) || ((scmd)[0] == '#') || ((scmd)[0] == '*') || ((scmd)[0] == '\n') || ((scmd)[0] == '\r'))
{
// this line is commented, nothing to do
}
Expand All @@ -3477,7 +3481,7 @@ namespace libforefire
if (!domainExists(scmd + " scheduled with @"))
{
command.clear();
return;
return error;
}
string atCommand = line.substr(0, line.rfind("]") + 1);
string whenCommand = line.substr(line.rfind("]") + 1, -1);
Expand All @@ -3495,15 +3499,19 @@ namespace libforefire
else
{
cout << whenDouble << "unknown post operator >" << whenCommand << "< , press 'Tab' for command list." << endl;
status = error;
}
}
else
{
commandMap::const_iterator curcmd = translator.find(scmd);
if (curcmd == translator.end())
{
if (scmd.at(0) != '!')
if (scmd[0] != '!')
{
cout << "unknown command >" << scmd << "< , press 'Tab' for command list." << endl;
status = error;
}
}
else
{
Expand All @@ -3514,36 +3522,42 @@ namespace libforefire
{
// calling the right function
// cout << "executing command '" << scmd << "' with argument(s) '" << command[1] << "'" << endl;
(curcmd->second)(command[1], numTabs);
if ((curcmd->second)(command[1], numTabs) != normal)
status = error;
}
catch (BadOption &)
{
cout << where()
<< "argument(s) '" << command[1] << "' is (are) not fit for command '"
<< command[0] << "'" << endl;
cout << "type 'man[" << command[0] << "]' for more information" << endl;
status = error;
}
catch (MissingOption &mo)
{
cout << where()
<< "command '" << command[0] << "' misses "
<< mo.num << " options." << endl;
cout << "type 'man[" << command[0] << "]' for more information" << endl;
status = error;
}
catch (MissingTime &)
{
cout << where()
<< "you have to specify a time for that command (as in 't=0.')" << endl;
status = error;
}
catch (...)
{
cout << where()
<< " PROBLEM: Command associated to " << line << " ended in error" << endl;
status = error;
}
}
}
}
command.clear();
return status;
}

std::string Command::executeCommandAndCaptureOutput(const std::string &cmd)
Expand Down
15 changes: 8 additions & 7 deletions src/Command.h
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,6 @@ class Command {
static double startTime;
static double endTime;

enum Status {
normal = 0, error = 1
};

static bool firstCommand;
/*! \brief set by quit(), read by quitRequested() */
static bool quitAsked;
Expand Down Expand Up @@ -330,9 +326,14 @@ class Command {
OutputCapture& operator=(const OutputCapture&) = delete;
};

/*! \brief execute the desired command */
static void ExecuteCommand(string&);
static void executeLoop(ifstream* inputStream);
enum Status {
normal = 0, error = 1
};

/*! \brief execute the desired command
* \return normal, or error when the command is unknown or fails */
static int ExecuteCommand(string&);
static int executeLoop(ifstream* inputStream);

/*! \brief complete the last front */
static void completeFront(FireFront*);
Expand Down
6 changes: 6 additions & 0 deletions tests/python/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,12 @@ def test_errors_are_raised_here():
failures.append("reading a missing parameter did not raise")
except RuntimeError:
pass
runner.execute("step[dt=1h]")
try:
runner.execute("step[dt=1h]", check=True)
failures.append("a failed command with check=True did not raise")
except RuntimeError:
pass
runner["perimeterResolution"] = 3.0
if runner["perimeterResolution"] != 3.0:
failures.append("the worker stopped answering after an error")
Expand Down
Loading