You are on page 1of 3

#%% Scipy

import numpy as np
import scipy as scp

dir(scp)

from scipy import linalg

help(linalg)

#%% Calcular una determinante

# definicion de una matriz


arr = np.array([[1,2],[3,4]])
arr
print(arr)

help(linalg.det)

det_A = linalg.det(arr)

%cd "C:\Users\AZCH\Desktop\Clase9_PY"
%pwd
%ls

from scipy import io as spio


# De scipy importanmos el submodulo io, mediante un alias
# spio
spio.mminfo("mahindas.mtx")
mahindas = spio.mmread("mahindas.mtx")
type(mahindas)
mahindas.shape

linalg.det(mahindas)

# conversion de mahindas (sparse) a una matriz densa


mahindas_Dense = mahindas.todense()
type(mahindas_Dense)
linalg.det(mahindas_Dense)

#
===================================================================
==========
# Ejemplo de optimizacion
#
===================================================================
==========
# f(x,y) = (x**2 + y -11)**2 + (x + y**2 -7)**2
# Calcular el minimo de f(x,y)
# en [-5,5]x[-5,5]

from mpl_toolkits.mplot3d import Axes3D


from matplotlib import cm
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = Axes3D(fig, azim = -29, elev = 49)
X = np.arange(-6, 6, 0.1)
Y = np.arange(-6, 6, 0.1)
X, Y = np.meshgrid(X, Y)
Z = (X*X+Y-11)**2 + (X+Y*Y-7)**2
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, norm =
LogNorm(), cmap = cm.jet)
plt.xlabel("x")
plt.ylabel("y")
plt.savefig("Himmelblau function.png")
plt.show()

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams

rcParams['font.size'] = 12

npts = 201
x, y = np.mgrid[-6:6:npts*1j, -6:6:npts*1j]
z = (x**2 + y - 11)**2 + (x + y**2 - 7)**2

fig = plt.figure(figsize=(8, 8))


levels = np.logspace(0.3, 3.5, 15)
plt.contour(x, y, z, levels, cmap="viridis")
plt.xlabel(r"$x$", fontsize=14)
plt.ylabel(r"$y$", fontsize=14)
plt.xticks([-6, -3, 0, 3, 6])
plt.yticks([-6, -3, 0, 3, 6])
plt.xlim([-6, 6])
plt.ylim([-6, 6])
plt.savefig("Himmelblau_contour.png", bbox_inches="tight")
plt.show()

#
===================================================================
==========
# definicion del problema
#
===================================================================
==========
def f(X):
x,y = X
return (x**2 + y -11)**2 + (x + y**2 -7)**2

f([2.99,1.99])

# Por simple inspeccion : (3,2) es un minimo (f(3,2) = 0 )


from scipy.optimize import minimize
help(minimize)

# 1era solucion
P1 = minimize(f, (0,0) )

# 2da solucion
P2 = minimize(f, (-3,-3) )

# 3era solucion
P3 = minimize(f, (-3,3) )

# 4ta solucion
P4 = minimize(f, (3,-1.5) )

type(P1)

P1['x']
P1['fun']
P1['njev']

You might also like