Esempio n. 1
0
def test_instantiate_compositenode():
    """test instantiation"""
    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    addid = sg.add_node(pm.get_node("Catalog.Math", "+"))
    val1id = sg.add_node(pm.get_node("Catalog.Data", "float"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "float"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "float"))

    sg.connect(val1id, 0, addid, 0)
    sg.connect(val2id, 0, addid, 1)
    sg.connect(addid, 0, val3id, 0)

    sgfactory = CompositeNodeFactory("addition")
    sg.to_factory(sgfactory)

    # allocate the compositenode
    sg = sgfactory.instantiate()
    sg.node(val1id).set_input(0, 2.)
    sg.node(val2id).set_input(0, 3.)

    # evaluation
    sg()

    assert sg.node(val3id).get_output(0) == 5.
def test_multi_out_eval():
    """ Test multiple out connection"""

    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    val1id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "string"))

    sg.connect(val1id, 0, val2id, 0)
    sg.connect(val1id, 0, val3id, 0)

    sgfactory = CompositeNodeFactory("testlazyeval")
    sg.to_factory(sgfactory)
    # allocate the compositenode
    sg = sgfactory.instantiate()

    sg.node(val1id).set_input(0, "teststring")
    sg()
    assert sg.node(val2id).get_output(0) == "teststring"
    assert sg.node(val3id).get_output(0) == "teststring"

    #partial evaluation
    sg.node(val1id).set_input(0, "teststring2")
    sg.eval_as_expression(val2id)
    assert sg.node(val2id).get_output(0) == "teststring2"

    sg.eval_as_expression(val3id)
    assert sg.node(val3id).get_output(0) == "teststring2"
Esempio n. 3
0
    def test_recursion_factory(self):
        """ Test Recursion detection"""

        pm = self.pm
        #pm.init()
        pkg = Package("compositenode", {})

        sgfactory1 = CompositeNodeFactory("graph1")
        sgfactory2 = CompositeNodeFactory("graph2")

        map(pkg.add_factory, (sgfactory1, sgfactory2))

        assert len(pkg.get_names()) == 2

        pm.add_package(pkg)
    
        n1 = sgfactory1.instantiate()
        n2 = sgfactory1.instantiate()
        # build the compositenode factory
        n1.add_node(n2)
        n2.add_node(n1)

        n1.to_factory(sgfactory1)
        n2.to_factory(sgfactory2)

        #sgfactory1.add_nodefactory ( ("compositenode", "graph2"))
        #sgfactory2.add_nodefactory ( ("compositenode", "graph1"))

        try:
            sg = sgfactory1.instantiate()
            assert False
        except RecursionError:
            assert True
Esempio n. 4
0
def test_save_workspace():
    pm = PackageManager()
    pm.init()

    asession = Session()

    import sys

    sgfactory = CompositeNodeFactory(name="SubGraphExample",
                                description= "Examples",
                                category = "Examples",
                               )
    sg= CompositeNode()
    # build the subgraph factory

    addid = sg.add_node(pm.get_node("pkg_test", "float"))
    sg.to_factory(sgfactory)
    instance = sgfactory.instantiate()

    instance.actor(addid).set_input(0, 3)
    asession.add_workspace(instance)

    asession.save('test.pic')

    asession.workspaces = []
    asession.load('test.pic')
    try:
        os.remove('test.pic')
    except:
        os.remove('test.pic.db')

    i = asession.workspaces[0]
    assert type(i) == type(instance)
def test_to_factory():
    """ Create a compositenode, generate its factory and reintantiate it """

    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    n1 = pm.get_node("Catalog.Data", "float")
    n2 = pm.get_node("Catalog.Data", "float")
    e1 = sg.add_node(n1)
    e2 = sg.add_node(n2)
    sg.connect(e1, 0, e2, 0)

    n1.set_input(0, 34.)
    sg()
    assert n2.get_output(0)==34.

    sgfactory = CompositeNodeFactory("factorytest")
    sg.to_factory(sgfactory)

    sg2 = sgfactory.instantiate()

    assert len(list(sg2.vertices()))==2+2 # two nodes + in/ou
    assert len(list(sg2.edges()))==1

    sg2.node(e1).set_input(0, 3.)
    sg2()
    assert sg2.node(e2).get_output(0)==3.

    return pm, sg, sgfactory
Esempio n. 6
0
    def test_addnode(self):
        """Test  node addition"""

        sg = CompositeNode()

        # build the compositenode factory
        val1id = sg.add_node(self.float_node)
        val2id = sg.add_node(self.float_node)

        sg.connect(val1id, 0, val2id, 0)

        sgfactory = CompositeNodeFactory("testaddnode")
        sg.to_factory(sgfactory)
        # allocate the compositenode

        sg = sgfactory.instantiate()

        sg.node(val1id).set_input(0, 2.)
        sg()
        assert sg.node(val2id).get_output(0)==2.


        # Add a new node
        addid = sg.add_node(self.plus_node)
        sg.connect(val1id, 0, addid, 0)
        sg.connect(val2id, 0, addid, 1)

        sg.to_factory(sgfactory)
        sg = sgfactory.instantiate()
        sg.node(val1id).set_input(0, 3.)
        sg()
        assert sg.node(addid).get_output(0)==6.
Esempio n. 7
0
    def test_auto_io(self):
        """ Test auto io"""
        sg = CompositeNode()

        # build the compositenode factory
        val1id = sg.add_node(self.string_node)
        val2id = sg.add_node(self.string_node)
        val3id = sg.add_node(self.string_node)


        sg.connect(val1id, 0, val3id, 0)
        sg.connect(val2id, 0, val3id, 0)

        sgfactory = CompositeNodeFactory("testlautoio")
        sg.to_factory(sgfactory, listid=[val1id, val2id, val3id], auto_io=True)

        # allocate the compositenode
        sg = sgfactory.instantiate()
        assert sg.get_nb_input() == 2
        assert sg.get_nb_output() == 1
        sg.set_input(0, "to")
        sg.set_input(1, "to")

        sg()
        res = sg.get_output(0)
        assert ''.join(eval(res)) == "toto"
