Python Kernel died when using Gurobi in Enthought Canopy on Win 7 - python

I was trying to use Gurobi for Python to solve a Mixed Integer Optimization problem, but every time I run the code I wrote according to the Gurobi tutorial, a message popped up, saying:
"The Kernel has died, would you like to restart it? If you do not restart the kernel, you will be able to save the notebook, but running code will nor work until the notebook is reopened."
I used Enthought Canopy with Python 2.7 and Gurobipy from Gurobi on Win 7.
Here is a small trial optimization problem I tried to solve, and the message above showed up after I run it:
import gurobipy
import numpy
from gurobipy import *
def minVol(N1,solution):
model=Model()
x=model.addVar(lb=0.0,ub=1.0,vtype=GRB.CONTINUOUS)
y=model.addVar(lb=0.0,ub=1.0,vtype=GRB.CONTINUOUS)
model.update()
varibles=model.getVars()
model.setObjective(2*x+y,GRB.Maximize)
model.update()
model.optimize()
if model.status==GRB.OPTIMAL:
s=model.getAttr('s',varibles)
for i in range(N1):
solution[i]=s[i]
return True
else:
return False
N1=2
solution=[0]*(N1)
success=minVol(N1,solution)
if success:
print solution
Anyone would help me with this? Thank you very much!

Related

Jupyter Notebook malfunctioning

I am running Julia and Python on Jupyter notebook. I like the UI and the auto indentation and other features (I'm a beginner). However, while running Julia today the entire notebook just appears blank. The code blocks are not colour coded, and there is no auto indentation. However, when I open a Python notebook/change the kernel from Julia to Python, it works as usual. I have attached pictures here for comparison.
I don't know what has changed. How do I fix this?
EDIT: Adding some code for reference:
Julia
using Plots
function lattice(N)
lat = zeros(N,N)
for i in (1:N)
for j in (1:N)
if rand() < 0.5
lat[i,j] = 1
else lat[i,j] = -1
end
end
end
return(lat)
end
Python
import numpy as np
def ran_ini_cond(L):
spins = np.zeros((L,L))
for i in range(L):
for j in range(L):
spins[i,j] = np.random.choice([1,-1])
print('inital lattice')
return(spins)
These are two different versions of the same program I am trying to run on Julia and Python. The code works, but a lot of the IJulia and/or Jupyter notebook features are disabled for Julia (as seen in the pictures).

Get CPU and GPU Temp using Python Windows

I was wondering if there was a way to get the CPU and the GPU temperature in python. I have already found a way for Linux (using psutil.sensors_temperature()), and I wanted to find a way for Windows.
A way to find the temperatures for Mac OS would also be appreciated, but I mainly want a way for windows.
I prefer to only use python modules, but DLL and C/C++ extensions are also completely acceptable!
When I try doing the below, I get None:
import wmi
w = wmi.WMI()
prin(w.Win32_TemperatureProbe()[0].CurrentReading)
When I try doing the below, I get an error:
import wmi
w = wmi.WMI(namespace="root\wmi")
temperature_info = w.MSAcpi_ThermalZoneTemperature()[0]
print(temperature_info.CurrentTemperature)
Error:
wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147217396, 'OLE error 0x8004100c', None, None)>
I have heard of OpenHardwareMoniter, but this requires me to install something that is not a python module. I would also prefer to not have to run the script as admin to get the results.
I am also fine with running windows cmd commands with python, but I have not found one that returns the CPU temp.
Update: I found this: https://stackoverflow.com/a/58924992/13710015.
I can't figure out how to use it though.
When I tried doing: print(OUTPUT_temp._fields_), I got
[('Board Temp', <class 'ctypes.c_ulong'>), ('CPU Temp', <class 'ctypes.c_ulong'>), ('Board Temp2', <class 'ctypes.c_ulong'>), ('temp4', <class 'ctypes.c_ulong'>), ('temp5', <class 'ctypes.c_ulong'>)]
Note: I really do not want to run this as admin. If I absolutely have to, I can, but I prefer not to.
I think there doesn't have a directly way to achieve that. Some CPU producers wouldn't provide wmi to let your know the temperature directly.
You could use OpenHardwareMoniter.dll. Use the dynamic library.
Firstly, Download the OpenHardwareMoniter. It contains a file called OpenHardwareMonitorLib.dll (version 0.9.6, December 2020).
Install the module pythonnet:
pip install pythonnet
Below code works fine on my PC (Get the CPU temperature):
import clr # the pythonnet module.
clr.AddReference(r'YourdllPath')
# e.g. clr.AddReference(r'OpenHardwareMonitor/OpenHardwareMonitorLib'), without .dll
from OpenHardwareMonitor.Hardware import Computer
c = Computer()
c.CPUEnabled = True # get the Info about CPU
c.GPUEnabled = True # get the Info about GPU
c.Open()
while True:
for a in range(0, len(c.Hardware[0].Sensors)):
# print(c.Hardware[0].Sensors[a].Identifier)
if "/temperature" in str(c.Hardware[0].Sensors[a].Identifier):
print(c.Hardware[0].Sensors[a].get_Value())
c.Hardware[0].Update()
To Get the GPU temperature, change the c.Hardware[0] to c.Hardware[1].
Compare the result with :
Attention: If you want to get the CPU temperature, you need to run it as Administrator. If not, you will only get the value of Load. For GPU temperature, it can work without Admin permissions (as on Windows 10 21H1).
I did some changes from a Chinese Blog
I found a pretty good module for getting the temperature of NVIDIA GPUs.
pip install gputil
Code to print out temperature
import GPUtil
gpu = GPUtil.getGPUs()[0]
print(gpu.temperature)
I found it here
so you can use gpiozero to get the temp
first pip install gpiozero and from gpiozero import CPUTemperature to import it and cpu = CPUTemperature() print(cpu.temperature)
code:
from gpiozero import CPUTemperature
cpu = CPUTemperature()
print(cpu.temperature)
hope you enjoy. :)

