```python
# fitting function in Python:
'''optimize.curve_fit and lestq
leastsq can fit residuals:
    def residuals(coeffs, y, t):...
    leastsq(residuals, x0, args=(y, t)), take care of the order

curve_fit(func, xdata, ydata, x0, sigma) can fit function
    When defining func, put x as the first input.
'''

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from ipywidgets import interact, FloatSlider, RadioButtons
from scipy import optimize
import scipy as sc
import os.path
```

```python
# Test Stoner package
"""Demonstrate Channel math operations."""
from Stoner import Data
from numpy import linspace,ones_like,sin,cos,pi
from numpy.random import normal
from Stoner.plot.utils import errorfill

x=linspace(0,10*pi,101)
e=0.01*ones_like(x)
y=0.1*sin(x)+normal(size=len(x),scale=0.01)+0.1
e2=0.01*cos(x)
y2=0.1*ones_like(x)
d=Data(x,y,e,y2,e2,column_headers=["$X$","$Y_+$",r"$\delta Y_+$","$Y_-$",r"$\delta Y_-$"],setas="xyeye")

a=tuple(d.column_headers[1:3])
b=tuple(d.column_headers[3:5])

d.add(a,b,replace=False)
d.subtract(a,b,replace=False)
d.multiply(a,b,replace=False)
d.divide(a,b,replace=False)
d.diffsum(a,b,replace=False)
d.setas="xyeyeyeyeyeyeye"
d.plot(multiple="panels",plotter=errorfill,color="red",alpha_fill=0.2)
```

    C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py:107: MatplotlibDeprecationWarning: The mpl_toolkits.axes_grid module was deprecated in version 2.1. Use mpl_toolkits.axes_grid1 and mpl_toolkits.axisartist provies the same functionality instead.
      warnings.warn(message, mplDeprecation, stacklevel=1)

    <IPython.core.display.Javascript object>

    C:\ProgramData\Anaconda3\lib\site-packages\Stoner\plot\utils.py:130: RuntimeWarning: divide by zero encountered in true_divide
      y = h / (np.sqrt(2 * np.pi) * yd)
    C:\ProgramData\Anaconda3\lib\site-packages\Stoner\plot\utils.py:128: RuntimeWarning: divide by zero encountered in log
      z = lambda x, s,y: s * np.sqrt(-2 * np.log(np.sqrt(2 * np.pi) * s * y))
    C:\ProgramData\Anaconda3\lib\site-packages\Stoner\plot\utils.py:128: RuntimeWarning: invalid value encountered in sqrt
      z = lambda x, s,y: s * np.sqrt(-2 * np.log(np.sqrt(2 * np.pi) * s * y))

```python
import Stoner
from Stoner import FileFormats as SFF

v=SFF.QDFile()
v.load(filename=r'D:\3_Physical Properties\Nd3Sb3Zn2O14\Nd3Sb3Zn2O14_powder_1stBatch_mt_mh_squid.dat')

print v.header
print v.column_headers

#print v.column(u'Temperature (K)')
#print v.column('Magnetic Field (Oe)')
#print v[:,u'Temperature (K)']
print v[:,['Temperature (K)','Magnetic Field (Oe)','DC Moment Free Ctr (emu)']]
```

## Single spin mag

```python
ut2k=0.6717  # convert mub*Tesla to K
#jz=-0.2; jx=0.1; jy=0.1;jxz=0.1 #exchange interaction in K
#moment=2.6 # in muonB

def mag(g,jz,tempe,field):
    p1=np.exp(-(g/2*field/ut2k)/tempe) #probability for the spin unparallel to the field
    p2=np.exp(-(-g/2*field/ut2k-jz*6)/tempe)#probability for the spin unparallel to the field
    prob1=p1/(p1+p2);prob2=p2/(p1+p2)
    mag=(1-prob1+prob2)*g/2
    return mag
field=np.linspace(0,0.5,150)
plt.plot(field,mag(6.3,-0.33,0.07,field)/4)
plt.show()

```

    <IPython.core.display.Javascript object>

## Powder with Ising spins

```python
#　ＭＨ（Ｔ）　ｆｏｒ　ｅｆｆｅｃｔｉｖｅ　ｓｐｉｎ　ｈａｌｆ　ｐｏｗｄｅｒ　ｓａｍｐｌｅ，　ｅｇ，Ｎｄ２Ｚｒ２Ｏ７
import scipy.integrate as integrate

kb = 1.38*10**-23
mb = 9.27*10**-24 # in units of Kelvin
jp = 1/2.       # for our Ising Moment
def isingpow(h, t, g): # h cannot be a array due to func 'integrate' can not take array as a upper limit
    p1 = mb*jp/(kb*t)
    fun =lambda v: v*np.tanh(g*p1*v)  #x= g p1 v where v is the field and the varble to integrate
    smh = g*jp*integrate.quad(fun, 0.00001, h)[0]/h**2
    return smh
# we can vectorize the function only for 'h'
# https://stackoverflow.com/questions/41223186/numpy-vectorization-with-integration
visingpow = np.vectorize(isingpow, excluded=['t','g']) # vectorize the func for 'h'

x=np.linspace(0.1,5, 10)
print visingpow(x, 2, 6.3)

# plot test
y=[]
for xi in x:
    y.append(isingpow(xi,2,1))
#y = isingpow(x,2,6.3)
print x.shape, np.array(y).shape
plt.plot(x,np.array(y),'*')
plt.show()
```

    [ 0.11084096  0.65706397  1.02973027  1.24500696  1.36463278  1.43284043
      1.47370974  1.49956243  1.51676424  1.52872556]
    (10L,) (10L,)

### MH fitting for Nd2Zr2O7

```python
# MH data for Nd2Zr2O7
fpath = r'D:\3_Physical Properties\Gd2Zr2O7\2_NZO_pow_MH_2-5-10-20k_OldSQUID_Sep2015.txt'
mhdat = np.genfromtxt(fpath, usecols=(0,1,2,3,4,5,6,7), skip_header=1) # MH at 1.8, 5, 10, 20K

Ts = [1.8, 5., 10., 20] # temperatures

for i in xrange(0, mhdat.shape[1],2):
    mhdat[:,i] = mhdat[:,i] / 10000. # change the unit to Tesla

#plot data
for i in xrange(0, mhdat.shape[1],2):
    plt.plot(mhdat[:,i],mhdat[:,i+1],'o')

```

    <IPython.core.display.Javascript object>

