Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
python: reorg to allow 'from simgrid import *' in scripts
authorMartin Quinson <martin.quinson@ens-rennes.fr>
Mon, 31 Dec 2018 14:59:55 +0000 (15:59 +0100)
committerMartin Quinson <martin.quinson@ens-rennes.fr>
Mon, 31 Dec 2018 17:38:29 +0000 (18:38 +0100)
examples/python/actor-create/actor-create.py
examples/python/actor-yield/actor-yield.py
examples/python/exec-basic/exec-basic.py
src/bindings/python/simgrid_python.cpp

index 20a4daf..0edff20 100644 (file)
 # application and the settings to test it. This is a better scientific methodology. Actually, starting an actor with
 # Actor.create() is mostly useful to start an actor from another actor.
 
-import simgrid, sys
+import sys
+from simgrid import *
 
 # Our first class of actors is simply implemented with a function, that takes a single string as parameter.
 #
 # Later, this actor class is instantiated within the simulation.
 def receiver(mailbox_name):
-  mailbox = simgrid.Mailbox.by_name(mailbox_name)
+  mailbox = Mailbox.by_name(mailbox_name)
 
-  simgrid.info("Hello s4u, I'm ready to get any message you'd want on {:s}".format(mailbox.get_name()))
+  this_actor.info("Hello s4u, I'm ready to get any message you'd want on {:s}".format(mailbox.get_name()))
 
   msg1 = mailbox.get()
   msg2 = mailbox.get()
   msg3 = mailbox.get()
-  simgrid.info("I received '{:s}', '{:s}' and '{:s}'".format(msg1, msg2, msg3))
-  simgrid.info("I'm done. See you.")
+  this_actor.info("I received '{:s}', '{:s}' and '{:s}'".format(msg1, msg2, msg3))
+  this_actor.info("I'm done. See you.")
 
 # Our second class of actors is also a function
 def forwarder(*args):
   if len(args) < 2: raise AssertionError("Actor forwarder requires 2 parameters, but got only {:d}".format(len(args)))
-  mb_in  = simgrid.Mailbox.by_name(args[0])
-  mb_out = simgrid.Mailbox.by_name(args[1])
+  mb_in  = Mailbox.by_name(args[0])
+  mb_out = Mailbox.by_name(args[1])
 
   msg = mb_in.get()
-  simgrid.info("Forward '{:s}'.".format(msg))
+  this_actor.info("Forward '{:s}'.".format(msg))
   mb_out.put(msg, len(msg))
 
 # Declares a third class of actors which sends a message to the mailbox 'mb42'.
@@ -55,16 +56,16 @@ class Sender:
       if len(args) > 2: raise AssertionError("Actor sender requires 2 parameters, but got only {:d}".format(len(args)))
 
   def __call__(self):
-      simgrid.info("Hello s4u, I have something to send")
-      mailbox = simgrid.Mailbox.by_name(self.mbox)
+      this_actor.info("Hello s4u, I have something to send")
+      mailbox = Mailbox.by_name(self.mbox)
 
       mailbox.put(self.msg, len(self.msg))
-      simgrid.info("I'm done. See you.")
+      this_actor.info("I'm done. See you.")
 
 # Here comes the main function of your program
 if __name__ == '__main__':
   # When your program starts, you have to first start a new simulation engine, as follows
-  e = simgrid.Engine(sys.argv)
+  e = Engine(sys.argv)
 
   # Then you should load a platform file, describing your simulated platform
   e.load_platform("../../platforms/small_platform.xml");
@@ -74,15 +75,15 @@ if __name__ == '__main__':
   # The easiest way to do so is to implement the behavior of your actor in a single function,
   # as we do here for the receiver actors. This function can take any kind of parameters, as
   # long as the last parameters of Actor::create() match what your function expects.
-  simgrid.Actor.create("receiver", simgrid.Host.by_name("Fafard"), receiver, "mb42")
+  Actor.create("receiver", Host.by_name("Fafard"), receiver, "mb42")
 
   # If your actor is getting more complex, you probably want to implement it as a class instead,
   # as we do here for the sender actors. The main behavior goes into operator()() of the class.
   #
   # You can then directly start your actor, as follows:
