How to convert3D model to 2D blueprint - dictionary

I want to convert 3D model to 2D blueprint using python or any algorithm.
I'm still looking for a way to make it happen

In python you can use the bmesh module to extract the edges from a mesh.
import bpy
import bmesh
def get_edges(obj):
bm = bmesh.new()
bm.from_mesh(obj.data)
edges = [e for e in bm.edges]
bm.free()
return edges
edges = get_edges(bpy.context.object)
You can then use the bgl module to draw the edges on the screen.
import bgl
def draw_edges(edges):
bgl.glEnable(bgl.GL_BLEND)
bgl.glLineWidth(2)
bgl.glBegin(bgl.GL_LINES)
bgl.glColor4f(1, 0, 0, 1)
for e in edges:
bgl.glVertex3f(*e.verts[0].co)
bgl.glVertex3f(*e.verts[1].co)
bgl.glEnd()
bgl.glLineWidth(1)
bgl.glDisable(bgl.GL_BLEND)
draw_edges(edges)

Related

How to get the length of lines representing edges in the plot of graph after layout out using networkx

For a graph in networkx, I have made a layout to draw a network graph using code below:
data = pd.read_csv('data\\email-dept3.csv')
edges = [edge for edge in zip(data['source'],data['target'])]
print(len(edges))
G = nx.Graph()
G.add_edges_from(edges)
node_pos = nx.kamada_kawai_layout(G)
#I want to get the edge length as one attributes, but I don't know how to code this function
edge_length = calculate_edge_length()
nx.draw_networkx_nodes(G,node_pos,**options)#draw nodes
[nx.draw_networkx_edges(G,node_pos,edgelist=[key],alpha=np.amin([1,value*100]),width=2) for key,value in cent.items()]
plt.show()
And the result is:
What I want to do is get the every edge's length in this graph. Because after layout, every node has a position in screen, and the edge has its length according to its two nodes' position. But in networkx's API, I can't find the method to get the edge's length. And I also don't know how to calculate this value.
If you need more information, please contact me.
I am trying all kinds of methods to adjust the transparency of edges. The length of line is one of my consideration.
Interesting idea! Seems like a worthwhile experiment; I'll let you decide if it works well or not. :-)
But in networkx's API, I can't find the method to get the edge's length
I think you have to compute them yourself. Fortunately, that's not too hard. Here's an example.
import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (10,10)
def example_graph():
"""
Return the classic Karate Club network, but give text labels to the nodes.
"""
labels = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJZKLMNOPQRSTUVWXYZ'
kg = nx.karate_club_graph()
edges = [(labels[i], labels[j]) for i,j in kg.edges()]
G = nx.Graph()
G.add_edges_from(edges)
return G
# Test network
G = example_graph()
# Determine layout node positions
node_pos = nx.kamada_kawai_layout(G)
# Determine edge distances (from the node positions)
node_pos_df = pd.DataFrame(node_pos.values(), columns=['x', 'y'], index=node_pos.keys())
node_pos_df = node_pos_df.rename_axis('label').sort_index()
edges = np.array(G.edges())
u_pos = node_pos_df.loc[edges[:, 0]].values
v_pos = node_pos_df.loc[edges[:, 1]].values
distances = np.linalg.norm(u_pos - v_pos, axis=1)
## Optional: Add the distances as edge attributes
#edge_distances = {(u,v): d for (u,v), d in zip(G.edges(), distances)}
#nx.set_edge_attributes(G, edge_distances, "layout_distance")
# Compute alpha: Set 0.15 as minimum alpha, 1.0 as maximum alpha
d_min, d_max = distances.min(), distances.max()
alphas = 1.0 - 0.85 * (distances - d_min) / (d_max - d_min)
# Draw graph
nx.draw_networkx_nodes(G, node_pos)
nx.draw_networkx_edges(G, node_pos, edgelist=G.edges(), alpha=alphas, width=2)
plt.show()

3-dimensional graph LightGraphs/GraphPlot/Julia or Networkx/Python

I am wondering whether it is possible to plot a vertical bar over a 2-dimensional representation of a graph. Say I have a tree and I want to associate with any node a "potential" which can be represented as a vertical bar.
NetworkX can do that using the matplotlib drawing tools because the result is a matplotlib figure on which you can use matplotlib to draw anything else you'd like on top of the networkx drawing of the graph.
nx.draw(G)
mpl.plot([xpt, xpt], [ymin, ymax], '--b')
mpl.show()
This is a minimal example which does what I was looking for (in Python):
import networkx as nx
import random
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
degree = 3
N = 10
g = nx.random_regular_graph(degree, N)
fig = plt.figure(figsize=(10,7))
ax = Axes3D(fig)
for i,j in enumerate(g.edges()):
x = np.array((positions[j[0]][0], positions[j[1]][0]))
y = np.array((positions[j[0]][1], positions[j[1]][1]))
ax.plot(x, y, c='black', alpha=0.5)
for key, value in positions.items():
xi = value[0]
yi = value[1]
# Scatter plot
ax.scatter(xi, yi, c= 'red')
ax.bar3d(xi, yi, 0, 0.01, 0, random.random(), shade=False)
ax.set_axis_off()
It generates this kind of plot, which can be useful to represent additional information on a graph