```python
# multi-curve fitting: def a global error

def err(t, g, x, y):
    x, y = x[~np.isnan(x)], y[~np.isnan(y)]
    #err = visingpow(x, t, g) - y # use vectorized scipy function
    err = np.array([isingpow(x[i], t, g) - y[i] for i in np.arange(0, x.shape[0])]).ravel()
    return  err
# have to put "ravel()" or 'flatten()' otherwise error on 'hstack' when using leastsq (no problem for non-fit use)

def err_global(g):
    err0=[]
    for i in range(len(Ts)):
        errc=err(Ts[i], g, mhdat[:,i*2],mhdat[:,i*2+1])
        err1=np.concatenate((err0,errc))
        err0=err1
    return err0 #(err0**2).sum()

# fit
p_best,success=optimize.leastsq(err_global, 5.5)
print p_best, success
#print err_global(p_best)

# plot dat and fit
fig = plt.figure(figsize=(5,4))
for i in xrange(0, mhdat.shape[1],2):
    plt.plot(mhdat[:,i],mhdat[:,i+1],'*')

xdat=np.linspace(0.01,5, 100)
for t in np.hstack(([0.1, 0.5, 1],Ts)).ravel():
    ydat = np.array([isingpow(xdat[i], t, p_best[0]) for i in np.arange(0, xdat.shape[0])])
    plt.plot(xdat,ydat)

plt.show()

'''
Why the fitting result is similar but different with that in Mathematica (5.24) ?
The function to fit does not produece the same curve if fix the same parameters!!!
Probelem with Integrate, data without simga?
'''
```

```python
str = 'Hello World!'

print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[-5:-1]     # Prints characters starting from 3rd to 5th
```

## Fit MH of Nd2Sn2O7

```python
fpath = r'D:\3_Physical Properties\Nd2Sn2O7'
fnames = ['Nd2Sn2O7_powder_1stBatch_mt_0p1T.txt','Nd2Sn2O7_powder_1stBatch_mt_1T.txt',
         'Nd2Sn2O7_powder_1stBatch_mh_1p8_5_10_20K.txt', 'Nd2Sn2O7_powder_1stBatch_mh_squid.txt']

#mh = np.genfromtxt(os.path.join(fpath,fnames[2]), usecols=(0,1,2), skip_header=0)
mh = np.genfromtxt(os.path.join(fpath,fnames[3]), usecols=(0,1,2), skip_header=0)
print mh
# convert units
mh[:,1], mh[:,2] = mh[:,1]/10000, mh[:,2]/0.02432*637.8998/5585/2
#mh_squid[:,1], mh_squid[:,2] = mh_squid[:,1]/10000, mh_squid[:,2]/0.02432*637.8998/5585/2
print mh
```

    [[  1.79979670e+00   1.16069540e-01  -1.12098400e-03]
     [  1.79916710e+00   4.99563263e+02   1.60209580e-02]
     [  1.79958713e+00   9.99730103e+02   3.31077720e-02]
     ...,
     [  2.00004530e+01   3.99970972e+03   1.33833950e-02]
     [  2.00005608e+01   1.99961108e+03   6.68313900e-03]
     [  2.00005121e+01  -1.85711250e-01  -9.98000000e-05]]
    [[  1.79979670e+00   1.16069540e-05  -2.63229850e-03]
     [  1.79916710e+00   4.99563263e-02   3.76204689e-02]
     [  1.79958713e+00   9.99730103e-02   7.77437845e-02]
     ...,
     [  2.00004530e+01   3.99970972e-01   3.14269343e-02]
     [  2.00005608e+01   1.99961108e-01   1.56933701e-02]
     [  2.00005121e+01  -1.85711250e-05  -2.34350705e-04]]

```python
# we can vectorize the function for 't' and 'h'
visingpow = np.vectorize(isingpow, excluded=['g'])
def multi_visingpow(t_h, g):
    # h and t can be arrays and combined for using curve_fit (only accept one varible input)
    # https://stackoverflow.com/questions/28372597/python-curve-fit-with-multiple-independent-variables
    t, h = t_h[:,0], t_h[:,1]
    return visingpow(h, t, g)

# Fit g factor
popt, pcov = optimize.curve_fit(multi_visingpow, mh[:,0:2], mh[:,2], p0=5.2)
print popt

# also fit a mass scale factor
#popt1, pcov1 = optimize.curve_fit(lambda t_h, g, mass_sc: multi_visingpow(t_h, g)*mass_sc, mh[:,0:2], mh[:,2], p0=[5.2, 1])
#print popt1

# also fit chi_vv
#popt2, pcov2 = optimize.curve_fit(lambda t_h, g, a: multi_visingpow(t_h, g)+a*t_h[:,1], mh[:,0:2], mh[:,2], p0=[5.2, 0.01])
#print popt2

```

    [ 5.1705624]

```python
# plot dat and fit
Ts = [1.8, 5, 10, 20]
fig = plt.figure(figsize=(5,4))
plt.plot(mh[:,1],mh[:,2],'o',mec='black',mfc='none',markevery=0.02)
#plt.plot(mh_squid[:,1],mh_squid[:,2],'s')

hdat=np.linspace(0.001,7, 100)
for t in np.hstack(([.1],Ts)).ravel():
    ydat = visingpow(hdat, t, popt)
    plt.plot(hdat,ydat,'r-')

# Plot the fit with fitted mass
#plt.plot(mh[:,1], visingpow(mh[:,1],mh[:,0], popt1[0])*popt1[1],'o',ms=1,c='black')

# Plot the fit with fitted chi_vv
#plt.plot(mh[:,1], visingpow(mh[:,1],mh[:,0], popt2[0])+popt2[1]*mh[:,1],'o',ms=1,c='grey')

plt.show()
```

    <IPython.core.display.Javascript object>

```python
mt = np.genfromtxt(os.path.join(fpath,fnames[0]), usecols=(0,1,2), skip_header=0)

mt = Data(mt[:,[0,2]],column_headers=['Temperature (K)','DC Moment Free Ctr (emu)'], setas="xy")

mt.multiply('DC Moment Free Ctr (emu)', 1./1000/0.02432*637.8998/2, header='DC Moment Free Ctr (emu)', replace=True)

def chicw(t,tcw,mu,chivv):
    return 0.125 * mu**2 / (t-tcw) + chivv

fit=mt.curve_fit(chicw, xcol='Temperature (K)', ycol='DC Moment Free Ctr (emu)', bounds=lambda x,y: 5<x<15,
                 result=True, replace=False, header="Fit",output="report")

print(fit.report.popt)

plt.figure()
plt.plot(mt[:,0],1/mt[:,1],'o',mfc='none')
plt.plot(mt[:,0],1/mt[:,2])
plt.xlim([0,30])
plt.ylim([0,30])
plt.show()
```

    [ 0.11763906  2.78183178  0.00903607]

    <IPython.core.display.Javascript object>

