Getting top node of imported maya file

4,051 views
Skip to first unread message

Eric Thivierge

unread,
Dec 1, 2014, 3:06:56 PM12/1/14
to python_in...@googlegroups.com
Is there a way to get a pointer / node of the top node of a Maya file
that was imported using the PyMel method "ImportFile"? It seems it may
be returning all of the nodes that are imported and then I'd have to
iterate through them all and see which one doesn't have a parent?

Thanks,
Eric T.

Marcus Ottosson

unread,
Dec 1, 2014, 3:48:36 PM12/1/14
to python_in...@googlegroups.com

Top level nodes are known as assemblies in Maya. Although I don’t know of any way of getting a reference directly from an import, listing assemblies directly may help distil new nodes.

Assuming your file only had a single top-level node:

from maya import cmds

before = cmds.ls(assemblies=True)
cmds.polyCube(name="MyCube")  # Perform your import here
after = cmds.ls(assemblies=True)
top_level_node = set(after).difference(before).pop()

print top_level_node  # Returns MyCube

Bradley Friedman

unread,
Dec 1, 2014, 3:52:46 PM12/1/14
to python_in...@googlegroups.com
As in mel before it, I’ve generally forced it to import into a group, and hence have the ability to specify the group name. Then I acquire the new group by name. By definition, its children are the things that were imported. If the new group is undesirable, I un-parent the contents and then delete it once I’ve used it to get a handle on the file contents.

Ugly, but effective.

-brad
> --
> You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/547CCA5C.6090608%40hybride.com.
> For more options, visit https://groups.google.com/d/optout.

Eric Thivierge

unread,
Dec 1, 2014, 3:56:09 PM12/1/14
to python_in...@googlegroups.com, Bradley Friedman
Thanks both for the info.

Marcus Ottosson

unread,
Dec 1, 2014, 5:06:03 PM12/1/14
to python_in...@googlegroups.com
That's a clever approach!

Along those lines, you could also opt to import files under a given namespace; all nodes, including non-DAG ones, will end up within the namespace. As a side-note, this is probably as close as you'll get to the Softimage "Model".

Justin Israel

unread,
Dec 1, 2014, 5:54:33 PM12/1/14
to python_in...@googlegroups.com
Also as a variation to what Marcus suggested, instead of needing to first capture the assemblies in the scene, do the import, and compare the new assemblies listing to the old one with a set, you can just pass your list of nodes to ls() and have it return just the assemblies:

cmds.ls(nodes, assemblies=True)



On Tue Dec 02 2014 at 11:05:59 Marcus Ottosson <konstr...@gmail.com> wrote:
That's a clever approach!

Along those lines, you could also opt to import files under a given namespace; all nodes, including non-DAG ones, will end up within the namespace. As a side-note, this is probably as close as you'll get to the Softimage "Model".

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

Christopher Crouzet

unread,
Dec 1, 2014, 6:42:09 PM12/1/14
to python_in...@googlegroups.com

Marcus Ottosson

unread,
Dec 2, 2014, 3:31:07 AM12/2/14
to python_in...@googlegroups.com

Also as a variation to what Marcus suggested, instead of needing to first capture the assemblies in the scene, do the import, and compare the new assemblies listing to the old one with a set, you can just pass your list of nodes to ls() and have it return just the assemblies.

The question is, which list do you pass? The reason for doing a before and after is getting the difference in order to figure out which nodes were imported, and which were already there.

Using the Maya Python API:

topLevelDagPaths = list(OpenMaya.bnn_MItDagHierarchy())
OpenMaya.MFileIO.importFile(fileName, type, preserveReferences,
                            nameSpace, ignoreVersion)
return [dagPath for dagPath in OpenMaya.bnn_MItDagHierarchy()
        if not dagPath in topLevelDagPaths]

Which seems to iterate using OpenMaya.MItDag(OpenMaya.MItDag.kBreadthFirst)

It looks like this will return all imported nodes, and not just the assembilies. In addition, finding differences via list-comprehension is about 100x slower than using sets.



For more options, visit https://groups.google.com/d/optout.



--
Marcus Ottosson
konstr...@gmail.com

Christopher Crouzet

unread,
Dec 2, 2014, 4:09:03 AM12/2/14
to python_in...@googlegroups.com
I believe you're wrong on both points.