def test_auto_io():
    """ Test auto io"""
    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    val1id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "string"))

    sg.connect(val1id, 0, val3id, 0)
    sg.connect(val2id, 0, val3id, 0)

    sgfactory = CompositeNodeFactory("testlautoio")
    sg.to_factory(sgfactory, listid=[val1id, val2id, val3id], auto_io=True)

    # allocate the compositenode
    sg = sgfactory.instantiate()
    assert sg.get_nb_input() == 2
    assert sg.get_nb_output() == 1
    sg.set_input(0, "to")
    sg.set_input(1, "to")

    sg()
    res = sg.get_output(0)
    assert ''.join(eval(res)) == "toto"
Esempio n. 9
0
def test_to_factory():
    """ Create a compositenode, generate its factory and reintantiate it """

    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    n1 = pm.get_node("Catalog.Data", "float")
    n2 = pm.get_node("Catalog.Data", "float")
    e1 = sg.add_node(n1)
    e2 = sg.add_node(n2)
    sg.connect(e1, 0, e2, 0)

    n1.set_input(0, 34.)
    sg()
    assert n2.get_output(0) == 34.

    sgfactory = CompositeNodeFactory("factorytest")
    sg.to_factory(sgfactory)

    sg2 = sgfactory.instantiate()

    assert len(list(sg2.vertices())) == 2 + 2  # two nodes + in/ou
    assert len(list(sg2.edges())) == 1

    sg2.node(e1).set_input(0, 3.)
    sg2()
    assert sg2.node(e2).get_output(0) == 3.

    return pm, sg, sgfactory
Esempio n. 10
0
    def test_instantiate_compositenode(self):
        """test instantiation"""
        #pm = PackageManager()
        #pm.init()

        sg = CompositeNode()

        # build the compositenode factory
        addid = sg.add_node(self.plus_node)
        val1id = sg.add_node(self.float_node)
        val2id = sg.add_node(self.float_node)
        val3id = sg.add_node(self.float_node)

        sg.connect(val1id, 0, addid, 0)
        sg.connect(val2id, 0, addid, 1)
        sg.connect(addid, 0, val3id, 0)

        sgfactory = CompositeNodeFactory("addition")
        sg.to_factory(sgfactory)

        # allocate the compositenode
        sg = sgfactory.instantiate()
        sg.node(val1id).set_input(0, 2.)
        sg.node(val2id).set_input(0, 3.)

        # evaluation
        sg()

        assert sg.node(val3id).get_output(0) == 5.
Esempio n. 11
0
    def test_to_factory(self):
        """ Create a compositenode, generate its factory and reintantiate it """

        sg = CompositeNode()

        n1 = self.float_node
        n2 = self.float_node
        e1 = sg.add_node(n1)
        e2 = sg.add_node(n2)
        sg.connect(e1, 0, e2, 0)

        n1.set_input(0, 34.)
        sg()
        assert n2.get_output(0)==34.
    
        sgfactory = CompositeNodeFactory("factorytest")
        sg.to_factory(sgfactory)

        sg2 = sgfactory.instantiate()

        assert len(list(sg2.vertices()))==2+2 # two nodes + in/ou
        assert len(list(sg2.edges()))==1

        sg2.node(e1).set_input(0, 3.)
        sg2()
        assert sg2.node(e2).get_output(0)==3.

        return sg, sgfactory
Esempio n. 12
0
def test_auto_io():
    """ Test auto io"""
    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    val1id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "string"))

    sg.connect(val1id, 0, val3id, 0)
    sg.connect(val2id, 0, val3id, 0)

    sgfactory = CompositeNodeFactory("testlautoio")
    sg.to_factory(sgfactory, listid=[val1id, val2id, val3id], auto_io=True)

    # allocate the compositenode
    sg = sgfactory.instantiate()
    assert sg.get_nb_input() == 2
    assert sg.get_nb_output() == 1
    sg.set_input(0, "to")
    sg.set_input(1, "to")

    sg()
    res = sg.get_output(0)
    assert ''.join(eval(res)) == "toto"
Esempio n. 13
0
def test_multi_in_eval():
    """ Test multiple out connection"""
    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    val1id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "string"))

    sg.connect(val1id, 0, val3id, 0)
    sg.connect(val2id, 0, val3id, 0)

    sgfactory = CompositeNodeFactory("testlazyeval")
    sg.to_factory(sgfactory)
    # allocate the compositenode
    sg = sgfactory.instantiate()

    sg.node(val1id).set_input(0, "teststring1")
    sg.node(val2id).set_input(0, "teststring2")
    sg()
    assert (sg.node(val3id).get_output(0) == "['teststring1', 'teststring2']")\
        or \
        (sg.node(val3id).get_output(0) == "['teststring2', 'teststring1']")
def test_instantiate_compositenode():
    """test instantiation"""
    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    addid = sg.add_node(pm.get_node("Catalog.Math", "+"))
    val1id = sg.add_node(pm.get_node("Catalog.Data", "float"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "float"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "float"))

    sg.connect(val1id, 0, addid, 0)
    sg.connect(val2id, 0, addid, 1)
    sg.connect(addid, 0, val3id, 0)

    sgfactory = CompositeNodeFactory("addition")
    sg.to_factory(sgfactory)

    # allocate the compositenode
    sg = sgfactory.instantiate()
    sg.node(val1id).set_input(0, 2.)
    sg.node(val2id).set_input(0, 3.)

    # evaluation
    sg()

    assert sg.node(val3id).get_output(0) == 5.
Esempio n. 15
0
def test_save_workspace():
    pm = PackageManager()
    pm.init()

    asession = Session()

    import sys

    sgfactory = CompositeNodeFactory(
        name="SubGraphExample",
        description="Examples",
        category="Examples",
    )
    sg = CompositeNode()
    # build the subgraph factory

    addid = sg.add_node(pm.get_node("pkg_test", "float"))
    sg.to_factory(sgfactory)
    instance = sgfactory.instantiate()

    instance.actor(addid).set_input(0, 3)
    asession.add_workspace(instance)

    asession.save('test.pic')

    asession.workspaces = []
    asession.load('test.pic')
    try:
        os.remove('test.pic')
    except:
        os.remove('test.pic.db')

    i = asession.workspaces[0]
    assert type(i) == type(instance)