```python

```

## Nd3Sb3Zn2O14 (not Ising, so not appliable)

```python
fpath = r'D:\3_Physical Properties\Nd3Sb3Zn2O14'
fnames = ['Nd3Sb3Mg2O14_powder_1stBatch_mt_0p1T.txt','Nd3Sb3Mg2O14_powder_1stBatch_mt_1T.txt',
          'Nd3Sb3Mg2O14_powder_1stBatch_mh_1p8_5_10_20K.txt']
mh = np.genfromtxt(os.path.join(fpath,fnames[2]), usecols=(0,1,2), skip_header=0)

# convert units
mh[:,1], mh[:,2] = mh[:,1]/10000, mh[:,2]/0.04842*1152.76/5585/3

# SQUID data
v=SFF.QDFile()
v.load(filename=r'D:\3_Physical Properties\Nd3Sb3Zn2O14\Nd3Sb3Zn2O14_powder_1stBatch_mt_mh_squid.dat')

ind = np.where(v[:,'Temperature (K)']==20.0007820129395)[0][0]
print ind
mh_squid = np.array([v[:ind,'Temperature (K)'],v[:ind,'Magnetic Field (Oe)']/10000,v[:ind,'DC Moment Free Ctr (emu)']/0.04842*1152.76/5585/3]).T
#print mh_squid
from Stoner import Data

```

    177

TDI Format 1.5
index  	   Time Stamp (sec)
      1 (x)	       ....
           	     Moment (emu)
      4 (y)	  M. Std. Err. (emu)
        5	       ....
           	        Map 16
        68

Byapp{String}= MPMS3      	                        3.74461e+09	                           	                              nan	                               nan	                           	                          nan

1.0 1.1                   	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Datatype,Comment{I32      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

}= 1                      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Datatype,Time{I32}=       	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

2                         	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Fieldgroup.Dc{List}=      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

[2, 3, 4, 14, 34,         	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

35, 36, 37, 38, 39,       	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

40, 41, 42, 43, 44,       	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

45, 46, 47]               	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Fieldgroup.Vsm{List}      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

= [2, 3, 4, 5, 6,         	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

8, 9, 10, 11, 14,         	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

15]                       	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Fileopentime{String}      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

= 3744613099.34556        	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

08/28/2018 10:22 am       	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Moment_Units{I3      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

2}= 0                     	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Multivu Release      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

2.3.3.2{String}=          	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

MPMS3 Measurement         	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Release 1.1.16            	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Build 347                 	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Comment{      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

String}= First            	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

batch                     	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Holder{S      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

tring}= Not               	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Specified                 	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Holder_D      	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

etail{String}=            	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Standard                  	                        3.74461e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Mass{Dou      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

ble Float}= 48.42         	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Material      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

{String}=                 	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Nd3Sb3Zn2O14              	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Molecula      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

r_Weight{Double           	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Float}= 1152.77           	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Offset{D      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

ouble Float}= 66.73       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Shape{I3      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

2}= 1                     	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Size{I32      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

}= 1                      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Info.Sample_Volume{I      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

32}= 1                    	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Loaded as{String}=        	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

QDFile                    	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Startupaxis-X{I32}=       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

2                         	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Startupaxis-Y1{I32}=      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

5                         	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Startupgroup,All{Str      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

ing}= None                	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Stoner.class{String}      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

= Data                    	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

Title,Nd3Sb3Zn2O14{S      	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

tring}= None              	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74462e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74463e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74464e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74464e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74464e+09	...                        	                              nan	                               nan	...                        	                          nan

...                       	                        3.74464e+09	...                        	                              nan	                               nan	...                        	                          nan

```python
# Fit g factor
popt, pcov = optimize.curve_fit(multi_visingpow, mh[:,0:2], mh[:,2], p0=5.2)
print popt
```

    [ 4.66155106]

```python
Ts = [1.8, 5, 10, 20]
fig = plt.figure(figsize=(5,4))
plt.plot(mh[:,1],mh[:,2],'o',markevery=0.03,label='VSM')

hdat=np.linspace(0.001,7, 100)
for t in np.hstack(([.1],Ts)).ravel():
    ydat = visingpow(hdat, t, popt)
    plt.plot(hdat,ydat)

plt.plot(mh_squid[:,1], mh_squid[:,2],'o',ms=1,c='black',label='SQUID')

plt.legend()
plt.show()
```

    <IPython.core.display.Javascript object>

```python
mt = v[ind+1:,['Temperature (K)','DC Moment Free Ctr (emu)']]
mt = Data(mt,column_headers=['Temperature (K)','DC Moment Free Ctr (emu)'], setas="xy")

mt.multiply('DC Moment Free Ctr (emu)', 1./1000/0.04842*1152.76/3, header='DC Moment Free Ctr (emu)', replace=True)

def chicw(t,tcw,mu,chivv):
    return 0.125 * mu**2 / (t-tcw) + chivv

fit=mt.curve_fit(chicw, xcol='Temperature (K)', ycol='DC Moment Free Ctr (emu)', bounds=lambda x,y: 5<x<15,
                 result=True,replace=False,header="Fit",output="report")

print(fit.report.popt)

#mt.plot(fmt='o')

plt.figure()
plt.plot(mt[:,0],1/mt[:,1],'o',mfc='none')
plt.plot(mt[:,0],1/mt[:,2])
plt.xlim([0,30])
plt.ylim([0,50])
plt.show()
```

    [ 0.14339458  2.15158862  0.00542373]

    <IPython.core.display.Javascript object>

```python

```

## MH fitting of Sm2Zr2O7