Firstly, the constructor of the iterator `bnn_MItDagHiearchy` has a default argument `recursive=false`, meaning that only the top (assembly) DAG nodes will be returned, as expected by the `bnn_importFile()` method.

Secondly, and since you seem to enjoy reading development practices online, you must know that you shouldn't talk about premature optimizations when there's no actual performance issues. Especially in this case where:
- the method `bnn_importFile()` most likely won't be used in a tight loop. And even if it does, the performance limitations would come from the actual import of the file incurred by Maya rather than from something as insignificant as choosing between list-comprehension or sets.
- the number of items being checked for uniqueness within the list comprehension is most likely to be very (very) small, and hence there more likely won't be any noticeable difference in performances whatever method is used, even if you decided to generate that list 17458 times in a row.



For more options, visit https://groups.google.com/d/optout.

Christopher Crouzet

unread,
Dec 2, 2014, 4:19:54 AM12/2/14
to python_in...@googlegroups.com
By “actual performance issues”, I meant performance hits that have been proved after measurements over the expected use cases.

Keep in mind that optimizations often work the other way around from what we intuitively think, and as a rule you should only worry to write code that is readable unless optimizations are actually required.

Some extra literature for you on this exact subject of lists vs sets applied to C++: http://lafstern.org/matt/col1.pdf
Now, do you still think that the additional complexity of a set data structure is worth it for such a small amount of elements?

Marcus Ottosson

unread,
Dec 2, 2014, 4:27:41 AM12/2/14
to python_in...@googlegroups.com

Christopher, I’m sorry I didn’t read too carefully through your code, but you didn’t really provide much information to along with your suggestion to use your library for the task in the OP.

and since you seem to enjoy reading development practices online

I’m sensing I may have offended you, sorry about that.

the number of items being checked for uniqueness within the list comprehension is most likely to be very (very) small

My suggestion to use sets here was in regards to comparing all nodes contained within a file. Files may contain quite a few nodes, even in the hundreds of thousands, and in these cases I believe sets produce a noticeable difference.



For more options, visit https://groups.google.com/d/optout.



--
Marcus Ottosson
konstr...@gmail.com

Christopher Crouzet

unread,
Dec 2, 2014, 5:08:05 AM12/2/14
to python_in...@googlegroups.com
I provided my suggestion because I knew that it would meet the requirements of the question. Why would I need to describe its code?

I'm not offended, it's just annoying to be linked to some StackOverflow bullshit like if the answer there was some kind of holy graal accurately providing a solution for all the problems in the universe. Even though the author of the answer rightfully says that “it depends”, and emphasizes on the need to time it, he still writes as a fact that sets are significally faster when checking for uniqueness—thus without any sort of proof. In which case is he right or wrong? Maybe it becomes true only when using more than 100,000+ elements? Would the results still be the same for large elements, or heterogeneous elements? I'd expect from you to be more critic towards this kind of things.

I'd also expect from you to not give such advices that you don't know true for sure, especially since I haven't asked any help on the subject. If I was a newbie, I would believe you as well as that author on SO, and maybe I would go on rewriting all my codebase to use sets for such cases and tell all my friends to do the same, until I'd realize 2 years later how wrong it all is. All this when we shouldn't even have been talking about this matter for such a non-critical code that is meant to run once and where readability prevails.

It's of course a stupid example but—and you can find some more literature on the subject—all I'm trying to say here is to be careful on what you say as it can/will influence others and might perpetuate bad coding practices.

Enough OT.



For more options, visit https://groups.google.com/d/optout.

Marcus Ottosson

unread,
Dec 2, 2014, 5:23:47 AM12/2/14
to python_in...@googlegroups.com
Relax?

Justin Israel

unread,
Dec 2, 2014, 5:29:20 AM12/2/14
to python_in...@googlegroups.com
@Marcus, sorry if my suggestion was vague. My intention was that the list would be that returned from the file import call, when using the "return new nodes" flag. One could take that list and query for the assemblies.

@Christopher, while I don't want to further propagate the off-topic discussion, I figured since we are already there, I might throw in my 2cents. I actually see valid points in both your comments as well as Marcus. I definitely agree that premature optimisation is the root of all evil. But what about cases where a certain idiom over another could yield a better possible outcome vs no change at all, simply by it becoming muscle memory? The way I see it, if you aren't expending any extra time trying to optimise a piece of code, and your first thought goes to "membership test in a loop... I'll use a set", did we lose anything by that? In this particular case, maybe using a set yields no quantifiable gain, but does the practice in doing so yield anything over time? Then again, in your defence you are correct that you did not ask for any help and your code was not meant to be the subject of evaluation. But either way, it was code provided, and we tend to spawn conversation on this list at random points.