def test_multi_in_eval():
    """ Test multiple out connection"""
    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    val1id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "string"))

    sg.connect(val1id, 0, val3id, 0)
    sg.connect(val2id, 0, val3id, 0)


    sgfactory = CompositeNodeFactory("testlazyeval")
    sg.to_factory(sgfactory)
    # allocate the compositenode
    sg = sgfactory.instantiate()

    sg.node(val1id).set_input(0, "teststring1")
    sg.node(val2id).set_input(0, "teststring2")
    sg()
    assert (sg.node(val3id).get_output(0) == "['teststring1', 'teststring2']")\
        or \
        (sg.node(val3id).get_output(0) == "['teststring2', 'teststring1']")
Esempio n. 17
0
    def test_multi_out_eval(self):
        """ Test multiple out connection"""

        sg = CompositeNode()

        # build the compositenode factory
        val1id = sg.add_node(self.string_node)
        val2id = sg.add_node(self.string_node)
        val3id = sg.add_node(self.string_node)

        sg.connect(val1id, 0, val2id, 0)
        sg.connect(val1id, 0, val3id, 0)

        sgfactory = CompositeNodeFactory("testlazyeval")
        sg.to_factory(sgfactory)
        # allocate the compositenode
        sg = sgfactory.instantiate()

        sg.node(val1id).set_input(0, "teststring")
        sg()
        assert sg.node(val2id).get_output(0) == "teststring"
        assert sg.node(val3id).get_output(0) == "teststring"

        #partial evaluation
        sg.node(val1id).set_input(0, "teststring2")
        sg.eval_as_expression(val2id)
        assert sg.node(val2id).get_output(0) == "teststring2"

        sg.eval_as_expression(val3id)
        assert sg.node(val3id).get_output(0) == "teststring2"
Esempio n. 18
0
    def test_multi_in_eval(self):
        """ Test multiple out connection"""
        sg = CompositeNode()

        # build the compositenode factory
        val1id = sg.add_node(self.string_node)
        val2id = sg.add_node(self.string_node)
        val3id = sg.add_node(self.string_node)

        sg.connect(val1id, 0, val3id, 0)
        sg.connect(val2id, 0, val3id, 0)

        sgfactory = CompositeNodeFactory("testlazyeval")
        sg.to_factory(sgfactory)
        # allocate the compositenode
        sg = sgfactory.instantiate()

        sg.node(val1id).set_input(0, "teststring1")
        sg.node(val2id).set_input(0, "teststring2")
        sg()
        assert (sg.node(val3id).get_output(
            0) == "['teststring1', 'teststring2']") \
               or \
               (sg.node(val3id).get_output(
                   0) == "['teststring2', 'teststring1']")
Esempio n. 19
0
def test_multi_out_eval():
    """ Test multiple out connection"""

    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    val1id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "string"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "string"))

    sg.connect(val1id, 0, val2id, 0)
    sg.connect(val1id, 0, val3id, 0)

    sgfactory = CompositeNodeFactory("testlazyeval")
    sg.to_factory(sgfactory)
    # allocate the compositenode
    sg = sgfactory.instantiate()

    sg.node(val1id).set_input(0, "teststring")
    sg()
    assert sg.node(val2id).get_output(0) == "teststring"
    assert sg.node(val3id).get_output(0) == "teststring"

    #partial evaluation
    sg.node(val1id).set_input(0, "teststring2")
    sg.eval_as_expression(val2id)
    assert sg.node(val2id).get_output(0) == "teststring2"

    sg.eval_as_expression(val3id)
    assert sg.node(val3id).get_output(0) == "teststring2"
Esempio n. 20
0
def test_compositenodewriter():

    setup_module()

    pm = PackageManager()
    pm.init()

    sg = CompositeNode(inputs=[dict(name="%d" % i) for i in xrange(3)],
                       outputs=[dict(name="%d" % i) for i in xrange(4)],
                      )

    # build the compositenode factory
    addid = sg.add_node(pm.get_node("pkg_test", "+"))
    val1id = sg.add_node(pm.get_node("pkg_test", "float"))
    val2id = sg.add_node(pm.get_node("pkg_test", "float"))
    val3id = sg.add_node(pm.get_node("pkg_test", "float"))

    sg.connect(val1id, 0, addid, 0)
    sg.connect(val2id, 0, addid, 1)
    sg.connect(addid, 0, val3id, 0)
    sg.connect(val3id, 0, sg.id_out, 0)
    sgfactory = CompositeNodeFactory("addition")
    sg.to_factory(sgfactory)
    # Package
    metainfo = {'version': '0.0.1',
               'license': 'CECILL-C',
               'authors': 'OpenAlea Consortium',
               'institutes': 'INRIA/CIRAD',
               'description': 'Base library.',
               'url': 'http://openalea.gforge.inria.fr'}

    package1 = pm.create_user_package("MyTestPackage", 
                                      metainfo, os.path.curdir)
    package1.add_factory(sgfactory)
    print package1.keys()
    assert 'addition' in package1
    package1.write()

    sg = sgfactory.instantiate()

    sg.node(val1id).set_input(0, 2.)
    sg.node(val2id).set_input(0, 3.)

    # evaluation
    sg()
    print sg.node(val3id).get_output(0)
    assert sg.node(val3id).get_output(0) == 5.

    print "nb vertices", len(sg)
    assert len(sg) == 6

    pm.init()
    newsg = pm.get_node('MyTestPackage', 'addition')
    print "nb vertices", len(newsg)
    assert len(newsg) == 6
Esempio n. 21
0
    def test_compositenodeio(self):
        """ Test IO"""
        pm = self.pm
        # pm.init()

        pkg = Package("compositenode", {})

        # create a compositenode with 2 in and 1 out
        # the compositenode does an addition
        sg = CompositeNode(inputs=(dict(name="in1", interface=None, value=None),
                                   dict(name="in2", interface=None,
                                        value=None)),
                           outputs=(dict(name="out", interface=None),), )
        addid = sg.add_node(self.plus_node)

        sg.connect(sg.id_in, 0, addid, 0)
        sg.connect(sg.id_in, 1, addid, 1)
        sg.connect(addid, 0, sg.id_out, 0)

        sgfactory = CompositeNodeFactory("additionsg")
        sg.to_factory(sgfactory)

        sg1 = sgfactory.instantiate()
        sg1.set_input(0, 2.)
        sg1.set_input(1, 3.)
        sg1()

        assert sg1.get_output(0) == 5.

        pkg.add_factory(sgfactory)
        pm.add_package(pkg)

        sg = CompositeNode()
        addid = sg.add_node(pm.get_node("compositenode", "additionsg"))
        val1id = sg.add_node(self.float_node)
        val2id = sg.add_node(self.float_node)
        val3id = sg.add_node(self.float_node)

        sg.connect(val1id, 0, addid, 0)
        sg.connect(val2id, 0, addid, 1)
        sg.connect(addid, 0, val3id, 0)

        sgfactory2 = CompositeNodeFactory("testio")
        sg.to_factory(sgfactory2)
        # allocate the compositenode

        sg = sgfactory2.instantiate()
        sg.node(val1id).set_input(0, 2.)
        sg.node(val2id).set_input(0, 3.)

        # evaluation
        sg()
        assert sg.node(val3id).get_output(0) == 5.