```python
# Load and plot MH data
fpath = r'D:\3_Physical Properties\Sm2Zr2O7\SmZrO_pow_MH_2k_0-7T.txt'
fpath = r'D:\3_Physical Properties\Sm2Zr2O7\Sm2Zr2O7_29_03_2017_powder_MH_2-3-5-7K.txt' # why ten times smaller than old dat
mhdat = np.genfromtxt(fpath, usecols=(0,1), skip_header=0)
mhdat = np.hstack(np.vsplit(mhdat,4))# just for the 'MH 2-3-5-7K'
#print mhdat
Ts = [1.8] # temperatures or set 2K
Ts = [2, 3, 5, 7] # temperatures or set 2K
for i in xrange(0, mhdat.shape[1],2):
    mhdat[:,i] = mhdat[:,i] / 10000. # change the unit to Tesla

#plot data
for i in xrange(0, mhdat.shape[1],2):
    plt.plot(mhdat[:,i],mhdat[:,i+1],'*')
```

```python
def err(t, g, x,y):
    x, y = x[~np.isnan(x)], y[~np.isnan(y)]
    #err = visingpow(x, t, g) - y # use vectorized scipy function
    err = np.array([isingpow(x[i], t, g) - y[i] for i in np.arange(0, x.shape[0])]).ravel()
    return err
# have to put "ravel()" or 'flatten()' otherwise error on 'hstack' when using leastsq (no problem for non-fit use)

def err_global(g):
    err0=[]
    for i in range(len(Ts)):
        errc=err(Ts[i], g, mhdat[:,i*2],mhdat[:,i*2+1])
        err1=np.concatenate((err0,errc))
        err0=err1
    return err0 #(err0**2).sum()

# fit
p_best,success=optimize.leastsq(err_global, 0.3)
print p_best, success
#print err_global(p_best)
```

    [ 0.56365864] 1

```python
# plot dat and fit
fig = plt.figure(figsize=(5,4))
for i in xrange(0, mhdat.shape[1],2):
    plt.plot(mhdat[:,i],mhdat[:,i+1],linestyle='none', marker='o',mfc='none', mec='black', label='Data')

xdat=np.linspace(0.01,7, 100)
for t in Ts:
    ydat = np.array([isingpow(xdat[i], t, p_best[0]) for i in np.arange(0, xdat.shape[0])])
    plt.plot(xdat,ydat,c='r',label='Fit')
# for t in np.hstack(([0.1, 0.5, 1],Ts)).ravel():
#     ydat = np.array([isingpow(xdat[i], t, p_best[0]) for i in np.arange(0, xdat.shape[0])])
#     plt.plot(xdat,ydat)

# plt.text(5,0.02,'Sm$_2$Zr$_2$O$_7$\n1.8 K',size=14, ha='left', va='center',
#             backgroundcolor='white',bbox=dict(facecolor='none', edgecolor='white', boxstyle='round'))

plt.xlabel('B (T)',size=14)
plt.ylabel('M ($\mu_B$/Sm)',size=14)

plt.minorticks_on()
plt.xticks( color='k', size=14)
plt.yticks( color='k', size=14)
plt.legend(loc='best',numpoints=1,frameon=False,framealpha=1,fontsize=14)
#fig.savefig(r'D:\3_Physical Properties\Sm2Zr2O7\SmZrO_pow_MH_2k_0-7T_fit.pdf', bbox_inches="tight",verbose=True)
plt.show()

```

```python
np.savetxt(r'D:\3_Physical Properties\Sm2Zr2O7\SmZrO_pow_MH_2k_0-7T_fit.txt',np.vstack([xdat*10000,ydat]).T,fmt='%.5f')

```

# Tb2Hf2O7 Ising fit

```python
# Load and plot MH data
fpath = r'D:\3_Physical Properties\Tb2Ti2O7/MH_TbHfO_2K.dat'
mhdat = np.genfromtxt(fpath, usecols=(0,1), skip_header=0)
#print mhdat
Ts = [2] # temperatures or set 2K
mhdat[:,0] = mhdat[:,0] / 10000. # change the unit to Tesla
mhdat[:,1] = mhdat[:,1]/5585/2

#plot data
% matplotlib inline
plt.plot(mhdat[:,0],mhdat[:,1],'*')
plt.show()
```

```python
def err(t, g, x,y):
    x, y = x[~np.isnan(x)], y[~np.isnan(y)]
    #err = visingpow(x, t, g) - y # use vectorized scipy function
    err = np.array([isingpow(x[i], t, g) - y[i] for i in np.arange(0, x.shape[0])]).ravel()
    return err
# have to put "ravel()" or 'flatten()' otherwise error on 'hstack' when using leastsq (no problem for non-fit use)

def err_global(g):
    err0=[]
    for i in range(len(Ts)):
        errc=err(Ts[i], g, mhdat[:,i*2],mhdat[:,i*2+1])
        err1=np.concatenate((err0,errc))
        err0=err1
    return err0 #(err0**2).sum()

# fit
p_best,success=optimize.leastsq(err_global, 50)
print p_best, success
#print err_global(p_best)
```

    [ 0.3620708] 1

```python
fig = plt.figure(figsize=(5,4))
for i in xrange(0, mhdat.shape[1],2):
    plt.plot(mhdat[:,i],mhdat[:,i+1],linestyle='none', marker='o',mfc='none', mec='black', label='Data')

xdat=np.linspace(0.01,14, 100)
for t in Ts:
    ydat = np.array([isingpow(xdat[i], t, 12) for i in np.arange(0, xdat.shape[0])])
    plt.plot(xdat,ydat,label='g=12')
    ydat = np.array([isingpow(xdat[i], t, 14) for i in np.arange(0, xdat.shape[0])])
    plt.plot(xdat,ydat,label='g=14')
    ydat = np.array([isingpow(xdat[i], t, 16) for i in np.arange(0, xdat.shape[0])])
    plt.plot(xdat,ydat,label='g=16')
    ydat = np.array([isingpow(xdat[i], t, 18) for i in np.arange(0, xdat.shape[0])])
    plt.plot(xdat,ydat,label='g=18')
    ydat = np.array([isingpow(xdat[i], t, 20) for i in np.arange(0, xdat.shape[0])])
    plt.plot(xdat,ydat,label='g=20')

plt.xlabel('H (T)',size=14)
plt.ylabel('M ($\mu_B$/Tb)',size=14)

plt.minorticks_on()
plt.xticks( color='k', size=14)
plt.yticks( color='k', size=14)
plt.legend(loc='best',numpoints=1,frameon=False,framealpha=1,fontsize=14)
#fig.savefig(r'D:\3_Physical Properties\Sm2Zr2O7\SmZrO_pow_MH_2k_0-7T_fit.pdf', bbox_inches="tight",verbose=True)
plt.show()
```