-  simgrid.Actor.create("sender1", simgrid.Host.by_name("Tremblay"), Sender())
+  Actor.create("sender1", Host.by_name("Tremblay"), Sender())
   # If you want to pass parameters to your class, that's very easy: just use your constructors
-  simgrid.Actor.create("sender2", simgrid.Host.by_name("Jupiter"), Sender("GloubiBoulga"));
+  Actor.create("sender2", Host.by_name("Jupiter"), Sender("GloubiBoulga"));
 
   # But starting actors directly is considered as a bad experimental habit, since it ties the code
   # you want to test with the experimental scenario. Starting your actors from an external deployment
index 894a4ff..64fd3eb 100644 (file)
@@ -3,7 +3,8 @@
 # This program is free software; you can redistribute it and/or modify it
 # under the terms of the license (GNU LGPL) which comes with this package.
 
-import simgrid, sys
+import sys
+from simgrid import *
 
 # This example does not much: It just spans over-polite actor that yield a large amount
 # of time before ending.
@@ -20,11 +21,11 @@ class Yielder:
         self.number_of_yields = int(args[0])
     def __call__(self):
         for i in range(self.number_of_yields):
-            simgrid.yield_()
-        simgrid.info("I yielded {:d} times. Goodbye now!".format(self.number_of_yields))
+            this_actor.yield_()
+        this_actor.info("I yielded {:d} times. Goodbye now!".format(self.number_of_yields))
 
 if __name__ == '__main__':
-    e = simgrid.Engine(sys.argv)
+    e = Engine(sys.argv)
 
     e.load_platform(sys.argv[1])             # Load the platform description
     e.register_actor("yielder", Yielder)  # Register the class representing the actors
index 09d9dd6..7ab3769 100644 (file)
@@ -4,13 +4,13 @@
 # under the terms of the license (GNU LGPL) which comes with this package.
 
 import sys
-import simgrid as sg
+from simgrid import *
 
 def executor():
     # execute() tells SimGrid to pause the calling actor until
     # its host has computed the amount of flops passed as a parameter
-    sg.execute(98095)
-    sg.info("Done.")
+    this_actor.execute(98095)
+    this_actor.info("Done.")
     # This simple example does not do anything beyond that
 
 def privileged():
@@ -21,8 +21,8 @@ def privileged():
     #
     # So instead of a half/half sharing between the two executions,
     # we get a 1/3 vs 2/3 sharing.
-    sg.execute(98095, 2);
-    sg.info("Done.");
+    this_actor.execute(98095, 2);
+    this_actor.info("Done.");
 
     # Note that the timings printed when executing this example are a bit misleading,
     # because the uneven sharing only last until the privileged actor ends.
@@ -32,10 +32,10 @@ def privileged():
 i = 0
 if "--" in sys.argv:
     i = sys.argv.index("--")
-e = sg.Engine(sys.argv[0:i])
+e = Engine(sys.argv[0:i])
 e.load_platform(sys.argv[i+1])
 
-sg.Actor.create("executor", sg.Host.by_name("Tremblay"), executor)
-sg.Actor.create("privileged", sg.Host.by_name("Tremblay"), privileged)
+Actor.create("executor", Host.by_name("Tremblay"), executor)
+Actor.create("privileged", Host.by_name("Tremblay"), privileged)
 
 e.run()
\ No newline at end of file
index e30747d..7c33438 100644 (file)
@@ -54,14 +54,17 @@ PYBIND11_MODULE(simgrid, m)
 
   m.attr("simgrid_version") = simgrid_version;
 
-  m.def("info", [](char* s) { XBT_INFO("%s", s); }, "Display a logging message of default priority.");
-
   /* this_actor namespace */
