Using Manim, can I draw a new object in the background of existing ones? - manim

I have illustrated the parallelogram spanned by two vectors, and would like to shade in the area of that parallelogram, which I tried to do like so:
from manim import *
import numpy as np
class DrawParallelogram( Scene ):
def construct( self ):
o = np.array( [ 0, -2, 0 ] )
p1 = np.array( [ 3, 1, 0 ] ) # u
p2 = np.array( [ 1, 3, 0 ] ) # v
op1 = o + p1
op2 = o + p2
op3 = o + p1 + p2
v1 = Arrow( start = o, end = op1, buff = 0, color = RED ) # u
v2 = Arrow( start = o, end = op2, buff = 0, color = YELLOW ) # v
v1p = Arrow( start = op2, end = op3, buff = 0, color = RED ) # u'
v2p = Arrow( start = op1, end = op3, buff = 0, color = YELLOW ) # v'
parallelogram = [ o, op1, op3, op2 ]
poly = Polygon( *parallelogram, color = PURPLE, fill_opacity = 0.5 )
self.play( AnimationGroup( Write( v1 ), Write( v2 ), Write( v1p ), Write( v2p ) ) )
self.wait( )
self.play( Write( poly ) )
However, this parallelogram colors over the arrows that I have already drawn, like so:
and I'd like it to be in the background. Is there a way to introduce a new object into the scene so that it is logically behind any of the existing ones, as if I had drawn it first, so that it would look like:

You can use the set_z_index method to set the z_index property of the parallelogram to a value less than that of the arrows.
Here I have set it to a lower value than that of v1:
poly.set_z_index(v1.z_index - 1)
Alternatively you can manipulate the z_index property directly:
poly.z_index = v1.z_index - 1
Using the set_z_index method would be the cleaner solution.
Complete code:
from manim import *
import numpy as np
class DrawParallelogram( Scene ):
def construct( self ):
o = np.array( [ 0, -2, 0 ] )
p1 = np.array( [ 3, 1, 0 ] ) # u
p2 = np.array( [ 1, 3, 0 ] ) # v
op1 = o + p1
op2 = o + p2
op3 = o + p1 + p2
v1 = Arrow( start = o, end = op1, buff = 0, color = RED ) # u
v2 = Arrow( start = o, end = op2, buff = 0, color = YELLOW ) # v
v1p = Arrow( start = op2, end = op3, buff = 0, color = RED ) # u'
v2p = Arrow( start = op1, end = op3, buff = 0, color = YELLOW ) # v'
parallelogram = [ o, op1, op3, op2 ]
poly = Polygon( *parallelogram, color = PURPLE, fill_opacity = 0.5 )
# Set the z-index
poly.set_z_index(v1.z_index - 1)
self.play( AnimationGroup( Write( v1 ), Write( v2 ), Write( v1p ), Write( v2p ) ) )
self.wait( )
self.play( Write( poly ) )

Related

Finding the total weight in MST in Prim's Algorithm

