Using Python's Networkx library, I created an undirected graph to represent a relationship network between various people. A snippet of my code is below:
import networkx as nx
def creategraph(filepath):
G=nx.Graph()
#All the various nodes and edges are added in this stretch of code.
return G
From what I understand, each node is basically a dictionary. The problem that this presents to me is that I want to perform a different kind of Random Walk algorithm. Now before you jump on me and tell me to use one of the standard functions of the Networkx library, I want to point out that it is a custom algorithm. Suppose I run the creategraph function, and the G object is returned and stored in another object (let's call it X). I want to start off at a node called 'Bob.' Bob is connected to Alice and Joe. Now, I want to reassign Y to point to either Alice or Bob at random (with the data I'm dealing with, a given node could have hundreds of edges leaving it). How do I go about doing this? Also, how do I deal with unicode entries in a given node's dict (like how Alice and Joe are listed below?)
X = creategraph("filename")
Y=X['Bob']
print Y
>> {u'Alice': {}, u'Joe': {}}
The choice function in the random module could help with the selection process. You don't really need to worry about the distinction between unicode and string unless you're trying to write them out somewhere as sometimes unicode characters aren't translatable into the ASCII charset that Python defaults to.
The way you'd use random.choice would be something along the lines of:
Y = Y[random.choice(Y.keys())]
Related
In abaqus Python script, several Plies have a large number of copies, each of which has many fibers. In each Fiber, a set of edges has been selected: App1-1, App1-2, ..., App99-1, App99-2, ..., App99-88. How to create a new set that will contain all or some of these set of edges?
Thank you.
Code:
allApps=[]
...
for i in range(Plies):
...
for j in range (Fiber):
appSet = Model.rootAssembly.Set(edges=
Model.rootAssembly.instances['Part'+str(i+1)+'-'+str(1+j)].edges[0:0+1],
name='App'+str(i+1)+'-'+str(1+j))
allApps.append(appSet)
I can guess it should be something like this:
Model.rootAssembly.Set(name='allAppEdges', edges=.?.Array(allApps))
but I'm not sure about this and I have no idea about correct syntax
I tested the following on a simple part and it worked for me. I think you could adapt this to achieve what you're trying to do for your specific model. The key is the part.EdgeArray type. For whatever reason Abaqus requires your edges be supplied within that type, rather than a simple list or tuple. The Abaqus documentation is not clear on this, and when you pass a list of edges it will fail with a vague error: Feature creation failed.
from abaqus import *
import part
mdl = mdb.models['Model-1']
inst = mdl.rootAssembly.instances['Part-1-1']
# Loop through all edges in the instance and add them to a list
my_edges = []
for e in inst.edges:
my_edges.append(e)
# Create a new set with these edges
#mdl.rootAssembly.Set(name='my_edges', edges=my_edges) # This will fail because my_edges needs to be an EdgeArray
mdl.rootAssembly.Set(name='my_edges', edges=part.EdgeArray(my_edges))
For others that may find themselves here - similar types are available for vertices, faces, and cells: part.VertexArray, part.FaceArray, and part.CellArray.
I tried to create a LP model by using pyomo.environ. However, I'm having a hard time on creating sets. For my problem, I have to create two sets. One set is from a bunch of nodes, and the other one is from several arcs between nodes. I create a network by using Networkx to store my nodes and arcs.
The node data is saved like (Longitude, Latitude) in tuple form. The arcs are saved as (nodeA, nodeB), where nodeA and nodeB are both coordinates in tuple.
So, a node is something like:
(-97.97516252657978, 30.342243012086083)
And, an arc is something like:
((-97.97516252657978, 30.342243012086083),
(-97.976196300350608, 30.34247219922803))
The way I tried to create a set is as following:
# import pyomo.envrion as pe
# create a model m
m = pe.ConcreteModel()
# network is an object I created by Networkx module
m.node_set = pe.Set(initialize= self.network.nodes())
m.arc_set = pe.Set(initialize= self.network.edges())
However, I kept getting an error message on arc_set.
ValueError: The value=(-97.97516252657978, 30.342243012086083,
-97.976196300350608, 30.34247219922803) does not have dimension=2,
which is needed for set=arc_set
I found it's weird that somehow my arc_set turned into one tuple instead of two. Then I tried to convert my nodes and arcs into string but still got the error.
Could somebody show me some hint? Or how do delete this bug?
Thanks!
Underneath the hood, Pyomo "flattens" all indexing sets. That is, it removes nested tuples so that each set member is a single tuple of scalar values. This is generally consistent with other algebraic modeling languages, and helps to make sure that we can consistently (and correctly) retrieve component members regardless of how the user attempted to query them.
In your case, Pyomo will want each member of the the arc set as a single 4-member tuple. There is a utility in PyUtilib that you can use to flatten your tuples when constructing the set:
from pyutilib.misc import flatten
m.arc_set = pe.Set(initialize=(tuple(flatten(x)) for x in self.network.edges())
You can also perform some error checking, in this case to make sure that all edges start and end at known nodes:
from pyutilib.misc import flatten
m.node_set = pe.Set( initialize=self.network.nodes() )
m.arc_set = pe.Set(
within=m.node_set*m.node_set,
initialize=(tuple(flatten(x)) for x in self.network.edges() )
This is particularly important for models like this where you are using floating point numbers as indices, and subtle round-off errors can produce indices that are nearly the same but not mathematically equal.
There has been some discussion among the developers to support both structured and flattened indices, but we have not quite reached consensus on how to best support it in a backwards compatible manner.
I have a large tab2 file that I have imported in python. In the 15th and 16th column of the file- individual, cellular interactions are documented in a descending format like so:
Protein A Protein B
A1 B1
A2 B2
etc. so A1 interacts with B1 and so on....
I need to extract these interactions into lists- "dataA and dataB" (although I'll be doing it in files later).
However once I have done this what I need to use these lists/ files to create a graph to represent the overall pathway (using networkx). So I figure that I need to bind the lists in such a way that A1 will be across from B1- it's interactor....
I would do it in some way similar to this:
a = numpy.Protein A(1000)
b = numpy.Protein B(1000)
numpy.column_stack((a,b))
However this numpy created array may not be suitable for input into networkx as I am told that networkx requires it's input in tuples for the command e.g.
"G.add_edges_from([(1,2),(1,3)])"....
So my question is: am I going about this the right way? Or should I be concentrating first on getting the data into networkx in away that suits networks? Or is there some way that I'm not considering to enter my data into it networkx as an array?
All you need to do is the following:
1) iterate through your list of interactions and build a list of proteins by appending the protein names to a list.
2) after creating a networkx object, for each node, use add_node to add it to the network.
3) Iterate again through your original interaction list, and use add_edge to draw connections between the nodes.
No need to use numpy at all
I'm writing a function that receives a graph as input.
The very first thing I need to do is determine the order of the graph (that is, the number of vertices in the graph).
I mean, I could use g.summary() (which returns a string that includes the number of vertices), but then I'd have parse the string to get at the number of vertices -- and that's just nasty.
To get the number of edges I'm using len(g.get_edgelist()), which works. But there is no g.get_vertexlist(), so I can't use the same method.
Surely there is an easy way to do this that doesn't involve parsing strings.
g.vcount() is a dedicated function in igraph that returns the number of vertices. Similarly, g.ecount() returns the number of edges, and it is way faster than len(g.get_edgelist()) as it does not have to construct the full edge list in advance.
As some functions in igraph have been renamed in meantime, I found the answers here out of date. What the docs suggest now is calling
gorder(g)
which works for me. Analogy for ecount is
gsize(g) # vcount(g) still works, but not g.vcount()
It's useful to note that help pages are cleverly redirected, so
?vcount
brings you to gorder docs etc.
g.vs should return the sequence of vertices as an igraph.VertexSeq object:
>>> from igraph import Graph
>>> g = Graph.Formula("A-B")
>>> g.vs["name"]
['A', 'B']
>>> len(g.vs)
2
>>> g.vcount()
2
Edit: As #Tamas mentions below, g.vcount() will also return the number of vertices. Example edited to account for this.
I am writing a custom export script to parse all the objects in a blender file, filter them by name, then check to make sure that they meet some specific criteria.
I am using Blender 2.68a. I've created a blender file with some basic 2d and 3d meshes, as well as some that should fail my test criteria. I am working in the internal Python console inside of Blender. This is the only way to work with the blender python API, as their python environment is customized.
I've sorted how to iterate through the objects using a for loop and the D.objects iterator, then check for name matches using regular expressions, and then get a mesh from the object using:
mesh = obj.to_mesh(C.scene, True, 'RENDER') #where obj is an bpy.data.object[index] in the scene
mesh.update(True, True)
mesh.polygons[index].<long list of possible functions>
lets me access an array of polygons to know if there is a set of vertices with edges that form a polygon, and what their key values are.
What I can't sort out is how to determine from the python console if a poly is a face or just a poly. Is there a built in function, or what tests can i perform to programmatically determine this? For example, I can have a mesh 4 vertices with 4 edges that do not have a face, and I do not want to export this, but if i were to edit the same 4 vertices/edges and put a face on it, then it becomes a desirable export.
Can anyone explain the bpy.data.object data structure or explain where the "faces" are stored? it seems as though it would be a property of the npolys themselves, but the API does not make it obvious. Any assistance in clarifying this would be greatly appreciated. Cheers.
So, i asked this question on the blender.org forums, http://www.blender.org/forum/viewtopic.php?t=28286&postdays=0&postorder=asc&start=0 and a very helpful individual has helped me over the past few days each time I got stuck in my own efforts to plow through this.
The short list of answers is:
1) All polygons are faces. If it isnt stored as a polygon, it isnt a face.
2) using the to_mesh() function on an object returns a copy of the function, and so any selections that are done to the copy are not reflected by the context and therefore the methodology I was using was flawed. The only way to access the live object is through use of:
bpy.data.objects[<index or object name>].data.vertices[<index>].co[<0,1,2> which correspond to x,y,z respectively]
bpy.data.objects[<index or object name>].data.polygons[<index>].edge_keys
The first one gives you access to an ordered index of all the vertices in the object(assuming it is of type 'MESH'), and their coordinates.
The second one gives you access to an 2d array of ordered pairs which represent edges. The numbers it contains within the tuples correspond to the index value in the vertices list from the first command, and so you can get the coordinates which the edge goes between.
One can also create a new BMesh object and copy the object you are interested in into the BMesh. This gives you a lot more functionality that you can't access on the live object. The code in answer 3 shows an example of this.
3)see below for answer to my question regarding checking faces in a mesh.
it turns out that one way to determine if an object has faces and all edges are a part of a face is to use the following code snippet written by a helpful user, CoDEmanX on the above thread.
import bpy, bmesh
for ob in bpy.context.scene.objects:
if ob.type != 'MESH':
continue
bm = bmesh.new()
bm.from_object(ob, bpy.context.scene)
if len(bm.faces) > 0 and 0 not in (len(e.link_faces) for e in bm.edges):
print(ob.name, "is valid")
else:
print(ob.name, "has errors")
I changed this a little bit, as i didnt want it to loop through all the objects, and instead i've got this as a function that returns true if the object passed in is valid and false otherwise. This lets me serialize my calls so that my addon only tries to validate the objects which have a name which matches a regex.
def validate(obj):
import bpy, bmesh
if obj.type == 'MESH':
bm = bmesh.new()
bm.from_object(obj, bpy.context.scene)
if len(bm.faces) > 0 and 0 not in (len(e.link_faces) for e in bm.edges):
return True
return False