-  m.def("execute", py::overload_cast<double>(&simgrid::s4u::this_actor::execute),
-        "Block the current actor, computing the given amount of flops, see :cpp:func:`void simgrid::s4u::this_actor::execute(double)`");
-  m.def("execute", py::overload_cast<double, double>(&simgrid::s4u::this_actor::execute),
-        "Block the current actor, computing the given amount of flops at the given priority, see :cpp:func:`void simgrid::s4u::this_actor::execute(double, double)`");
-  m.def("yield_", &simgrid::s4u::this_actor::yield, "Yield the actor, see :cpp:func:`void simgrid::s4u::this_actor::yield()`");
+  py::module m2 = m.def_submodule("this_actor", "Bindings of the s4u::this_actor namespace.");
+  m2.def("info", [](char* s) { XBT_INFO("%s", s); }, "Display a logging message of default priority.");
+  m2.def("execute", py::overload_cast<double>(&simgrid::s4u::this_actor::execute),
+         "Block the current actor, computing the given amount of flops, see :cpp:func:`void "
+         "simgrid::s4u::this_actor::execute(double)`");
+  m2.def("execute", py::overload_cast<double, double>(&simgrid::s4u::this_actor::execute),
+         "Block the current actor, computing the given amount of flops at the given priority, see :cpp:func:`void "
+         "simgrid::s4u::this_actor::execute(double, double)`");
+  m2.def("yield_", &simgrid::s4u::this_actor::yield,
+         "Yield the actor, see :cpp:func:`void simgrid::s4u::this_actor::yield()`");
 
   /* Class Engine */
   py::class_<Engine>(m, "Engine", "Simulation Engine, see :ref:`class s4u::Engine <API_s4u_Engine>`")
@@ -122,30 +125,24 @@ PYBIND11_MODULE(simgrid, m)
       }, "Blocking data reception, see :cpp:func:`void* simgrid::s4u::Mailbox::get()`");
 
   /* Class Actor */
-  py::class_<simgrid::s4u::Actor, ActorPtr>(m, "Actor", ""
-      "An actor is an independent stream of execution in your distributed application, see :ref:`class s4u::Actor <API_s4u_Actor>`")
-
-    .def("create", [](py::args args, py::kwargs kwargs) {
-        xbt_assert(args.size()>2, "Creating an actor takes at least 3 parameters: name, host, and main function.");
-        return simgrid::s4u::Actor::create(args[0].cast<std::string>(), args[1].cast<Host*>(), [args]() {
-          py::tuple funargs(args.size()-3);
-          for (size_t i=3; i<args.size(); i++)
-            funargs[i-3] = args[i];
-
-          PyObject *result = PyObject_CallObject(args[2].ptr(), funargs.ptr());
-          if (!result)
-              throw pybind11::error_already_set();
-        });
-    }, "Create an actor from a function or an object, see :cpp:func:`simgrid::s4u::Actor::create()`")
-    /*
-    .def("create", [](std::string name, Host* host, py::object obj) -> ActorPtr {
-        xbt_assert(pybind11::hasattr(obj, "__call__"), "Your object does not implement the __call__() method");
-
-        return simgrid::s4u::Actor::create(name, host, [obj](){
-          obj.attr("__call__")();
-        });
-    }, "Create an actor from a python object")
-    */;
-
-
+  py::class_<simgrid::s4u::Actor, ActorPtr>(m, "Actor",
+                                            ""
+                                            "An actor is an independent stream of execution in your distributed "
+                                            "application, see :ref:`class s4u::Actor <API_s4u_Actor>`")
+
+      .def("create",
+           [](py::args args, py::kwargs kwargs) {
+             xbt_assert(args.size() > 2,
+                        "Creating an actor takes at least 3 parameters: name, host, and main function.");
+             return simgrid::s4u::Actor::create(args[0].cast<std::string>(), args[1].cast<Host*>(), [args]() {
+               py::tuple funargs(args.size() - 3);
+               for (size_t i = 3; i < args.size(); i++)
+                 funargs[i - 3] = args[i];
+
+               PyObject* result = PyObject_CallObject(args[2].ptr(), funargs.ptr());
+               if (!result)
+                 throw pybind11::error_already_set();
+             });
+           },
+           "Create an actor from a function or an object, see :cpp:func:`simgrid::s4u::Actor::create()`");
 }