Esempio n. 22
0
def test_compositenodewriter():
    pm = PackageManager()
    pm.init()

    sg = CompositeNode(
        inputs=[dict(name="%d" % i) for i in xrange(3)],
        outputs=[dict(name="%d" % i) for i in xrange(4)],
    )

    # build the compositenode factory
    addid = sg.add_node(pm.get_node("pkg_test", "+"))
    val1id = sg.add_node(pm.get_node("pkg_test", "float"))
    val2id = sg.add_node(pm.get_node("pkg_test", "float"))
    val3id = sg.add_node(pm.get_node("pkg_test", "float"))

    sg.connect(val1id, 0, addid, 0)
    sg.connect(val2id, 0, addid, 1)
    sg.connect(addid, 0, val3id, 0)
    sg.connect(val3id, 0, sg.id_out, 0)
    sgfactory = CompositeNodeFactory("addition")
    sg.to_factory(sgfactory)
    # Package
    metainfo = {
        'version': '0.0.1',
        'license': 'CECILL-C',
        'authors': 'OpenAlea Consortium',
        'institutes': 'INRIA/CIRAD',
        'description': 'Base library.',
        'url': 'http://openalea.gforge.inria.fr'
    }

    package1 = pm.create_user_package("MyTestPackage", metainfo, tmp_dir)
    package1.add_factory(sgfactory)
    assert 'addition' in package1
    package1.write()

    sg = sgfactory.instantiate()

    sg.node(val1id).set_input(0, 2.)
    sg.node(val2id).set_input(0, 3.)

    # evaluation
    sg()
    assert sg.node(val3id).get_output(0) == 5.

    assert len(sg) == 6

    pm.init()
    newsg = pm.get_node('MyTestPackage', 'addition')
    assert len(newsg) == 6
Esempio n. 23
0
    def set_code(self, code):
        self._initial_code = code
        if not code:
            self._workflow = CompositeNodeFactory(self.name).instantiate()
        elif isinstance(code, CompositeNodeFactory):
            # hakishhh
            # CompositeNodeFactory.instantiate_node = monkey_patch_instantiate_node
            self._workflow = code.instantiate()
        else:
            # Access to the current project
            cnf = eval(code, globals(), locals())
            # hakishhh
            CompositeNodeFactory.instantiate_node = monkey_patch_instantiate_node
#             raise IOError(cnf)
            self._workflow = cnf.instantiate()
Esempio n. 24
0
    def instantiate_widget(self):
        self._widget = dataflowview.GraphicalGraph.create_view(self.model._workflow, clone=True)
        self._clipboard = CompositeNodeFactory("Clipboard")

        from openalea.core.service.ipython import interpreter
        interp = interpreter()

        GraphOperator.globalInterpreter = interp
        self._operator = GraphOperator(graph=self.model._workflow,
                                       graphScene=self._widget.scene(),
                                       clipboard=self._clipboard,
                                       )
        self._widget.mainMenu = types.MethodType(mainMenu, self._widget)
        self._widget.applet = self
        self._widget._actions = None

        methods = {}
        methods['actions'] = actions
        methods['mainMenu'] = mainMenu
        methods['display_help'] = _display_help

        self._widget = adapt_widget(self._widget, methods)

        if not VIEWER3D_SET:
            _set_viewer3d()

        # todo: use services
        self.widget().scene().focusedItemChanged.connect(self.item_focus_change)

        return self.widget()
Esempio n. 25
0
    def test_compositenode_creation_without_edges(self):
        """test compositenode creation without edges"""

        sg = CompositeNode()

        # build the compositenode factory
        addid = sg.add_node(self.plus_node)
        val1id = sg.add_node(self.float_node)
        val2id = sg.add_node(self.float_node)
        val3id = sg.add_node(self.float_node)

        sgfactory = CompositeNodeFactory("addition")
        sg.to_factory(sgfactory)
        # allocate the compositenode
        sg = sgfactory.instantiate()

        assert len(sg) == 4+2
Esempio n. 26
0
 def __get_current_factory(self, name):
     """ Build a temporary factory for current workspace
     Return (node, factory)
     """
     master = self.master
     tempfactory = CompositeNodeFactory(name=name)
     graph = master.get_graph()
     graph.to_factory(tempfactory)
     return (graph, tempfactory)
Esempio n. 27
0
def test_compositenode_creation_without_edges():
    """test compositenode creation without edges"""
    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    addid = sg.add_node(pm.get_node("Catalog.Math", "+"))
    val1id = sg.add_node(pm.get_node("Catalog.Data", "float"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "float"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "float"))

    sgfactory = CompositeNodeFactory("addition")
    sg.to_factory(sgfactory)
    # allocate the compositenode
    sg = sgfactory.instantiate()

    assert len(sg) == 4 + 2
def test_compositenode_creation_without_edges():
    """test compositenode creation without edges"""
    pm = PackageManager()
    pm.init()

    sg = CompositeNode()

    # build the compositenode factory
    addid = sg.add_node(pm.get_node("Catalog.Math", "+"))
    val1id = sg.add_node(pm.get_node("Catalog.Data", "float"))
    val2id = sg.add_node(pm.get_node("Catalog.Data", "float"))
    val3id = sg.add_node(pm.get_node("Catalog.Data", "float"))

    sgfactory = CompositeNodeFactory("addition")
    sg.to_factory(sgfactory)
    # allocate the compositenode
    sg = sgfactory.instantiate()

    assert len(sg) == 4+2