Visualizing agents using Mesa & Networkx

I'm current doing a multi agent path finding using Mesa and Networkx. The nodes represent location where only 1 agent can reside at one point of time. The edges represent distance between the nodes. How do I visualize the moving of agents along the edges at each time step? For example at time step = 4, Agent A is in the middle of edge connecting node 1 and 2.
I guess you want to plot some agent traversing between the nodes using networkx and matplotlib.
import matplotlib.pyplot as plt
import networkx as nx
import matplotlib.animation as animation
import matplotlib
import numpy as np
matplotlib.use('TkAgg')
plt.ion()
H = nx.octahedral_graph() # generate a random graph
pos = nx.spring_layout(H, iterations=200) # find good positions for nodes
In order to do that, first we need to know the position of the agent in each step or frame while traversing. If we assume that there are 50 steps between each node (or on each edge), we can write a generator to update the agent's position in each frame:
def traverse(graph, start, end, steps_between_nodes=50):
"""Generate the new position of the agent.
:param graph: the graph you want to put your agent to traverse on.
:param start: the node to start from.
:param end: the node to end at.
:param steps_between_nodes: number of steps on each edge.
"""
steps = np.linspace(0, 1, steps_between_nodes)
# find the best path from start to end
path = nx.shortest_path(graph, source=start, target=end)
stops = np.empty((0, 2))
for i, j in zip(path[1:], path):
# get the position of the agent at each step
new_stops = steps[..., None] * pos[i] + (1 - steps[..., None]) * pos[j]
stops = np.vstack((stops, new_stops))
for s in stops:
yield s
Then we can animate it as follows:
agent_pos = traverse(H, 1, 4) # make an agent traversing from 1 to 4
def update_position(n):
plt.cla()
nx.draw(H, pos, node_size=700, with_labels=True, node_color='green')
c = plt.Circle(next(agent_pos), 0.05, color='purple', zorder=2, alpha=0.7)
plt.gca().add_patch(c)
ani = animation.FuncAnimation(plt.gcf(), update_position, interval=30, repeat=False)
plt.ioff()
plt.show()
Finally we will have something like this:

Generating a complete graph in metric space

Please help with the simplest way to generate a complete random weighted undirected graph given size N, so that weights form a metric space (obey triangle inequality). I know there is networkx library but not sure how to do this.
Although #SvenMarnach is correct, I thought I would mention that it is pretty easy to initialize a graph from a distance matrix in networkx:
import numpy as np
import networkx as nx
V = 100 # number of nodes
D = 2 # dimensionality
positions = np.random.rand(V, D)
differences = positions[:, None, :] - positions[None, :, :]
distances = np.sqrt(np.sum(differences**2, axis=-1)) # euclidean
# create a weighted, directed graph in networkx
graph = nx.from_numpy_matrix(distances, create_using=nx.DiGraph())

trajectory of bullet, when there is a drag force

i tried to express the trajectory of bullet when there is a drag force.
however, i am not able to express the graph precisely.
how to depict trajectory from ode equation?.
this is my graph. this graph does not plausible. although i struggled setting different sign of vydot value, this is not working correctly.
from pylab import*
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np
g=10
m=1
k=0.01
y=zeros([2])
vy0=0
vydot=200
vx0=0
vxdot=200
y[0]=vy0
y[1]=vydot
x=zeros([2])
x[0]=vx0
x[1]=vxdot
t=linspace(0,1000,5000)
def fy(y,t):
g0=y[1]
g1=-k*y[1]
return array([g0,g1])
def fx(z,t):
g0=-x[1]
g1=-k*(x[1])-g
return array([g0,g1])
ans1=odeint(fy,y,t)
ans2=odeint(fx,x,t)
ydata=(ans1[:,])
xdata=(ans2[:,])
plt.plot(ydata,xdata)
show()"""
In air, as opposed to liquids, the bullet not only displaces the volume along its path, but also increases the impulse of the displaced air molecules proportional to the velocity. Thus the drag force is
vn=sqrt(vx²+vy²)
dragx = -k*vn*vx
dragy = -k*vn*vy
Thus use
def f(z,t):
x,y,vx,vy = z
vn = sqrt(vx*vx+vy*vy)
return array([vx, vy, -k*vn*vx, -k*vn*vy-g ])
For a first overview, consider the problem without drag. Then the solution is
x(t) = vx*t = 200m/s*t
y(t) = vy*t-g/2*t² = 200m/s*t - 5m/s²*t²
y(t)=0 is again met for t=2*vy/g at the x coordinate 2*vx*vy/g = 8000m. Maximum height is reached for t=vy/g at height vy²/(2g)=2000m.

Resources