# Heisenburg spin

```python
#　ＭＨ（Ｔ）　ｆｏｒ　　Ｈｅｉｓｅｎｂｕｒｇ　ｓｐｉｎ，　ｅｇ，Ｇｄ２Ｚｒ２Ｏ７

# use Ｓｙｍｐｙ which is not necessary. in the next cell we use numpy
import numpy as np
import sympy as sp

J = 3.5 # for Gd3+

mb = 0.6717 # in K/T, so field h is in T
kb = 1.0 # because mb is in K/T
j,t,g,h = sp.symbols('j,t,g,h')
def heisenM(h, t, g):
    # allp = sp.Sum(sp.exp(mb*g*j*h/(kb*t)),(j,-J, J)) # Sum: not work for non-integal J
    # m = sp.Sum(g*j*sp.exp(mb*g*j*h/(kb*t)),(j,-J, J))/allp

    allp = sum(sp.exp(mb*g*j*h/(kb*t)) for j in np.arange(-J, J+1)) # sum: list comprihensive
    m = sum(g*j*sp.exp(mb*g*j*h/(kb*t)) for j in np.arange(-J, J+1))/allp
    return m

#print heisenM(14., 5, 2.).doit()
heisenM = sp.lambdify((h, t,g), heisenM(h, t,g), modules=['numpy', 'sympy']) # vectorize the function

xdat=np.linspace(0.01,14, 100)
temps = np.array([2,5,10,20])

for temps in temps:
    ydat = heisenM(xdat,temps, 2.)
    plt.plot(xdat,ydat)
```

```python
# use　ｎｕｍｐｙ

J = 3.5 # for Gd3+

mb = 0.6717 # in K/T, so field h is in T
kb = 1.0 # because mb is in K/T

def heisenM(h, t, g):
    allp = sum(np.exp(mb*g*j*h/(kb*t)) for j in np.arange(-J, J+1))
    m = sum(g*j*np.exp(mb*g*j*h/(kb*t)) for j in np.arange(-J, J+1))/allp
    return m

xdat=np.linspace(0.01,14, 100)
temps = np.array([2,5,10,20])
# heisenM(xdat,temps, 2.) could not brodacast

for temps in temps:
    ydat = heisenM(xdat,temps, 2.)
    plt.plot(xdat,ydat)
```

```python
# load mh data
fpath = r'D:\3_Physical Properties\Gd2Zr2O7\1_Gd2Zr2O7_pow_MH.txt'
mhdat = np.genfromtxt(fpath, usecols=(0,1,2,3,4,5), skip_header=1) # MH at 1.8, 5, 10K

Ts = [1.8, 5., 10.] # temperatures

for i in xrange(0, mhdat.shape[1],2):
    mhdat[:,i] = mhdat[:,i] / 10000. # change the unit to Tesla

#print mhdat[:,0]
for i in xrange(0, mhdat.shape[1],2):
    plt.plot(mhdat[:,i],mhdat[:,i+1])

```

```python
# multicureve fitting: def a global error
from scipy import optimize
import scipy as sc

def err(t,g, x,y):
    x, y = x[~np.isnan(x)], y[~np.isnan(y)]
    return heisenM(x, t, g) - y

def err_global(g):
    err0=[]
    for i in range(len(Ts)):
        errc=err(Ts[i], g, mhdat[:,i*2],mhdat[:,i*2+1])
        err1=np.concatenate((err0,errc))
        err0=err1
    return err0

# fit
p_best,success=optimize.leastsq(err_global, 2.)
print p_best, success
#print err_global(p_best)

# plot dat and fit
fig = plt.figure(figsize=(5,4))
for i in xrange(0, mhdat.shape[1],2):
    plt.plot(mhdat[:,i],mhdat[:,i+1],'*')

xdat=np.linspace(0.01,14, 100)
for t in Ts:
    ydat = heisenM(xdat, t, p_best[0])
    plt.plot(xdat,ydat)

plt.show()
```

```python
# single cruve fitting

def err(p, x, y):
    t, g = p[0], p[1]
    #print t, g
    #x, y = x[~np.isnan(x)], y[~np.isnan(y)]
    return heisenM(x, t, g) - y

fig = plt.figure(figsize=(5,4))
colors = ['red','blue','black']

xdat=np.linspace(0.01,14, 100)
for i in range(len(Ts)):
    x, y = mhdat[~np.isnan(mhdat[:,i*2]), i*2], mhdat[~np.isnan(mhdat[:,i*2+1]), i*2+1]

    # use curve_fit()
    #popt, pcov = optimize.curve_fit(heisenM, x, y) # fit both t and g
    popt, pcov = optimize.curve_fit( lambda h, g: heisenM(h, Ts[i],g), x, y) # fix t as the real one
    print popt

    # use leastsq()
    # p,cov, infodict, mesg, ier = optimize.leastsq(err, p_guess, args=(x,y),full_output=True)# fit both t and g
    p,cov, infodict, mesg, ier = optimize.leastsq( lambda g: err([Ts[i],g], x, y), 2., full_output=True)# only fit g
    print p #, infodict, mesg, ier

    plt.plot(x, y, '*')

    ydat = heisenM(xdat, Ts[i], p[0])
    plt.plot(xdat,ydat,c=colors[i])

plt.show()

# export simulated data with g=2
expdat = np.zeros((100,4))
expdat[:,0] = xdat[:]
for i in range(len(Ts)):
    expdat[:,i+1] = heisenM(xdat, Ts[i], 2.)
#print expdat

# np.savetxt(r'D:\3_Physical Properties\Gd2Zr2O7\1_Gd2Zr2O7_pow_MH_cal_g2.txt', expdat, fmt='%1.4e')
```