Esempio n. 29
0
    def __init__(self):

        Observed.__init__(self)

        self.workspaces = []
        self.cworkspace = -1  # current workspace
        self.graphViews = weakref.WeakKeyDictionary()

        self.datapool = DataPool()

        # Use dictionary
        self.use_by_name = {}
        self.use_by_interface = {}

        self.pkgmanager = PackageManager()

        self.empty_cnode_factory = CompositeNodeFactory("Workspace")
        self.clipboard = CompositeNodeFactory("Clipboard")

        self.init()
Esempio n. 30
0
    def repr_code(self):
        """
        :return: a string representation of model to save it on disk
        """
        name = self.name

        if name[-3:] in ".py":
            name = name[-3:]
        elif name[-4:] in ".wpy":
            name = name[-4:]
        cn = self._workflow
        cnf = CompositeNodeFactory(name)
        cn.to_factory(cnf)

        repr_wf = repr(cnf.get_writer())
        # hack to allow eval rather than exec...
        # TODO: change the writer

        repr_wf = (" = ").join(repr_wf.split(" = ")[1:])
        return repr_wf
Esempio n. 31
0
    def repr_code(self):
        """
        :return: a string representation of model to save it on disk
        """
        name = self.name

        if name[-3:] in '.py':
            name = name[-3:]
        elif name[-4:] in '.wpy':
            name = name[-4:]
        cn = self._workflow
        cnf = CompositeNodeFactory(name)
        cn.to_factory(cnf)

        repr_wf = repr(cnf.get_writer())
        # hack to allow eval rather than exec...
        # TODO: change the writer

        repr_wf = (' = ').join(repr_wf.split(' = ')[1:])
        return repr_wf
Esempio n. 32
0
 def set_code(self, code):
     self._initial_code = code
     if not code:
         self._workflow = CompositeNodeFactory(self.name).instantiate()
     elif isinstance(code, CompositeNodeFactory):
         # hakishhh
         # CompositeNodeFactory.instantiate_node = monkey_patch_instantiate_node
         self._workflow = code.instantiate()
     else:
         # Access to the current project
         cnf = eval(code, globals(), locals())
         # hakishhh
         CompositeNodeFactory.instantiate_node = monkey_patch_instantiate_node
         #             raise IOError(cnf)
         self._workflow = cnf.instantiate()
Esempio n. 33
0
    def test_compositenodeio(self):
        """ Test IO"""
        pm = self.pm
        # pm.init()

        pkg = Package("compositenode", {})

        # create a compositenode with 2 in and 1 out
        # the compositenode does an addition
        sg = CompositeNode(
            inputs=(dict(name="in1", interface=None, value=None),
                    dict(name="in2", interface=None, value=None)),
            outputs=(dict(name="out", interface=None), ),
        )
        addid = sg.add_node(self.plus_node)

        sg.connect(sg.id_in, 0, addid, 0)
        sg.connect(sg.id_in, 1, addid, 1)
        sg.connect(addid, 0, sg.id_out, 0)

        sgfactory = CompositeNodeFactory("additionsg")
        sg.to_factory(sgfactory)

        sg1 = sgfactory.instantiate()
        sg1.set_input(0, 2.)
        sg1.set_input(1, 3.)
        sg1()

        assert sg1.get_output(0) == 5.

        pkg.add_factory(sgfactory)
        pm.add_package(pkg)

        sg = CompositeNode()
        addid = sg.add_node(pm.get_node("compositenode", "additionsg"))
        val1id = sg.add_node(self.float_node)
        val2id = sg.add_node(self.float_node)
        val3id = sg.add_node(self.float_node)

        sg.connect(val1id, 0, addid, 0)
        sg.connect(val2id, 0, addid, 1)
        sg.connect(addid, 0, val3id, 0)

        sgfactory2 = CompositeNodeFactory("testio")
        sg.to_factory(sgfactory2)
        # allocate the compositenode

        sg = sgfactory2.instantiate()
        sg.node(val1id).set_input(0, 2.)
        sg.node(val2id).set_input(0, 3.)

        # evaluation
        sg()
        assert sg.node(val3id).get_output(0) == 5.
Esempio n. 34
0
    def read_specification(self):
        spec = self.dir / 'specifications'
        from openalea.core.compositenode import CompositeNodeFactory
        from openalea.core.compositenode import CompositeNode

        f = spec.open()
        self.sg = CompositeNode()
        #name  = self.dir.basename().split('-')[-1]
        name = self.dir.basename()
        self.sgfactory = CompositeNodeFactory(name)

        self.read_files(f)
        self.read_commands(f)
        self.process_files()
        self.build_graph()

        f.close()
Esempio n. 35
0
def composite_node():
    inputs = []
    outputs = []
    for io in list('abcd'):
        inputs.append({
            'name': io,
            'desc': 'Input %s' % io.upper(),
            'value': 0
        })
        outputs.append({'name': io, 'desc': 'Input %s' % io.upper()})

    sg = CompositeNode(inputs=inputs, outputs=outputs)

    for i in range(len(inputs)):
        sg.connect(sg.id_in, i, sg.id_out, i)

    sgfactory = CompositeNodeFactory("addition")
    sg.to_factory(sgfactory)

    return sgfactory
Esempio n. 36
0
    def __init__(self):

        Observed.__init__(self)

        self.workspaces = []
        self.cworkspace = -1  # current workspace
        self.graphViews = weakref.WeakKeyDictionary()

        self.datapool = DataPool()

        # Use dictionary
        self.use_by_name = {}
        self.use_by_interface = {}

        self.pkgmanager = PackageManager()

        self.empty_cnode_factory = CompositeNodeFactory("Workspace")
        self.clipboard = CompositeNodeFactory("Clipboard")

        self.init()
Esempio n. 37
0
    def __init__(self,
                 graph,
                 graphScene=None,
                 clipboard=None,
                 siblings=None,
                 interpreter=None,
                 graphAdapter=None):
        Observed.__init__(self)

        do_imports()
        configure_dataflow_types()

        self.__ops = [
            dataflow.DataflowOperators(self),
            layout.LayoutOperators(self),
            color.ColorOperators(self),
            vertex.VertexOperators(self),
            port.PortOperators(self),
            anno.AnnotationOperators(self)
        ]

        self.__availableNames = {}

        for operator in self.__ops:
            for meth in dir(operator):
                self.__availableNames[meth] = getattr(operator, meth)

        self.__graph = graph
        self.__adapter = graphAdapter
        self.__scene = graphScene
        self.__clipboard = clipboard or CompositeNodeFactory("Clipboard")
        self.__siblings = siblings or []
        self.__interpreter = interpreter or GraphOperator.globalInterpreter

        # when working on current item these can be set
        self.__vertexItem = None
        self.__annotationItem = None
        self.__portItem = None
