Creating a graph in VTK - python-3.x

I want to create a graph using VTK class https://lorensen.github.io/VTKExamples/site/Python/Graphs/ConstructGraph/
def main():
g = vtk.vtkMutableUndirectedGraph()
v1 = g.AddVertex()
v2 = g.AddVertex()
g.AddEdge ( v1, v2 )
print ('Number of vertices:', g.GetNumberOfVertices())
print ("Number of edges:", g.GetNumberOfEdges())
g.AddEdge ( v1, v2 )
print ('Number of vertices:', g.GetNumberOfVertices())
print ('Number of edges:', g.GetNumberOfEdges())
graphLayoutView = vtk.vtkGraphLayoutView()
graphLayoutView.AddRepresentationFromInput(g)
graphLayoutView.ResetCamera()
graphLayoutView.Render()
graphLayoutView.GetInteractor().Start()
is the function defined. But I not quite sure how to use this.
For instance, in networkx I would do
t = [0, 2, 4, 5, 6, 8, 9, 11, 13, 1, 10, 1, 3, 7]
h= [1, 3, 3, 1, 7, 7, 10, 12, 12, 14, 14, 12, 14, 10]
ed_ls = [(x, y) for x, y in zip(tail, head)]
G = nx.OrderedGraph()
G.add_edges_from(ed_ls)
nx.draw(G)
Suggestions on how to create the same graph in VTK will be helpful

You already found the correct API. Just have to use it. Something like
g = vtk.vtkMutableUndirectedGraph()
# add your 15 vertices
for i in range(15):
g.AddVertex()
t = [0, 2, 4, 5, 6, 8, 9, 11, 13, 1, 10, 1, 3, 7]
h= [1, 3, 3, 1, 7, 7, 10, 12, 12, 14, 14, 12, 14, 10]
for start, end in zip(t,h):
g.AddEdge( start, end )

Related

When i use set( list_a + list_b ) it returns a dictionary. Do sets naturally return dictionaries?

I'm doing some beginner python exercises and one of them is to remove duplicates from a list. I've successfully done it, but the strange thing is that it is returning a dictionary instead of a list.
This is my code.
import random
a = []
b = []
for i in range(0,20):
n = random.randint(0,10)
a.append(n)
for i in range(0,20):
n = random.randint(0,10)
b.append(n)
print(sorted(a))
print(sorted(b))
c = set(list(a+b))
print(c)
and this is what it's spitting out
[0, 0, 1, 1, 1, 1, 2, 3, 4, 4, 6, 6, 7, 7, 7, 8, 9, 9, 10, 10]
[0, 1, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 7, 8, 9, 9, 10, 10, 10]
{0, 1, 2, 3, 4, 6, 7, 8, 9, 10}
thanks in advance!
{0, 1, 2, 3, 4, 6, 7, 8, 9, 10} is a set, not a dictionary, a dictionary would be printed as {key:value, key:value, ...}
Try print(type(c)) and you'll see it prints <class 'set'> rather than <class 'dict'>
Also try the following
s = {1,2,3}
print(type(s))
d = {'a':1,'b':2,'c':3}
print(type(d))
You'll see the type is different

PyTorch: How to insert before a certain element

Currently I have a 2D tensor, for each row, I want to insert a new element e before the first index of a specified value v. Additional information: cannot guarantee each row could have a such value. If there isn't, just append the element
Example: Supporse e is 0, v is 10, Given a tensor
[[9, 6, 5, 4, 10],
[8, 7, 3, 5, 5],
[4, 9, 10, 10, 10]]
I want to get
[[9, 6, 5, 4, 0, 10],
[8, 7, 3, 5, 5, 0],
[4, 9, 0, 10, 10, 10]]
Are there some Torch-style ways to do this? The worst case I can treat this as a trivial Python problem but I think the corresponding solution is a little time-consuming.
I haven't yet found a full PyTorch solution. I'll keep looking, but here is somewhere to start:
>>> v, e = 10, 0
>>> v, e = torch.tensor([v]), torch.tensor([e])
>>> x = torch.tensor([[ 9, 6, 5, 4, 10],
[ 8, 7, 3, 5, 5],
[ 4, 9, 10, 10, 10],
[10, 9, 7, 10, 2]])
To deal with the edge case where v is not found in one of the rows you can add a temporary column to x. This will ensure every row has a value v in it. We will use x_ as a helper tensor:
>>> x_ = torch.cat([x, v.repeat(x.size(0))[:, None]], axis=1)
tensor([[ 9, 6, 5, 4, 10, 10],
[ 8, 7, 3, 5, 5, 10],
[ 4, 9, 10, 10, 10, 10],
[10, 9, 7, 10, 2, 10]])
Find the indices of the first value v on each row:
>>> bp = (x_ == v).int().argmax(axis=1)
tensor([4, 5, 2, 0])
Finally, the easiest way to insert values at different positions in each row is with a list comprehension:
>>> torch.stack([torch.cat([xi[:bpi], e, xi[bpi:]]) for xi, bpi in zip(x, bp)])
tensor([[ 9, 6, 5, 4, 0, 10],
[ 8, 7, 3, 5, 5, 0],
[ 4, 9, 0, 10, 10, 10],
[ 0, 10, 9, 7, 10, 2]])
Edit - If v cannot occur in the first position, then no need for x_:
>>> x
tensor([[ 9, 6, 5, 4, 10],
[ 8, 7, 3, 5, 5],
[ 4, 9, 10, 10, 10]])
>>> bp = (x == v).int().argmax(axis=1) - 1
>>> torch.stack([torch.cat([xi[:bpi], e, xi[bpi:]]) for xi, bpi in zip(x, bp)])
tensor([[ 9, 6, 5, 0, 4, 10],
[ 8, 7, 3, 5, 0, 5],
[ 4, 0, 9, 10, 10, 10]])