currently I'm making a comparison between the Prim's Algorithm and Kruskal's Algorithm. Both codes are from GeeksforGeeks, however only the Kruskal's algorithm has the total calculated weight in finding the MST. The Prim's algorithm doesn't have one, and I don't have any idea on how can I output the total weight. I hope you can help me.
Here's the code for the Kruskal's Algorithm (from GeeksforGeeks):
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def KruskalMST(self):
result = []
i = 0
e = 0
self.graph = sorted(self.graph,
key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e = e + 1
result.append([u, v, w])
self.union(parent, rank, x, y)
minimumCost = 0
print("Edges in the constructed MST")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Spanning Tree", minimumCost)
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.KruskalMST()
The code for Prim's Algorithm (also from GeeksforGeeks):
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
minimumcost = 0
def printMST(self, parent):
print ("Edge \tWeight")
for i in range(1, self.V):
print (parent[i], "-", i, "\t", self.graph[i][parent[i]])
def minKey(self, key, mstSet):
min = sys.maxsize
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
def primMST(self):
key = [sys.maxsize] * self.V
parent = [None] * self.V
key[0] = 0
mstSet = [False] * self.V
parent[0] = -1
for cout in range(self.V):
u = self.minKey(key, mstSet)
mstSet[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u
self.printMST(parent)
g = Graph(5)
g.graph = [ [0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
g.primMST();

GLua - part of the string library

I have gui wherein I need show information from table
When I open gui, I have this error:
"attempt to index a string value with bad key ('Index' is not part of the string library)"
SH file. In this file I put table information
MyList = {}
MyList = {
Index = 1,
Name = "Name 1",
Class = "exampleclass",
Description = "Desc 1",
Model = "modelname",
Color = Color(255, 255, 255, 255)
}
CL file. This file contains the part of the code where the error occurs. The error occurs on the first line
for k, v in SortedPairsByMemberValue( MyList, "Index" ) do
if v.Class == "exampleclass" then
local mainbuttons = vgui.Create( "DCollapsibleCategory", category )
mainbuttons:Dock(TOP)
mainbuttons:DockMargin(0, 6, 0, 2)
mainbuttons.Header:SetTall(24)
mainbuttons:SetExpanded(0)
mainbuttons:SetLabel("")
mainbuttons.Text = v.Name
function mainbuttons:Paint(w, h)
local h = 24
surface.SetDrawColor(v.Color)
surface.DrawRect(0, 0, w, h)
surface.SetFont("NovuxFont.ArialLight.16")
local textw, texth = surface.GetTextSize(self.Text)
surface.SetTextColor(Color(255, 255, 255))
surface.SetTextPos(16, h / 2 - texth / 2)
surface.DrawText(self.Text)
end
local craftpanel = vgui.Create( "DPanel", mainbuttons )
craftpanel:SetPos( 0, 25 )
craftpanel:SetSize( mainframescroll:GetWide(), 250 )
craftpanel.Paint = function() -- Paint function
surface.SetDrawColor( 65, 65, 65, 0 )
surface.DrawRect( 0, 0, craftpanel:GetWide(), craftpanel:GetTall() )
end
local spoilertext = vgui.Create( "DLabel", mainbuttons )
spoilertext:SetText( v.Description )
spoilertext:SetTextColor( Color( 255, 255, 255 ) )
spoilertext:SetFont( "NovuxFont.ArialLight.16" )
spoilertext:SetPos( 108, 32 )
spoilertext:SetSize( mainframescroll:GetWide(), 25 )
spoilertext.Paint = function( self, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 102, 102, 102, 0 ))
end
local modelframe = vgui.Create( "DModelPanel", mainbuttons )
modelframe:SetPos( 0, 65 )
modelframe:SetSize( 300, 200 )
modelframe:SetModel( v.Model )
modelframe:GetEntity():SetAngles( Angle( -10, 0, 15 ) )
local mn, mx = modelframe.Entity:GetRenderBounds()
local size = 0
size = math.max( size, math.abs( mn.x ) + math.abs( mx.x ) )
size = math.max( size, math.abs( mn.y ) + math.abs( mx.y ) )
size = math.max( size, math.abs( mn.z ) + math.abs( mx.z ) )
modelframe:SetFOV( 45 )
modelframe:SetCamPos( Vector( size, size, size ) )
modelframe:SetLookAt( (mn + mx) * 0.5 )
function modelframe:LayoutEntity( Entity )
return
end
end
end
The problem is that you put the whole item in MyList where by logic of SortedPairsByMemberValue you supposed to put new table inside MyList.
This fixes the problem:
MyList = {
{
Index = 1,
Name = "Name 1",
Class = "exampleclass",
Description = "Desc 1",
Model = "modelname",
Color = Color(255, 255, 255, 255)
}
}
Notice that now this is a nested table.

keras change the parameters during training

I have a customized layer to do a simple linear-transformation. like x*w+b. I want to change the w and b during the training, is that possible? For example, I want w1 in the first iteration and w2 in second iteration.(w1 and w2 defined by myself).
Of course, you can do it, but you need to do it in a smart way. Here is some code you can play with.
from keras import backend as K
from keras.layers import *
from keras.models import *
import numpy as np
class MyDense( Layer ) :
def __init__( self, units=64, use_bias=True, **kwargs ) :
super(MyDense, self).__init__( **kwargs )
self.units = units
self.use_bias = use_bias
return
def build( self, input_shape ) :
input_dim = input_shape[-1]
self.count = 0
self.w1 = self.add_weight(shape=(input_dim, self.units), initializer='glorot_uniform', name='w1')
self.w0 = self.add_weight(shape=(input_dim, self.units), initializer='glorot_uniform', name='w0')
if self.use_bias:
self.bias = self.add_weight(shape=(self.units,),initializer='glorot_uniform',name='bias' )
else:
self.bias = None
self.input_spec = InputSpec(min_ndim=2, axes={-1: input_dim})
self.built = True
return
def call( self, x ) :
if self.count % 2 == 1 :
c0, c1 = 0, 1
else :
c0, c1 = 1, 0
w = c0 * self.w0 + c1 * self.w1
self.count += 1
output = K.dot( x, w )
if self.use_bias:
output = K.bias_add(output, self.bias, data_format='channels_last')
return output
def compute_output_shape(self, input_shape):
assert input_shape and len(input_shape) >= 2
assert input_shape[-1]
output_shape = list(input_shape)
output_shape[-1] = self.units
return tuple(output_shape)
# define a dummy model
x = Input(shape=(128,))
y = MyDense(10)(x)
y = Dense(1, activation='sigmoid')(y)
model = Model(inputs=x, outputs=y)
print model.summary()
# get some dummy data
a = np.random.randn(100,128)
b = (np.random.randn(100,) > 0).astype('int32')
# compile and train
model.compile('adam', 'binary_crossentropy')
model.fit( a, b )
Note: the following code is equivalent to what we did above, but it will NOT work !!!
if self.count % 2 == 1 :
w = self.w0
else :
w = self.w1
Why? Because having zero gradients (the former implementation) for one variable is NOT equivalent to having None gradients (the later implementation).

Questions about using Z3Py online to solve problems in Transport Phenomena

Certain problem in transport Phenomena is solved using the following code:
T_max, T_0, S, R, k, I, k_e, L, R, E, a = Reals('T_max T_0 S R k I k_e L R E a')
k = a*k_e*T_0
I = k_e*E/L
S = (I**2)/k_e
eq = T_0 + S* R**2/(4*k)
print eq
equations = [
T_max == eq,
]
print "Temperature equations:"
print equations
problem = [
R == 2, L == 5000,
T_0 == 20 + 273,
T_max == 30 + 273, k_e == 1,
a == 2.23*10**(-8), E > 0
]
print "Problem:"
print problem
print "Solution:"
solve(equations + problem)
using this code online we obtain
This output gives the correct answer but there are two issues in the code: a) the expresion named "eq" is not fully simplified and then it is necessary to give an arbitrary value for k_e . My question is: How to simplify the expression "eq" in such way that k_e be eliminated from "eq"?
Other example: To determine the radius of a tube
Code:
def inte(n,a,b):
return (b**(n+1))/(n+1)-(a**(n+1))/(n+1)
P_0, P_1, L, R, mu, q, C = Reals('P_0 P_1 L R mu q C')
k = (P_0 - P_1)/(2*mu*L)
equations = [0 == -k*inte(1,0,R) +C,
q == 2*3.1416*(-(k/2)*inte(3,0,R) + C*inte(1,0,R))]
print "Fluid equations:"
print equations
problem = [
L == 50.02/100, mu == (4.03*10**(-5)),
P_0 == 4.829*10**5, P_1==0,
q == 2.997*10**(-3), R >0
]
print "Problem:"
print problem
print "Solution:"
solve(equations + problem)
Output:
Fluid equations:
[-((P_0 - P_1)/(2·mu·L))·(R2/2 - 0) + C = 0, q =
3927/625·
(-(((P_0 - P_1)/(2·mu·L))/2)·(R4/4 - 0) + C·(R2/2 - 0))]
Problem:
[L = 2501/5000, mu = 403/10000000, P_0 = 482900, P_1 = 0, q = 2997/1000000, R > 0]
Solution:
[R = 0.0007512843?,
q = 2997/1000000,
P_1 = 0,
P_0 = 482900,
mu = 403/10000000,
L = 2501/5000,
C = 3380.3149444289?]

Reading and parsing files with LUA

I am trying to get it to read from a file x y z coordinates into a 3d array. But it does not seem to be working.
file is located in same folder as the .lua script
-9649.481 666.4141 117.3444
-9475.624 563.4871 116.0533
-9338.459 432.295 137.4043
function lines_from(file)
if not file_exists(file) then return {} end
for line in io.lines(file) do
tokens = {};
itr = 1;
for token in string.gmatch(line, "[^%s]+") do
tokens[ itr ] = token;
itr = itr + 1;
end
x = tokens[1];
y = tokens[2];
z = tokens[3];
g_lines_from[g_lines_fromCount] = { x, y, z };
g_lines_fromCount = g_lines_fromCount + 1;
end
end
function AddAll()
for i = 1, g_lines_from, 1 do
x, y, z = g_lines_from[i];
ListBoxEntry.Create( g_lbWaypoints, "X: " .. math.floor( x ) .. ", Y: " .. math.floor( y ) .. ", Z: " .. math.floor( z ) );
end
end
function OnAddWaypointClicked( eventID, button )
local file = "mine1-75.txt";
lines_from(file);
AddAll();
end;
Try the following function:
function readwaypoints(filename, numberofwaypoints)
local file = io.open(filename)
local waypoints = {}
for n = 1, numberofwaypoints do
local x, y, z
x = file:read('*n')
y = file:read('*n')
z = file:read('*n')
waypoints[#waypoints+1] = {['x'] = x, ['y'] = y, ['z'] = z}
end
file:close()
return waypoints
end
It takes a file name and the number of lines in the file. For your example file, it should return a table like this:
{[1] = {x = -9649.481, y = 666.4141, z = 117.3444},
[2] = {x = -9475.624, y = 563.4871, z = 116.0533},
[3] = {x = -9338.459, y = 432.295, z = 137.4043}}

Resources