```python
#　ＭＨ(z)　ｃａｌｃｕｌａｔｅｄ　ｂｙ　Ｓｐｅｃｔｒａ　ｗｉｔｈ　ｔｈｅ　Ｓｃａｌｅｄ　Ｎｄ　ＣＥＦ　ｐａｒｓ
# ｗｈｉｃｈ　ｉｓ　ｔｈｅ　ｓａｍｅ　ｗｉｔｈ　ｏｕｒｓ
import string

f = r'D:\9_Program files\crystal_field\Gd_scaledNd_MHz_2K.dat'

rule = string.maketrans('D', 'E') # make a translation table (rules) for translating a string (D to E in the numbers)

temp = np.genfromtxt(f, usecols=(0,1,2,3), \
                     converters = {1: lambda val: float(val.translate(rule)),
                                   2: lambda val: float(val.translate(rule)),
                                   3: lambda val: float(val.translate(rule))})
# 'val' given by 'genfromtxt' is a string, we can so use 'transleate' method

plt.plot(temp[:,0],temp[:,3],c='red')

xdat=np.linspace(0.01,14, 100)
ydat = heisenM(xdat, 2., 2.)
plt.plot(xdat,ydat,c='black')

```

```python

```


$ \newcommand{\bra}[1]{\langle #1|} $
$ \newcommand{\ket}[1]{|#1\rangle} $
$ \newcommand{\braket}[2]{\langle #1|#2\rangle} $
$ \newcommand{\dot}[2]{ #1 \cdot #2} $
$ \newcommand{\biginner}[2]{\left\langle #1,#2\right\rangle} $
$ \newcommand{\mymatrix}[2]{\left( \begin{array}{#1} #2\end{array} \right)} $
$ \newcommand{\myvector}[1]{\mymatrix{c}{#1}} $
$ \newcommand{\myrvector}[1]{\mymatrix{r}{#1}} $
$ \newcommand{\mypar}[1]{\left( #1 \right)} $
$ \newcommand{\mybigpar}[1]{ \Big( #1 \Big)} $
$ \newcommand{\sqrttwo}{\frac{1}{\sqrt{2}}} $
$ \newcommand{\dsqrttwo}{\dfrac{1}{\sqrt{2}}} $
$ \newcommand{\onehalf}{\frac{1}{2}} $
$ \newcommand{\donehalf}{\dfrac{1}{2}} $
$ \newcommand{\hadamard}{ \mymatrix{rr}{ \sqrttwo & \sqrttwo \\ \sqrttwo & -\sqrttwo }} $
$ \newcommand{\vzero}{\myvector{1\\0}} $
$ \newcommand{\vone}{\myvector{0\\1}} $
$ \newcommand{\stateplus}{\myvector{ \sqrttwo \\  \sqrttwo } } $
$ \newcommand{\stateminus}{ \myrvector{ \sqrttwo \\ -\sqrttwo } } $
$ \newcommand{\myarray}[2]{ \begin{array}{#1}#2\end{array}} $
$ \newcommand{\X}{ \mymatrix{cc}{0 & 1 \\ 1 & 0}  } $
$ \newcommand{\I}{ \mymatrix{rr}{1 & 0 \\ 0 & 1}  } $
$ \newcommand{\Z}{ \mymatrix{rr}{1 & 0 \\ 0 & -1}  } $
$ \newcommand{\Htwo}{ \mymatrix{rrrr}{ \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & \frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} & \frac{1}{2} } } $
$ \newcommand{\CNOT}{ \mymatrix{cccc}{1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0} } $
$ \newcommand{\norm}[1]{ \left\lVert #1 \right\rVert } $
$ \newcommand{\pstate}[1]{ \lceil \mspace{-1mu} #1 \mspace{-1.5mu} \rfloor } $
$ \newcommand{\greenbit}[1] {\mathbf{{\color{green}#1}}} $
$ \newcommand{\bluebit}[1] {\mathbf{{\color{blue}#1}}} $
$ \newcommand{\redbit}[1] {\mathbf{{\color{red}#1}}} $
$ \newcommand{\brownbit}[1] {\mathbf{{\color{brown}#1}}} $
$ \newcommand{\blackbit}[1] {\mathbf{{\color{black}#1}}} $

 Qiskit installation and test

_prepared by Abuzer Yakaryilmaz_

- [Check your system](#check)
- [Install qiskit](#install)
- [Tips](#tips)
- [Execute an example quantum program](#test)

### Check your system

Check your system, if Qiskit has already been installed:

```python
import qiskit
versions = qiskit.__qiskit_version__
print("The version of Qiskit is",versions['qiskit'])
print()
print("The version of each component:")
for key in versions:
    print(key,"->",versions[key])
```

    The version of Qiskit is 0.30.0

    The version of each component:
    qiskit-terra -> 0.18.2
    qiskit-aer -> 0.9.0
    qiskit-ignis -> 0.6.0
    qiskit-ibmq-provider -> 0.16.0
    qiskit-aqua -> 0.9.5
    qiskit -> 0.30.0
    qiskit-nature -> None
    qiskit-finance -> None
    qiskit-optimization -> None
    qiskit-machine-learning -> None

    C:\Users\angel\anaconda3\lib\site-packages\qiskit\aqua\__init__.py:86: DeprecationWarning: The package qiskit.aqua is deprecated. It was moved/refactored to qiskit-terra For more information see <https://github.com/Qiskit/qiskit-aqua/blob/main/README.md#migration-guide>
      warn_package('aqua', 'qiskit-terra')

**You should be able to see the version number of any library that is already installed in your system.**

### Install qiskit

(If you are an experienced user, visit this link: https://qiskit.org/documentation/install.html)

You can install Qiskit by executing the following cell:

```python
!pip install "qiskit[visualization]" --user
```

    Requirement already satisfied: qiskit[visualization] in c:\users\angel\anaconda3\lib\site-packages (0.30.0)
    Requirement already satisfied: qiskit-aqua==0.9.5 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (0.9.5)
    Requirement already satisfied: qiskit-ignis==0.6.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (0.6.0)
    Requirement already satisfied: qiskit-terra==0.18.2 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (0.18.2)
    Requirement already satisfied: qiskit-aer==0.9.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (0.9.0)
    Requirement already satisfied: qiskit-ibmq-provider==0.16.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (0.16.0)
    Requirement already satisfied: pillow>=4.2.1 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (8.2.0)
    Requirement already satisfied: seaborn>=0.9.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (0.11.1)
    Requirement already satisfied: pylatexenc>=1.4 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (2.10)
    Collecting pydot
      Downloading pydot-1.4.2-py2.py3-none-any.whl (21 kB)
    Requirement already satisfied: matplotlib>=2.1 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (3.3.4)
    Requirement already satisfied: pygments>=2.4 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (2.8.1)
    Requirement already satisfied: ipywidgets>=7.3.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit[visualization]) (7.6.3)
    Requirement already satisfied: pybind11>=2.6 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aer==0.9.0->qiskit[visualization]) (2.7.1)
    Requirement already satisfied: scipy>=1.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aer==0.9.0->qiskit[visualization]) (1.6.2)
    Requirement already satisfied: numpy>=1.16.3 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aer==0.9.0->qiskit[visualization]) (1.20.1)
    Requirement already satisfied: h5py<3.3.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (2.10.0)
    Requirement already satisfied: scikit-learn>=0.20.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (0.24.1)
    Requirement already satisfied: retworkx>=0.8.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (0.10.2)
    Requirement already satisfied: dlx<=1.0.4 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (1.0.4)
    Requirement already satisfied: sympy>=1.3 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (1.8)
    Requirement already satisfied: yfinance>=0.1.62 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (0.1.63)
    Requirement already satisfied: setuptools>=40.1.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (52.0.0.post20210125)
    Requirement already satisfied: pandas in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (1.2.4)
    Requirement already satisfied: docplex>=2.21.207 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (2.22.213)
    Requirement already satisfied: quandl in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (3.6.1)
    Requirement already satisfied: psutil>=5 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (5.8.0)
    Requirement already satisfied: fastdtw<=0.3.4 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (0.3.4)
    Requirement already satisfied: websocket-client>=1.0.1 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (1.2.1)
    Requirement already satisfied: python-dateutil>=2.8.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (2.8.1)
    Requirement already satisfied: requests>=2.19 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (2.25.1)
    Requirement already satisfied: urllib3>=1.21.1 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (1.26.4)
    Requirement already satisfied: requests-ntlm>=1.1.0 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (1.1.0)
    Requirement already satisfied: python-constraint>=1.4 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-terra==0.18.2->qiskit[visualization]) (1.4.0)
    Requirement already satisfied: jsonschema>=2.6 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-terra==0.18.2->qiskit[visualization]) (3.2.0)
    Requirement already satisfied: fastjsonschema>=2.10 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-terra==0.18.2->qiskit[visualization]) (2.15.1)
    Requirement already satisfied: ply>=3.10 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-terra==0.18.2->qiskit[visualization]) (3.11)
    Requirement already satisfied: dill>=0.3 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-terra==0.18.2->qiskit[visualization]) (0.3.4)
    Requirement already satisfied: tweedledum<2.0,>=1.1 in c:\users\angel\anaconda3\lib\site-packages (from qiskit-terra==0.18.2->qiskit[visualization]) (1.1.1)
    Requirement already satisfied: six in c:\users\angel\anaconda3\lib\site-packages (from docplex>=2.21.207->qiskit-aqua==0.9.5->qiskit[visualization]) (1.15.0)
    Requirement already satisfied: ipykernel>=4.5.1 in c:\users\angel\anaconda3\lib\site-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (5.3.4)
    Requirement already satisfied: ipython>=4.0.0 in c:\users\angel\anaconda3\lib\site-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (7.22.0)
    Requirement already satisfied: nbformat>=4.2.0 in c:\users\angel\anaconda3\lib\site-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (5.1.3)
    Requirement already satisfied: traitlets>=4.3.1 in c:\users\angel\anaconda3\lib\site-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (5.0.5)
    Requirement already satisfied: jupyterlab-widgets>=1.0.0 in c:\users\angel\anaconda3\lib\site-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (1.0.0)
    Requirement already satisfied: widgetsnbextension~=3.5.0 in c:\users\angel\anaconda3\lib\site-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (3.5.1)
    Requirement already satisfied: tornado>=4.2 in c:\users\angel\anaconda3\lib\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[visualization]) (6.1)
    Requirement already satisfied: jupyter-client in c:\users\angel\anaconda3\lib\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[visualization]) (6.1.12)
    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in c:\users\angel\anaconda3\lib\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (3.0.17)
    Requirement already satisfied: decorator in c:\users\angel\anaconda3\lib\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (5.0.6)
    Requirement already satisfied: backcall in c:\users\angel\anaconda3\lib\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.2.0)
    Requirement already satisfied: colorama in c:\users\angel\anaconda3\lib\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.4.4)
    Requirement already satisfied: jedi>=0.16 in c:\users\angel\anaconda3\lib\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.17.2)
    Requirement already satisfied: pickleshare in c:\users\angel\anaconda3\lib\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.7.5)
    Requirement already satisfied: parso<0.8.0,>=0.7.0 in c:\users\angel\anaconda3\lib\site-packages (from jedi>=0.16->ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.7.0)
    Requirement already satisfied: pyrsistent>=0.14.0 in c:\users\angel\anaconda3\lib\site-packages (from jsonschema>=2.6->qiskit-terra==0.18.2->qiskit[visualization]) (0.17.3)
    Requirement already satisfied: attrs>=17.4.0 in c:\users\angel\anaconda3\lib\site-packages (from jsonschema>=2.6->qiskit-terra==0.18.2->qiskit[visualization]) (20.3.0)
    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in c:\users\angel\anaconda3\lib\site-packages (from matplotlib>=2.1->qiskit[visualization]) (2.4.7)
    Requirement already satisfied: cycler>=0.10 in c:\users\angel\anaconda3\lib\site-packages (from matplotlib>=2.1->qiskit[visualization]) (0.10.0)
    Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\angel\anaconda3\lib\site-packages (from matplotlib>=2.1->qiskit[visualization]) (1.3.1)
    Requirement already satisfied: jupyter-core in c:\users\angel\anaconda3\lib\site-packages (from nbformat>=4.2.0->ipywidgets>=7.3.0->qiskit[visualization]) (4.7.1)
    Requirement already satisfied: ipython-genutils in c:\users\angel\anaconda3\lib\site-packages (from nbformat>=4.2.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.2.0)
    Requirement already satisfied: wcwidth in c:\users\angel\anaconda3\lib\site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.2.5)
    Requirement already satisfied: chardet<5,>=3.0.2 in c:\users\angel\anaconda3\lib\site-packages (from requests>=2.19->qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (4.0.0)
    Requirement already satisfied: certifi>=2017.4.17 in c:\users\angel\anaconda3\lib\site-packages (from requests>=2.19->qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (2020.12.5)
    Requirement already satisfied: idna<3,>=2.5 in c:\users\angel\anaconda3\lib\site-packages (from requests>=2.19->qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (2.10)
    Requirement already satisfied: cryptography>=1.3 in c:\users\angel\anaconda3\lib\site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (3.4.7)
    Requirement already satisfied: ntlm-auth>=1.0.2 in c:\users\angel\anaconda3\lib\site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (1.5.0)
    Requirement already satisfied: cffi>=1.12 in c:\users\angel\anaconda3\lib\site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (1.14.5)
    Requirement already satisfied: pycparser in c:\users\angel\anaconda3\lib\site-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.16.0->qiskit[visualization]) (2.20)
    Requirement already satisfied: joblib>=0.11 in c:\users\angel\anaconda3\lib\site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit[visualization]) (1.0.1)
    Requirement already satisfied: threadpoolctl>=2.0.0 in c:\users\angel\anaconda3\lib\site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit[visualization]) (2.1.0)
    Requirement already satisfied: pytz>=2017.3 in c:\users\angel\anaconda3\lib\site-packages (from pandas->qiskit-aqua==0.9.5->qiskit[visualization]) (2021.1)
    Requirement already satisfied: mpmath>=0.19 in c:\users\angel\anaconda3\lib\site-packages (from sympy>=1.3->qiskit-aqua==0.9.5->qiskit[visualization]) (1.2.1)
    Requirement already satisfied: notebook>=4.4.1 in c:\users\angel\anaconda3\lib\site-packages (from widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (6.3.0)
    Requirement already satisfied: prometheus-client in c:\users\angel\anaconda3\lib\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.10.1)
    Requirement already satisfied: argon2-cffi in c:\users\angel\anaconda3\lib\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (20.1.0)
    Requirement already satisfied: nbconvert in c:\users\angel\anaconda3\lib\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (6.0.7)
    Requirement already satisfied: terminado>=0.8.3 in c:\users\angel\anaconda3\lib\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.9.4)
    Requirement already satisfied: jinja2 in c:\users\angel\anaconda3\lib\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (2.11.3)
    Requirement already satisfied: pyzmq>=17 in c:\users\angel\anaconda3\lib\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (20.0.0)
    Requirement already satisfied: Send2Trash>=1.5.0 in c:\users\angel\anaconda3\lib\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (1.5.0)
    Requirement already satisfied: pywin32>=1.0 in c:\users\angel\anaconda3\lib\site-packages (from jupyter-core->nbformat>=4.2.0->ipywidgets>=7.3.0->qiskit[visualization]) (227)
    Requirement already satisfied: pywinpty>=0.5 in c:\users\angel\anaconda3\lib\site-packages (from terminado>=0.8.3->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.5.7)
    Requirement already satisfied: lxml>=4.5.1 in c:\users\angel\anaconda3\lib\site-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit[visualization]) (4.6.3)
    Requirement already satisfied: multitasking>=0.0.7 in c:\users\angel\anaconda3\lib\site-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit[visualization]) (0.0.9)
    Requirement already satisfied: MarkupSafe>=0.23 in c:\users\angel\anaconda3\lib\site-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (1.1.1)
    Requirement already satisfied: jupyterlab-pygments in c:\users\angel\anaconda3\lib\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.1.2)
    Requirement already satisfied: bleach in c:\users\angel\anaconda3\lib\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (3.3.0)
    Requirement already satisfied: testpath in c:\users\angel\anaconda3\lib\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.4.4)
    Requirement already satisfied: pandocfilters>=1.4.1 in c:\users\angel\anaconda3\lib\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (1.4.3)
    Requirement already satisfied: nbclient<0.6.0,>=0.5.0 in c:\users\angel\anaconda3\lib\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.5.3)
    Requirement already satisfied: defusedxml in c:\users\angel\anaconda3\lib\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.7.1)
    Requirement already satisfied: entrypoints>=0.2.2 in c:\users\angel\anaconda3\lib\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.3)
    Requirement already satisfied: mistune<2,>=0.8.1 in c:\users\angel\anaconda3\lib\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.8.4)
    Requirement already satisfied: async-generator in c:\users\angel\anaconda3\lib\site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (1.10)
    Requirement already satisfied: nest-asyncio in c:\users\angel\anaconda3\lib\site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (1.5.1)
    Requirement already satisfied: webencodings in c:\users\angel\anaconda3\lib\site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.5.1)
    Requirement already satisfied: packaging in c:\users\angel\anaconda3\lib\site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (20.9)
    Requirement already satisfied: more-itertools in c:\users\angel\anaconda3\lib\site-packages (from quandl->qiskit-aqua==0.9.5->qiskit[visualization]) (8.7.0)
    Requirement already satisfied: inflection>=0.3.1 in c:\users\angel\anaconda3\lib\site-packages (from quandl->qiskit-aqua==0.9.5->qiskit[visualization]) (0.5.1)
    Installing collected packages: pydot
    Successfully installed pydot-1.4.2

__*Restart the kernel*__ (check "Kernel" menu) to apply the changes to the current notebook.

### Tips

_Any terminal/shell command can be executed in the notebook cells by putting an exclamation mark (!) at the beginning of the command._

_$\rightarrow$ To update Qiskit to the latest version, execute the following command in a code cell_

    !pip install -U qiskit --user

_$\rightarrow$ To uninstall Qiskit, execute the following command in a code cell_

    !pip uninstall qiskit

```python
#!pip install -U qiskit --user
#!pip uninstall qiskit
```

### Execute an example quantum program

1) Create a quantum circuit

```python
# import the objects from qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from random import randrange

# create a quantum circuit and its register objects
qreg = QuantumRegister(2) # quantum register with two quantum bits
creg = ClassicalRegister(2) # classical register with two classical bit
circuit = QuantumCircuit(qreg,creg) # quantum circuit composed by a quantum register and a classical register

# apply a Hadamard gate to the first qubit
circuit.h(qreg[0])

# set the second qubit to state |1>
circuit.x(qreg[1])

# apply CNOT(first_qubit,second_qubit)
circuit.cx(qreg[0],qreg[1])

# measure the both qubits
circuit.measure(qreg,creg)

print("The execution of the cell was completed, and the circuit was created :)")
```

    The execution of the cell was completed, and the circuit was created :)

2) Draw the circuit

_Run the cell once more if the figure is not shown_

```python
# draw circuit
circuit.draw(output='mpl')

# the output will be a "matplotlib.Figure" object
```

3) Execute the circuit 1024 times in the local simulator and print the observed the outcomes

```python
## execute the circuit 1024 times
job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024)
# get the result
counts = job.result().get_counts(circuit)
print(counts)
```

    {'10': 487, '01': 537}

```python

```