程序代写代做代考 python Homework 2¶

Homework 2¶

Knowledge: Using numpy operations and functions¶

1. Write a script to perform an inner product of the given arrays:
x = np.arange(24).reshape((2,3,4))
y = np.arange(4)
np.reshape: Changes the dimensions(shape) of an array without changing its data. reference:https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html
np.arange: Returns evenly spaced values within a given interval. reference:https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html

Save the array x, y and the inner product.

1. Write a function to transform an input vector in Cartesian basis into a vector in the given basis.
The function takes input arguements: new_basis_vec1, new_basis_vec2, new_basis_vec3, vec_old.
$$ A,v_{new} = f\{x_{1},x_{2},x_{3},z_{1},z_{2},z_{3},v_{old}\}$$
Where $x_{1},x_{2},x_{3}$ are cartesian basis vectors and $z_{1},z_{2},z_{3}$ are new given basis vectors.$v_{old}$ is the vector to be transformed.
It should return the transfromed vector $v_{new}$. Please refer to the comments given in template code for further information.
( Check whether the input arguement satisfies the basis condition. If not, the function should print the condition not satisfied)

You can use sympy or numpy. You might need sympy to find the linear dependence of matrix [sympy](https://docs.sympy.org/latest/tutorial/matrices.html).

We have provided you a function “plotBasis” for you to check plot of the trasformed vector. Uncomment the function “plotBasis” to run and test your output.

Question 1¶
In [0]:
import numpy as np

# **** Insert your code here ****

Question 2¶
In [0]:
import matplotlib.pyplot as plt
from sympy import *
import numpy as np
import sys

def vectorBasisTransformation(new_basis_vec1, new_basis_vec2, new_basis_vec3, vec_old):
“””Transforms the vector in current basis(Cartesian) to new basis.

Steps:
Make matrix of the given new basis vectors
Check linear dependence of matrix using sympy package
Check matrix invertibility
If linear dependent and invertible, transform given vector to new basis

Args:
new_basis_vec1: New basis vector 1
new_basis_vec2: New basis vector 2
new_basis_vec3: New basis vector 3
vec_old: Vector to transform

Returns:
matrix: The change of basis matrix from old to new basis.
vec_new: Vector in new basis.

“””

# **** Insert your code here ****

return [matrix, vec_new]

if __name__ == “__main__”:
actual_basis_vec1 = np.array([1,0,0])
actual_basis_vec2 = np.array([0,1, 0])
actual_basis_vec3 = np.array([0,0,1])
new_basis_vec1 = np.array([2,3, 4])
new_basis_vec2 = np.array([-1,1, 1])
new_basis_vec3 = np.array([-1,0, 1])
vec_old = np.array([[2],[-4],[2]])

basis_matrix, vector_new = vectorBasisTransformation(new_basis_vec1, new_basis_vec2, new_basis_vec3,vec_old)
# plotBasis(actual_basis_vec1, actual_basis_vec2, actual_basis_vec3, new_basis_vec1, new_basis_vec2, new_basis_vec3, vec_new, vec_old)
In [0]:
def configure_plotly_browser_state():
import IPython
display(IPython.core.display.HTML(”’


”’))

# The red vector is the changed basis whereas blue is the original basis
def plotBasis(red_vect1, red_vect2, red_vect3, blue_vect1, blue_vect2, blue_vect3, vec_new, vec_old):
“””Plots the old basis and new basis

Args:
red_vect1: Old basis vec1
red_vect2: Old basis vec2
red_vect3: Old basis vec3
blue_vect1: New basis vec1
blue_vect2: New basis vec2
blue_vect3: New basis vec3
vec_new: New vector (light blue)
vec_old: Old vector (orange)
“””

# ploting lib
import plotly.graph_objs as go
from plotly.offline import plot
from plotly.offline import init_notebook_mode, iplot
from plotly.graph_objs import Scatter
configure_plotly_browser_state()
init_notebook_mode(connected=False)

basis_old1 = go.Scatter3d( x = [0,red_vect1[0].item()],
y = [0,red_vect1[1].item()],
z = [0,red_vect1[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(255,0,0)”,
width = 6)
)

basis_old2 = go.Scatter3d( x = [0,red_vect2[0].item()],
y = [0,red_vect2[1].item()],
z = [0,red_vect2[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(255,0,0)”,
width = 6)
)

basis_old3 = go.Scatter3d( x = [0,red_vect3[0].item()],
y = [0,red_vect3[1].item()],
z = [0,red_vect3[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(255,0,0)”,
width = 6)
)

basis_new1 = go.Scatter3d( x = [0,blue_vect1[0].item()],
y = [0,blue_vect1[1].item()],
z = [0,blue_vect1[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(0,0,255)”,
width = 6)
)

basis_new2 = go.Scatter3d( x = [0,blue_vect2[0].item()],
y = [0,blue_vect2[1].item()],
z = [0,blue_vect2[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(0,0,255)”,
width = 6)
)
basis_new3 = go.Scatter3d( x = [0,blue_vect3[0].item()],
y = [0,blue_vect3[1].item()],
z = [0,blue_vect3[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(0,0,255)”,
width = 6)
)

# Light blue
vector_new = go.Scatter3d( x = [0,vec_new[0].item()],
y = [0,vec_new[1].item()],
z = [0,vec_new[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(102,178,255)”,
width = 6)
)

# Orange
vector_old = go.Scatter3d( x = [0,vec_old[0].item()],
y = [0,vec_old[1].item()],
z = [0,vec_old[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(255,69,0)”,
width = 6)
)
iplot([basis_old1, basis_old2, basis_old3,basis_new1, basis_new2, basis_new3, vector_new,vector_old ], show_link=False)

Submission:
• Save your generated ‘x’, ‘y’ and your inner products output into a dictionary, with key value pair as:
• “0”: x,
• “1”: y,
• “2”: inner_products_numpy_array

• The output of the transformed function is a vector. Save the vector, and the change of basis matrix into the same dictonary with the keys and values:

• “3”: the_change_of_basis_matrix,
• “4”: new_vector_numpy_array
into a file hw2_output.npy .

• Along with the output file, copy paste or convert your code in Jupyter notebook to python script hw2_script.py. Remember to comment out your plaotting code, as when you run the script you would only want to save matrix and vector, not want to show the plot.

Solution:¶
In [0]:
%matplotlib inline
import matplotlib.pyplot as plt
from sympy import *
import numpy as np
import sys

x = np.arange(24).reshape((2,3,4))
print(“Array x:”)
print(x)
print(“Array y:”)
y = np.arange(4)
print(y)
print(“Inner of x and y arrays:”)
inner = np.inner(x, y)
print(np.inner(x, y))

Array x:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
Array y:
[0 1 2 3]
Inner of x and y arrays:
[[ 14 38 62]
[ 86 110 134]]
In [0]:
# The red vector is the changed basis whereas blue is the original basis
def plotBasis(red_vect1, red_vect2, red_vect3, blue_vect1, blue_vect2, blue_vect3, vec_new, vec_old):
“””Plots the old basis and new basis

Args:
red_vect1: Old basis vec1
red_vect2: Old basis vec2
red_vect3: Old basis vec3
blue_vect1: New basis vec1
blue_vect2: New basis vec2
blue_vect3: New basis vec3
vec_new: New vector (light blue)
vec_old: Old vector (orange)
“””

# ploting lib
import plotly.graph_objs as go
from plotly.offline import plot
from plotly.offline import init_notebook_mode, iplot
from plotly.graph_objs import Scatter
configure_plotly_browser_state()
init_notebook_mode(connected=False)

basis_old1 = go.Scatter3d( x = [0,red_vect1[0].item()],
y = [0,red_vect1[1].item()],
z = [0,red_vect1[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(255,0,0)”,
width = 6)
)

basis_old2 = go.Scatter3d( x = [0,red_vect2[0].item()],
y = [0,red_vect2[1].item()],
z = [0,red_vect2[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(255,0,0)”,
width = 6)
)

basis_old3 = go.Scatter3d( x = [0,red_vect3[0].item()],
y = [0,red_vect3[1].item()],
z = [0,red_vect3[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(255,0,0)”,
width = 6)
)

basis_new1 = go.Scatter3d( x = [0,blue_vect1[0].item()],
y = [0,blue_vect1[1].item()],
z = [0,blue_vect1[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(0,0,255)”,
width = 6)
)

basis_new2 = go.Scatter3d( x = [0,blue_vect2[0].item()],
y = [0,blue_vect2[1].item()],
z = [0,blue_vect2[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(0,0,255)”,
width = 6)
)
basis_new3 = go.Scatter3d( x = [0,blue_vect3[0].item()],
y = [0,blue_vect3[1].item()],
z = [0,blue_vect3[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(0,0,255)”,
width = 6)
)

# Light blue
vector_new = go.Scatter3d( x = [0,vec_new[0].item()],
y = [0,vec_new[1].item()],
z = [0,vec_new[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(102,178,255)”,
width = 6)
)

# Orange
vector_old = go.Scatter3d( x = [0,vec_old[0].item()],
y = [0,vec_old[1].item()],
z = [0,vec_old[2].item()],
marker = dict( size = 5,
color = “rgb(84,48,5)”),
line = dict( color = “rgb(255,69,0)”,
width = 6)
)
iplot([basis_old1, basis_old2, basis_old3,basis_new1, basis_new2, basis_new3, vector_new,vector_old ], show_link=False)

def configure_plotly_browser_state():
import IPython
display(IPython.core.display.HTML(”’


”’))

def vectorBasisTransformation(new_basis_vec1, new_basis_vec2, new_basis_vec3,vec_old):
“””Transforms the vector in current basis to new basis.

Steps:
Make matrix of the given new basis vector
Check linear dependence of matrix using sympy package
Check matrix invertibility
If linear dependent and invertible, transform given vector to new basis

Args:
new_basis_vec1: New basis vector 1
new_basis_vec2: New basis vector 2
new_basis_vec3: New basis vector 3
vec_old: Vector to transform

Returns:
matrix: The change of basis matrix from old to new basis.
vec_new: Vector in new basis.

“””

# Make matrix of old basis
w1 = np.transpose([new_basis_vec1])
w2 = np.transpose([new_basis_vec2])
w3 = np.transpose([new_basis_vec3])
matrix = np.concatenate((w1,w2,w3), axis = 1)
print(“Actual baisi matrix: “)
print(matrix)
# Check Dependence
sympy_matrix = Matrix(matrix)
rred_matrix, rred_matrix_indices = sympy_matrix.rref()
m = max(diag(rred_matrix[:,1]).shape)
n = max(diag(rred_matrix[1,:]).shape)
if n>m:
d=0
print(“Matrix is not linearly independent”)
else:
s=sum(diag(rred_matrix))
if n>s:
d=0
print(“Matrix is linearly dependent”)
else:
d=1

isdependent = d
assert d == 1, “The matrix is not linearly dependent”

# Check Invertible
if np.linalg.cond(matrix) < 1/sys.float_info.epsilon: inv = np.linalg.inv(matrix) i = 1 else: i = 0 print("Matrix is not invertible") isinvertible = i assert i == 1, "The matrix is not invertible" # Do transformation if(not isdependent or not isinvertible): print("Cannot transfrom current basis") else: vec_new = np.linalg.inv(np.array(matrix)).dot(vec_old) print("Vector in new basis is: {}".format(vec_new)) return [np.linalg.inv(matrix), vec_new] if __name__ == "__main__": actual_basis_vec1 = np.array([1,0,0]) actual_basis_vec2 = np.array([0,1, 0]) actual_basis_vec3 = np.array([0,0,1]) new_basis_vec1 = np.array([2,3, 4]) new_basis_vec2 = np.array([-1,1, 1]) new_basis_vec3 = np.array([-1,0, 1]) vec_old = np.array([[2],[-4],[2]]) basis_matrix, vec_new = vectorBasisTransformation(new_basis_vec1, new_basis_vec2, new_basis_vec3,vec_old) print(basis_matrix) print(vec_new) plotBasis(actual_basis_vec1, actual_basis_vec2, actual_basis_vec3, new_basis_vec1, new_basis_vec2, new_basis_vec3, vec_new, vec_old) Actual baisi matrix: [[ 2 -1 -1] [ 3 1 0] [ 4 1 1]] Vector in new basis is: [[ 0.66666667] [-6. ] [ 5.33333333]] [[ 0.16666667 0. 0.16666667] [-0.5 1. -0.5 ] [-0.16666667 -1. 0.83333333]] [[ 0.66666667] [-6. ] [ 5.33333333]] In [0]: basis_matrix = np.linalg.inv(basis_matrix) np.save("hw2_output_solution" ,{"0": x, "1": y , "2":inner, "3":basis_matrix, "4":vec_new})