Esempio n. 38
0
def composite_node(a=1, b=2):
    pkg = package()

    plus_node = pkg['plus'].instantiate()
    int_node = pkg['int'].instantiate()

    if a is None:
        input_a = {'interface': IInt, 'name': 'a', 'desc': ''}
    else:
        input_a = {'interface': IInt, 'name': 'a', 'value': a, 'desc': ''}

    if b is None:
        input_b = {'interface': IInt, 'name': 'b', 'desc': ''}
    else:
        input_b = {'interface': IInt, 'name': 'b', 'value': b, 'desc': ''}

    sg = CompositeNode(
        inputs=[input_a, input_b],
        outputs=[{
            'interface': IInt,
            'name': 'a',
            'desc': 'result'
        }],
    )

    # build the compositenode factory
    addid = sg.add_node(plus_node)

    sg.connect(sg.id_in, 0, addid, 0)
    sg.connect(sg.id_in, 1, addid, 1)
    sg.connect(addid, 0, sg.id_out, 0)

    sgfactory = CompositeNodeFactory("addition")
    sg.to_factory(sgfactory)

    return sgfactory
Esempio n. 39
0
class Session(Observed):

    """
    A session is composed by different workspaces, and an user package.
    A workspace is an open node
    A session can be saved on disk.
    """

    USR_PKG_NAME = "__my package__"

    def __init__(self):

        Observed.__init__(self)

        self.workspaces = []
        self.cworkspace = -1  # current workspace
        self.graphViews = weakref.WeakKeyDictionary()

        self.datapool = DataPool()

        # Use dictionary
        self.use_by_name = {}
        self.use_by_interface = {}

        self.pkgmanager = PackageManager()

        self.empty_cnode_factory = CompositeNodeFactory("Workspace")
        self.clipboard = CompositeNodeFactory("Clipboard")

        self.init()

    # gengraph
    def simulate_workspace_addition(self):
        for ws in self.workspaces:
            self.notify_listeners(("workspace_added", ws))
    #/gengraph

    def get_current_workspace(self, ):
        """ Return the current workspace object """
        return self.workspaces[self.cworkspace]

    ws = property(get_current_workspace)

    def get_graph_views(self):
        return self.graphViews.keys()

    def add_graph_view(self, view):
        self.graphViews[view] = None

    def add_workspace(self, compositenode=None, notify=True):
        """
        Open a new workspace in the session
        if compositenode = None, create a new empty compositenode
        """
        if compositenode is None:
            compositenode = self.empty_cnode_factory.instantiate()
            compositenode.set_caption("")
            self.workspaces.append(compositenode)

        elif(compositenode not in self.workspaces):
            self.workspaces.append(compositenode)
        else:
            return compositenode

        if(notify):
            self.notify_listeners(("workspace_added", compositenode))

        return compositenode

    def close_workspace(self, index, notify=True):
        """ Close workspace at index """

        del self.workspaces[index]
        if(notify):
            self.notify_listeners()

    def init(self, create_workspace=True):
        """ Init the Session """

        self.session_filename = None
        #self.workspaces = []

        # init pkgmanager
        self.pkgmanager.find_and_register_packages()

        # Create user package if needed
        if (not self.pkgmanager.has_key(self.USR_PKG_NAME)):
            try:
                self.pkgmanager.create_user_package(self.USR_PKG_NAME, {})
            except:
                pass

        if (create_workspace):
            self.add_workspace()
            self.cworkspace = 0

        load_interfaces()
        self.notify_listeners()

    def clear(self, create_workspace=True):
        """ Reinit Session """

        self.datapool.clear()
        self.pkgmanager.clear()
        self.init(create_workspace)

    def save(self, filename=None):
        """
        Save session in filename
        user_pkg and workspaces data are saved

        Be careful, this method do not work very well if data are not
        persistent.
        """

        if (filename):
            self.session_filename = filename

        d = shelve.open(self.session_filename, writeback=True)

        # modules
        modules_path = []
        for k in sys.modules.keys():
            m = sys.modules[k]
            if hasattr(m, '__file__'):
                modules_path.append((m.__name__, os.path.abspath(m.__file__)))

        d['__modules__'] = modules_path
        d.sync()

        # datapool
        d['datapool'] = {}
        for key in self.datapool:

            try:
                d['datapool'][key] = self.datapool[key]
                d.sync()
            except Exception, e:
                print e
                print "Unable to save %s in the datapool..." % str(key)
                del d['datapool'][key]

        # workspaces
        d['workspaces'] = []
        for cpt, ws in enumerate(self.workspaces):
            try:
                d['workspaces'].append(ws)
                d.sync()
            except Exception, e:
                print e
                print "Unable to save workspace %i. Skip this." % (cpt, )
                print " WARNING: Your session is not saved. Please save your dataflow as a composite node !!!!!"
                d['workspaces'].pop()
Esempio n. 40
0
 def __init__(self, **kwargs):
     name = kwargs.get("name", "Workflow")
     kwargs["name"] = name
     self._workflow = CompositeNodeFactory(name).instantiate()
     super(VisualeaModel, self).__init__(**kwargs)