Again, I am just throwing in my thoughts on both sides. My own muscle memory would have made me write a set when looping and testing membership, at no extra "pre-optimization costs" to my development process. I just figure O(1) beats O(n) and if I am wrong, then it is still O(n). But then again no one was asking for opinions :-)


Marcus Ottosson

unread,
Dec 2, 2014, 6:28:28 AM12/2/14
to python_in...@googlegroups.com

when using the “return new nodes” flag

Aah, I didn’t know there was such a thing! That’s perfect.

For a completeness,

new_nodes = cmds.file("MyCube.mb", i=True, returnNewNodes=True)
print cmds.ls(new_nodes, assemblies=True)[0]
# MyCube

Christopher Crouzet

unread,
Dec 2, 2014, 7:26:44 AM12/2/14
to python_in...@googlegroups.com
@Marucs: WHAT ARE YOU TALKING ABOUT!? I AM ALREADY RELAXED!!!$#^(*&@

@Justin: my previous comments were only aimed towards avoiding premature optimization but now that's another topic. Optimizations aside, I share your point of view regarding your “first thought”. The idea is to code using the tools that express the best the intentions of the developer. If the idea is to have an unique set of elements, then a set is a good choice.

Still, I'm subjectively happy with my choice of using a comprehensive list in the context of the `bnn_importFile()` method because it was the simplest to use. I'm a bit rusty with Python right now, so maybe I'm wrong, but I believe that if I've had to implement that method using sets, then I would have had to deal with needless conversions from/to lists, which would have made the code less readable without any real improvement on my intentions (I believe it's quite obvious already, and Marcus proved it)—I'm not even talking here of the additional allocations that those conversions would have probably caused on the heap, he he he!

Btw, O(1) does provide better performances than O(n) when processing but that would be forgetting the initialization-related costs. When the costs of memory allocation due to a more complex data structure are significant in comparison to the costs of the operations to process, then the O(1) algorithm might lose versus the O(n) one in order of magnitudes. If I remember well, that's what the C++ paper of vectors vs sets is talking about. That's also why most of the time there is no universal trick to increase performances and that benchmarking each snippet of code is the only way to go when required, and hence why any optimization intuition should be dismissed to focus solely on the code semantics.

That being said... optimizations look fun! Can't wait to learn how to dig into assembly code :)



For more options, visit https://groups.google.com/d/optout.

Joe Weidenbach

unread,
Dec 2, 2014, 11:52:54 AM12/2/14
to python_in...@googlegroups.com
Not to perpetuate a long discussion, but I personally find lots of benefits in discussing multiple ways of achieving things on a list such as this.  I haven't dealt with file imports from a script in a while myself, but the thing I picked up from this was the assemblies trick.  In my younger, more naive days, I wrote an importer and then proceeded to check each node and see if it was a root node or not, looping over it as I went.  I found the returnNewNodes flag in the documentation for file, and used that list, iterating manually over it with listRelatives.  The assemblies thing would have saved me a lot of loops there, and been much clearer to read. It's all about building the toolbelt!

For more options, visit https://groups.google.com/d/optout.




This email is free from viruses and malware because avast! Antivirus protection is active.


Justin Israel

unread,
Dec 2, 2014, 4:17:01 PM12/2/14
to python_in...@googlegroups.com
@ Christopher, I completely agree that constructing temporary sets from lists adds the overhead. I was only going off your own code example where you already convert your dag iterator into a list:  list(iterator),  vs doing  set(iterator). Sets do have a slightly higher cost for construction. But again, following my "first thought" mentality, I would have probably figured that the loop and membership test is the focus and not the construction. Again, I also completely agree that readability counts. But if just doing  s/list/set/ improves time complexity without sacrificing readability, I tend to commit that to my "first thought" muscle memory. 

@ Joe, ya that's actually what I like about allowing threads to slightly go off-topic on this list. It tends to bring out pretty useful discussions. Maybe other lists are pretty adamant about keeping each thread on topic, and generally it would be a good idea. But at least this side discussion wasn't completely off topic, as it was discussing extra code that was presented as an example for the original topic. 

It all adds up anyways to a pretty informative archive. 


Christopher Crouzet

unread,
Dec 2, 2014, 10:59:43 PM12/2/14
to python_in...@googlegroups.com
Aaah, I understand you now about the list(iterator) vs set(iterator) and you're right, I could definitely have used a set here from a semantic point of view.


While we're still in the OT for the sake of the informative archive, I've been intrigued and, as a set newbie that I am, I've just discovered the existance of the operator “-” allowing to return the difference between two sets. So I thought “cool” and I tried to implement the method entirely with sets for the fun of it, even though I knew I wouldn't like the final conversion to a list:

    def bnn_importFile(cls, fileName, type='', preserveReferences=False,
                       nameSpace='', ignoreVersion=False):
        if not type:
            type = None
        
        if not nameSpace:
            nameSpace = None
        
        topLevelDagPaths = set(OpenMaya.bnn_MItDagHierarchy())
        OpenMaya.MFileIO.importFile(fileName, type, preserveReferences,
                                    nameSpace, ignoreVersion)
        return list(set(OpenMaya.bnn_MItDagHierarchy()) - topLevelDagPaths)


The operator “-” doesn't seem to do its job here. I don't want to spend time investigating the issue but I quickly checked if the required `__hash__()` and `__eq__()` methods for such an operation to work were well defined for OpenMaya.MDagPath objects, and it seems to be the case. That's a bit of a mystery.



For more options, visit https://groups.google.com/d/optout.

Justin Israel

unread,
Dec 4, 2014, 3:41:56 PM12/4/14
to python_in...@googlegroups.com
That is an interesting point you have discovered. A set (and a dict) rely on the hash of the object, whereas doing an "in" membership test in a list rely on the equality of the two objects. 

Given two MObject instances that point to the same Maya object:

a == b
# True

hash(a) == hash(b)
# False

This means that the MObject only defines the equality operators, but their hash returns different values, making them useless for sets. It is kind of lame that the MObjects are that way. It would work fine if you were dealing with containers all pointing as the same MObject instances. But if you have containers that have MObject results from different calls, then it won't work. The closest thing they have seems to be this:

om.MObjectHandle(a).hashCode() == om.MObjectHandle(b).hashCode()
# True

... where they make you go and retrieve the hash code for your object, as opposed to just making SWIG do it for you in the __hash__() method of the python wrapper. 


To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.
--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.
--
Christopher Crouzet
http://christophercrouzet.com

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.



--
Marcus Ottosson
konstr...@gmail.com

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.



--
Christopher Crouzet
http://christophercrouzet.com

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.



--
Marcus Ottosson
konstr...@gmail.com

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.



--
Christopher Crouzet
http://christophercrouzet.com

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.
--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.



--
Christopher Crouzet
http://christophercrouzet.com

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

This email is free from viruses and malware because avast! Antivirus protection is active.


--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.
--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/CANuKW53QfHPpzdqsPpMAHPK14GrA8NnUMf0CrnEL3kPg-MKSJw%40mail.gmail.com.

Christopher Crouzet

unread,
Dec 7, 2014, 4:47:49 AM12/7/14
to python_in...@googlegroups.com
Interesting! I would never have think that hash values would differ for a same object, how lame indeed.
I wasn't even aware of the existance of the class `MObjectHandle`. It seems to be as much of a joke as the `MScriptUtil` class is.

After all I'm not even surprised anymore and that's why I originally started to develop a monkey patching library similar to what the `banana.maya` one is today.

To make good use of your findings, I've made changes to the `banana.maya` library to cover this case by monkey patching the original `__hash__()` method. In normal cases it's highly discouraged to override existing methods through monkey patching but I don't see how it could do any harm here—how could one possibly rely on its original behavior? And at the end of the day, no one's using my library so I'm not risking to break things! :)


This indeed seems to fix the initial issue with the set.


To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/CAPGFgA1f630D6msNd42eFSEYgVcWFGp-rQQ7fjx9GTCWZLdvng%40mail.gmail.com.

For more options, visit https://groups.google.com/d/optout.

Nicolas Combecave

unread,
Dec 7, 2014, 7:15:36 AM12/7/14
to python_in...@googlegroups.com
Just to go a little further deep in the OT zone, I found this lecture very interesting, as it explains how the dictionnaries work behind the scenes:

Reply all
Reply to author
Forward
0 new messages