qiskit plots not showing up in spyder console

System Informations
Qiskit version: 0.17.0
Python version: 3.7.7
Operating system: Windows 10 home x64
What is the current behavior?
I am using spyder 4.1.1 on Anaconda and any time I try to plot data it does not show up. The code runs with no errors but the plot it self does not appear anywhere.
Steps to reproduce the problem
Running the code listed below which is from the IBMQ website:
import numpy
import qiskit as qc
from qiskit import QuantumCircuit, execute, Aer
import matplotlib
from qiskit.visualization import plot_state_city
circ = qc.QuantumCircuit(3)
circ.h(0)
circ.cx(0,1)
circ.cx(0,2)
print(circ.draw())
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
plot_state_city(outputstate)
What is the expected behavior?
for the plot state city plot to show up in the console or somewhere else
Suggested solutions
I tried using both matplotlib.pylot.show() and matplotlib.pyplot.draw()
Try follow the instructions under "Spyder plots in separate windows" here. Then you can also call circ.draw(output='mpl') to draw the circuit in a window. Hope this helps.
To print your circuit, you have to type print(name of the circuit) so in your case type print(circ).
This may be because the plots don't show in spyder by default. If you run this code in a Jupyter Notebook the plots should show up just fine!
I generally use pycharm ide for running the qiskit code. I think, spyder should also work the same.
Please modify your code as below. I hope, it will work for you.
import numpy
import qiskit as qc
from qiskit import QuantumCircuit, execute, Aer
import matplotlib
from qiskit.visualization import plot_state_city
import matplotlib.pyplot as plt
circ = qc.QuantumCircuit(3)
circ.h(0)
circ.cx(0,1)
circ.cx(0,2)
circ.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
plot_state_city(outputstate)
plt.show()
1st: I changed the preferences of spyder: Tools ==> Preferences ==> ipython console ==> Graphics ==> Graphics backend ==> Automatic.
2nd: then I have tried the option mentioned in the answer above, with minor modification is that by writing 'mpl' only between the brackets after the word "draw" to have the code be circ.draw('mpl'), and things worked fine.