Esempio n. 41
0
class VisualeaModel(Model):
    default_name = "Workflow"
    default_file_name = "workflow.wpy"
    pattern = "*.wpy"
    extension = "wpy"
    icon = ":/images/resources/openalealogo.png"
    dtype = default_name
    mimetype = "text/x-visualea"

    def __init__(self, **kwargs):
        name = kwargs.get("name", "Workflow")
        kwargs["name"] = name
        self._workflow = CompositeNodeFactory(name).instantiate()
        super(VisualeaModel, self).__init__(**kwargs)

    def get_documentation(self):
        """

        :return: docstring of current workflow
        """
        if hasattr(self._workflow, "get_tip"):
            self._doc = self._workflow.get_tip()
        return self._doc

    def repr_code(self):
        """
        :return: a string representation of model to save it on disk
        """
        name = self.name

        if name[-3:] in ".py":
            name = name[-3:]
        elif name[-4:] in ".wpy":
            name = name[-4:]
        cn = self._workflow
        cnf = CompositeNodeFactory(name)
        cn.to_factory(cnf)

        repr_wf = repr(cnf.get_writer())
        # hack to allow eval rather than exec...
        # TODO: change the writer

        repr_wf = (" = ").join(repr_wf.split(" = ")[1:])
        return repr_wf

    def eval_value(self, value):
        return value

    def _outputs(self):
        outputs = []
        for i, outobj in enumerate(self.outputs_info):
            out = self._workflow.get_output(i)
            outputs.append(out)
            self._ns[outobj.name] = out
        if len(outputs) == 0:
            return None
        elif len(outputs) == 1:
            return outputs[0]
        else:
            return outputs

    def _set_inputs(self, *args, **kwargs):
        self._ns = self.inputs_from_ns(self.inputs_info, self._ns, *args, **kwargs)
        for i, inp in enumerate(self.inputs_info):
            self._workflow.set_input(i, self._ns[inp.name])

    def run(self, *args, **kwargs):
        """
        execute entire model
        """
        self.init(*args, **kwargs)
        self._workflow.eval()
        outputs = self._outputs()
        return outputs

    def namespace(self, **kwargs):
        from openalea.core.service.run import namespace

        return namespace(self, **kwargs)

    def init(self, *args, **kwargs):
        """
        go back to initial step
        """
        user_ns = kwargs.pop("namespace", {})
        self._ns = user_ns
        self._ns.update(self.namespace())
        self._set_inputs(*args, **kwargs)
        return self._outputs()

    def step(self, *args, **kwargs):
        """
        execute only one step of the model
        """
        raise NotImplementedError
        self._set_inputs()
        self._workflow.eval_as_expression()
        return self._outputs()

    def stop(self, *args, **kwargs):
        """
        stop execution
        """
        # TODO : to implement
        pass

    def animate(self, *args, **kwargs):
        """
        run model step by step
        """
        return self._workflow.eval()

    def execute(self, code=None):
        """
        In other paradigms: Execute code (str).
        Here this method does not have signification (only for "script-like" paradigm), so, it make a **run**.
        """
        return self.run()

    def set_code(self, code):
        self._initial_code = code
        if not code:
            self._workflow = CompositeNodeFactory(self.name).instantiate()
        elif isinstance(code, CompositeNodeFactory):
            # hakishhh
            # CompositeNodeFactory.instantiate_node = monkey_patch_instantiate_node
            self._workflow = code.instantiate()
        else:
            # Access to the current project
            cnf = eval(code, globals(), locals())
            # hakishhh
            CompositeNodeFactory.instantiate_node = monkey_patch_instantiate_node
            #             raise IOError(cnf)
            self._workflow = cnf.instantiate()

    @property
    def inputs_info(self):
        inputs = []
        for inp in self._workflow.input_desc:
            inpobj = InputObj()
            inpobj.name = inp.get("name", None)
            inpobj.interface = inp.get("interface", None)
            inpobj.default = inp.get("value", None)
            inputs.append(inpobj)
        return inputs

    @inputs_info.setter
    def inputs_info(self, inputs):
        self._workflow.clear_inputs()
        for inp in inputs:
            self._workflow.add_input(name=inp.name, value=inp.default, interface=inp.interface)

    @property
    def outputs_info(self):
        outputs = []
        for out in self._workflow.output_desc:
            outobj = OutputObj()
            outobj.name = out.get("name", None)
            outobj.interface = out.get("interface", None)
            outobj.default = out.get("value", None)
            outputs.append(outobj)
        return outputs

    @outputs_info.setter
    def outputs_info(self, outputs):
        self._workflow.clear_outputs()
        for out in outputs:
            self._workflow.add_output(name=out.name, value=out.default, interface=out.interface)
Esempio n. 42
0
 def __init__(self, **kwargs):
     name = kwargs.get('name', 'Workflow')
     kwargs['name'] = name
     self._workflow = CompositeNodeFactory(name).instantiate()
     super(VisualeaModel, self).__init__(**kwargs)
Esempio n. 43
0
class VisualeaModel(Model):
    default_name = "Workflow"
    default_file_name = "workflow.wpy"
    pattern = "*.wpy"
    extension = "wpy"
    icon = ":/images/resources/openalealogo.png"
    dtype = default_name
    mimetype = "text/x-visualea"

    def __init__(self, **kwargs):
        name = kwargs.get('name', 'Workflow')
        kwargs['name'] = name
        self._workflow = CompositeNodeFactory(name).instantiate()
        super(VisualeaModel, self).__init__(**kwargs)

    def get_documentation(self):
        """

        :return: docstring of current workflow
        """
        if hasattr(self._workflow, "get_tip"):
            self._doc = self._workflow.get_tip()
        return self._doc

    def repr_code(self):
        """
        :return: a string representation of model to save it on disk
        """
        name = self.name

        if name[-3:] in '.py':
            name = name[-3:]
        elif name[-4:] in '.wpy':
            name = name[-4:]
        cn = self._workflow
        cnf = CompositeNodeFactory(name)
        cn.to_factory(cnf)

        repr_wf = repr(cnf.get_writer())
        # hack to allow eval rather than exec...
        # TODO: change the writer

        repr_wf = (' = ').join(repr_wf.split(' = ')[1:])
        return repr_wf

    def eval_value(self, value):
        return value

    def _outputs(self):
        outputs = []
        for i, outobj in enumerate(self.outputs_info):
            out = self._workflow.get_output(i)
            outputs.append(out)
            self._ns[outobj.name] = out
        if len(outputs) == 0:
            return None
        elif len(outputs) == 1:
            return outputs[0]
        else:
            return outputs

    def _set_inputs(self, *args, **kwargs):
        self._ns = self.inputs_from_ns(self.inputs_info, self._ns, *args, **kwargs)
        for i, inp in enumerate(self.inputs_info):
            self._workflow.set_input(i, self._ns[inp.name])

    def run(self, *args, **kwargs):
        """
        execute entire model
        """
        self.init(*args, **kwargs)
        self._workflow.eval()
        outputs = self._outputs()
        return outputs

    def namespace(self, **kwargs):
        from openalea.core.service.run import namespace
        return namespace(self, **kwargs)

    def init(self, *args, **kwargs):
        """
        go back to initial step
        """
        user_ns = kwargs.pop('namespace', {})
        self._ns = user_ns
        self._ns.update(self.namespace())
        self._set_inputs(*args, **kwargs)
        return self._outputs()

    def step(self, *args, **kwargs):
        """
        execute only one step of the model
        """
        raise NotImplementedError
        self._set_inputs()
        self._workflow.eval_as_expression()
        return self._outputs()

    def stop(self, *args, **kwargs):
        """
        stop execution
        """
        # TODO : to implement
        pass

    def animate(self, *args, **kwargs):
        """
        run model step by step
        """
        return self._workflow.eval()

    def execute(self, code=None):
        """
        In other paradigms: Execute code (str).
        Here this method does not have signification (only for "script-like" paradigm), so, it make a **run**.
        """
        return self.run()

    def set_code(self, code):
        self._initial_code = code
        if not code:
            self._workflow = CompositeNodeFactory(self.name).instantiate()
        elif isinstance(code, CompositeNodeFactory):
            # hakishhh
            # CompositeNodeFactory.instantiate_node = monkey_patch_instantiate_node
            self._workflow = code.instantiate()
        else:
            # Access to the current project
            cnf = eval(code, globals(), locals())
            # hakishhh
            CompositeNodeFactory.instantiate_node = monkey_patch_instantiate_node