Python3 cross multiplication among tuples

I need to multiply the number in each tuple, not the order i[0] * j[0] and i[1] * j[1], but i[0] * i[0], i[0] * j[1], i[0] * j[2] and so on.
Moreover, I need to add the number as well, such as i[0] + i[0], i[0] + j[1], i[0] + j[2] and so on.
Is there an easy way to do this, instead of my code below that needs a lot of for?
dice1 = (1, 2, 3, 4)
dice2 = (1, 2, 3, 4, 5, 6, 7, 8)
dice3 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
dice4 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
dice5 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
dice6 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
myList = []
comp = []
d = 0
e = 0
for i in dice1:
for j in dice2:
d = i * j
myList.append(d)
e = len(myList)
comp.append(e)
You can utilize the itertools product function as follows:
from itertools import product
dice1 = (1, 2, 3, 4)
dice2 = (1, 2, 3, 4, 5, 6, 7, 8)
dice3 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
dice4 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
dice5 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
dice6 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
myList = []
comp = []
myList = [k[0] * k[1] for k in product(dice1, dice2)]
comp.append(len(myList)

Python for loop one-line difference from regullar

I just came up with a difference between one line and regular for loop.
As an example;
obs = [6, 12, 8, 10, 20 16]
freq = [5, 4, 3, 2, 1, 5]
data = []
data.extend(obs[i:i+1] * freq[i] for i in range(len(obs)))
outputs
[[6, 6, 6, 6, 6], [12, 12, 12, 12], [8, 8, 8], [10, 10], [20], [16, 16, 16, 16, 16]]
However,
for i in range(len(obs)):
data.extend(obs[i:i+1] * freq[i])
outputs
[6, 6, 6, 6, 6, 12, 12, 12, 12, 8, 8, 8, 10, 10, 20, 16, 16, 16, 16, 16]
Can someone kindly explain what causes this?
extending x by y means appending each entry of y to x.
Since the entries of obs[i:i+1] * freq[i] for i in range(len(obs)) are lists of integers, data.extend(obs[i:i+1] * freq[i] for i in range(len(obs))) will append of lists of integers to data, not integers.
On the other hand, the elements of obs[i:i+1] * freq[i] are integers, and therefore data.extend(obs[i:i+1] * freq[i]) will append integers to data.
This would generate the same output as the one-liner:
obs = [6, 12, 8, 10, 20, 16]
freq = [5, 4, 3, 2, 1, 5]
data = []
for i in range(len(obs)):
data.extend([obs[i:i+1] * freq[i]])

Swap pair of elements along an axis

I have a 2d numpy array as such:
import numpy as np
a = np.arange(20).reshape((2,10))
# array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
I want to swap pairs of elements in each row. The desired output looks like this:
# array([[ 9, 0, 2, 1, 4, 3, 6, 5, 8, 7],
# [19, 10, 12, 11, 14, 13, 16, 15, 18, 17]])
I managed to find a solution in 1d:
a = np.arange(10)
# does the job for all pairs except the first
output = np.roll(np.flip(np.roll(a,-1).reshape((-1,2)),1).flatten(),2)
# first pair done manually
output[0] = a[-1]
output[1] = a[0]
Any ideas on a "numpy only" solution for the 2d case ?
Owing to the first pair not exactly subscribing to the usual pair swap, we can do that separately. For the rest, it would relatively straight-forward with reshaping to split axes and flip axis. Hence, it would be -
In [42]: a # 2D input array
Out[42]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
In [43]: b2 = a[:,1:-1].reshape(a.shape[0],-1,2)[...,::-1].reshape(a.shape[0],-1)
In [44]: np.hstack((a[:,[-1,0]],b2))
Out[44]:
array([[ 9, 0, 2, 1, 4, 3, 6, 5, 8, 7],
[19, 10, 12, 11, 14, 13, 16, 15, 18, 17]])
Alternatively, stack and then reshape+flip-axis -
In [50]: a1 = np.hstack((a[:,[0,-1]],a[:,1:-1]))
In [51]: a1.reshape(a.shape[0],-1,2)[...,::-1].reshape(a.shape[0],-1)
Out[51]:
array([[ 9, 0, 2, 1, 4, 3, 6, 5, 8, 7],
[19, 10, 12, 11, 14, 13, 16, 15, 18, 17]])

Resources