Python Kernel Died when using triple for loop containing requires_grad=True parameters (Pytorch)

I just want to store para_k in every position of COV matrix, where:
para_k=torch.tensor([2.0],requires_grad=True).
And because I want to update parameters by optimising a loss function later(omitted here), I have to add another for loop. Therefore, the whole code is as follows:
import torch
para_k=torch.tensor([2.0],requires_grad=True)
for t in range(5):
num_row=300
num_col=300
COV = torch.zeros((num_row,num_col))
for i in range(num_row):
for j in range(num_col):
COV[i,j]=para_k
print('i= %d ,j= %d' % (i,j) )
This simple computation cannot be finished by Spyder!!
Things can go well if I change nrow and ncol to be smaller than 100.
If I use number larger than 100, it will send error message (sometimes even one iteration cannot be finished) that Kernel died and restarting: Spyder Kernel Died
I even uninstall and install again my Anaconda and reinstall pytorch. I also tried to run Spyder as administrator, still got the error.
I check the event of my system, the error is: ntdll.dll regarding to pythonw.exe. I listed pythonw.exe as exception of firewall, but still cannot solve the problem.

Using Numpy in different platforms

I have a piece of code which computes the Helmholtz-Hodge Decomposition.
I've been running on my Mac OS Yosemite and it was working just fine. A month ago, however, my Mac got pretty slow (it was really old), and I opted to buy a new notebook (Windows 8.1, Dell).
After installing all Python libs and so on, I continued my work running this same code (versioned in Git). And then the result was pretty weird, completely different from the one obtained in the old notebook.
For instance, what I do is to construct to matrices a and b(really long calculus) and then I call the solver:
s = numpy.linalg.solve(a, b)
This was returning a (wrong, and different of the result obtained in my Mac, which was right).
Then, I tried to use:
s = scipy.linalg.solve(a, b)
And the program exits with code 0 but at the middle of it.
Then, I just made a simple test of:
print 'here1'
s = scipy.linalg.solve(a, b)
print 'here2'
And here2 is never printed.
I tried:
print 'here1'
x, info = numpy.linalg.cg(a, b)
print 'here2'
And the same happens.
I also tried to check the solution after using numpy.linalg.solve:
print numpy.allclose(numpy.dot(a, s), b)
And I got a False (?!).
I don't know what is happening, how to find a solution, I just know that the same code runs in my Mac, but it would be very good if I could run it in other platforms. Now I'm stucked in this problem (don't have a Mac anymore) and with no clue about the cause.
The weirdest thing is that I don't receive any error on runtime warning, no feedback at all.
Thank you for any help.
EDIT:
Numpy Suit Test Results:
Scipy Suit Test Results:
Download Anaconda package manager
http://continuum.io/downloads
When you download this it will already have all the dependencies for numpy worked out for you. It installs locally and will work on most platforms.
This is not really an answer, but this blog discusses in length the problems of having a numpy ecosystem that evolves fast, at the expense of reproducibility.
By the way, which version of numpy are you using? The documentation for the latest 1.9 does not report any method called cg as the one you use...
I suggest the use of this example so that you (and others) can check the results.
>>> import numpy as np
>>> import scipy.linalg
>>> np.random.seed(123)
>>> a = np.random.random(size=(10000, 10000))
>>> b = np.random.random(size=(10000,))
>>> s_np = np.linalg.solve(a, b)
>>> s_sc = scipy.linalg.solve(a, b)
>>> np.allclose(s_np,s_sc)
>>> s_np
array([-15.59186559, 7.08345804, 4.48174646, ..., -16.43310046,
-8.81301553, -10.77509242])
I hope you can find the answer - one option in the future is to create a virtual machine for each of your projects, using Docker. This allows easy portability.
See a great article here discussing Docker for research.

Categories