#             raise IOError(cnf)
            self._workflow = cnf.instantiate()

    @property
    def inputs_info(self):
        inputs = []
        for inp in self._workflow.input_desc:
            inpobj = InputObj()
            inpobj.name = inp.get('name', None)
            inpobj.interface = inp.get('interface', None)
            inpobj.default = inp.get('value', None)
            inputs.append(inpobj)
        return inputs

    @inputs_info.setter
    def inputs_info(self, inputs):
        self._workflow.clear_inputs()
        for inp in inputs:
            self._workflow.add_input(name=inp.name, value=inp.default, interface=inp.interface)

    @property
    def outputs_info(self):
        outputs = []
        for out in self._workflow.output_desc:
            outobj = OutputObj()
            outobj.name = out.get('name', None)
            outobj.interface = out.get('interface', None)
            outobj.default = out.get('value', None)
            outputs.append(outobj)
        return outputs

    @outputs_info.setter
    def outputs_info(self, outputs):
        self._workflow.clear_outputs()
        for out in outputs:
            self._workflow.add_output(name=out.name, value=out.default, interface=out.interface)
 def new(self):
     iname = self.__name__
     node = CompositeNodeFactory(iname).instantiate()
     node.set_caption(iname)
     return self.wrap_data(node.caption, node)
Esempio n. 45
0
 def start(self):
     from openalea.visualea.graph_operator import GraphOperator
     self.__clipboard = CompositeNodeFactory("Clipboard")
     self.__siblings = SiblingList(CompositeNode.mimetype)
Esempio n. 46
0
class Session(Observed):
    """
    A session is composed by different workspaces, and an user package.
    A workspace is an open node
    A session can be saved on disk.
    """

    USR_PKG_NAME = "__my package__"

    def __init__(self):

        Observed.__init__(self)

        self.workspaces = []
        self.cworkspace = -1  # current workspace
        self.graphViews = weakref.WeakKeyDictionary()

        self.datapool = DataPool()

        # Use dictionary
        self.use_by_name = {}
        self.use_by_interface = {}

        self.pkgmanager = PackageManager()

        self.empty_cnode_factory = CompositeNodeFactory("Workspace")
        self.clipboard = CompositeNodeFactory("Clipboard")

        self.init()

    # gengraph
    def simulate_workspace_addition(self):
        for ws in self.workspaces:
            self.notify_listeners(("workspace_added", ws))

    #/gengraph

    def get_current_workspace(self, ):
        """ Return the current workspace object """
        return self.workspaces[self.cworkspace]

    ws = property(get_current_workspace)

    def get_graph_views(self):
        return self.graphViews.keys()

    def add_graph_view(self, view):
        self.graphViews[view] = None

    def add_workspace(self, compositenode=None, notify=True):
        """
        Open a new workspace in the session
        if compositenode = None, create a new empty compositenode
        """
        if compositenode is None:
            compositenode = self.empty_cnode_factory.instantiate()
            compositenode.set_caption("")
            self.workspaces.append(compositenode)

        elif (compositenode not in self.workspaces):
            self.workspaces.append(compositenode)
        else:
            return compositenode

        if (notify):
            self.notify_listeners(("workspace_added", compositenode))

        return compositenode

    def close_workspace(self, index, notify=True):
        """ Close workspace at index """

        del self.workspaces[index]
        if (notify):
            self.notify_listeners()

    def init(self, create_workspace=True):
        """ Init the Session """

        self.session_filename = None
        #self.workspaces = []

        # init pkgmanager
        self.pkgmanager.find_and_register_packages()

        # Create user package if needed
        if (not self.pkgmanager.has_key(self.USR_PKG_NAME)):
            try:
                self.pkgmanager.create_user_package(self.USR_PKG_NAME, {})
            except:
                pass

        if (create_workspace):
            self.add_workspace()
            self.cworkspace = 0

        load_interfaces()
        self.notify_listeners()

    def clear(self, create_workspace=True):
        """ Reinit Session """

        self.datapool.clear()
        self.pkgmanager.clear()
        self.init(create_workspace)

    def save(self, filename=None):
        """
        Save session in filename
        user_pkg and workspaces data are saved

        Be careful, this method do not work very well if data are not
        persistent.
        """

        if (filename):
            self.session_filename = filename

        d = shelve.open(self.session_filename, writeback=True)

        # modules
        modules_path = []
        for k in sys.modules.keys():
            m = sys.modules[k]
            if hasattr(m, '__file__'):
                modules_path.append((m.__name__, os.path.abspath(m.__file__)))

        d['__modules__'] = modules_path
        d.sync()

        # datapool
        d['datapool'] = {}
        for key in self.datapool:

            try:
                d['datapool'][key] = self.datapool[key]
                d.sync()
            except Exception, e:
                print e
                print "Unable to save %s in the datapool..." % str(key)
                del d['datapool'][key]

        # workspaces
        d['workspaces'] = []
        for cpt, ws in enumerate(self.workspaces):
            try:
                d['workspaces'].append(ws)
                d.sync()
            except Exception, e:
                print e
                print "Unable to save workspace %i. Skip this." % (cpt, )
                print " WARNING: Your session is not saved. Please save your dataflow as a composite node !!!!!"
                d['workspaces'].pop()