2020年4月13日 星期一

Python 學習筆記 : SciPy 測試 (一) : 科學常數

這學期二哥開始修工程數學, 會用到 SciPy 解方程式等計算, 為了避免被問倒, 我也開始複習工數與微積分, Python 數值計算工具 SciPy 也要開始測試學習.

Scipy 是以 Travis Oliphant 於 2006 年撰寫的 Numpy 套件為基礎所發展的 Python 科學計算套件,  2001 年 Travis Oliphant, Pearu Peterson, Eric Jones 等人將 Numpy 與他們所撰寫的程式整合為 SciPy, 並以 BSD 授權開源, 功能包含線性代數, 數值積分, 數值微分, 求矩陣特徵值, 解聯立方程式, 快速傅立葉變換, 統計分析, 影像處理, 數位信號處理, 非監督式機器學習等模組 (監督式是放在 scikit-learn 套件中) 等等. SciPy 裡面的很多底層函數都是用 Fortran 實作的, 因此運算效能優異, 可與 MATLAB 以及 Octave 等商業軟體相匹敵.

參考 :

# Wiki : SciPy
https://en.wikipedia.org/wiki/SciPy

教學文件參考 :

https://www.scipy.org/docs.html
https://docs.scipy.org/doc/scipy/reference/index.html

SciPy 相關書籍參考 :

# SciPy and Numpy (Oreilly, 2013)
Elegant SciPy: The Art of Scientific Python (Oreilly, 2017)
Learning SciPy for Numerical and Scientific Computing 2nd Edition (Packt, 2015)
Numerical Methods in Engineering with Python 3 (Cambridge, 2013)# Numerical Python: Scientific Computing and Data Science Applications With Numpy, Scipy and Matplotlib 2nd Edition (Apress, 2018)


一. 安裝 SciPy :

可在命令列下以 pip 安裝 SciPy (大約 31MB 左右) :

pip3 install scipy

或加 -U 參數更新到最新版 :

pip3 install scipy -U

D:\>pip3 install scipy -U
Collecting scipy
  Downloading scipy-1.4.1-cp37-cp37m-win_amd64.whl (30.9 MB)
Requirement already satisfied, skipping upgrade: numpy>=1.13.3 in c:\python37\lib\site-packages (from scipy) (1.16.0)
Installing collected packages: scipy
  Attempting uninstall: scipy
    Found existing installation: scipy 1.2.0
    Uninstalling scipy-1.2.0:
      Successfully uninstalled scipy-1.2.0
Successfully installed scipy-1.4.1

因為 SciPy 是以 Numpy 為基礎, 故安裝 SciPy 時會先裝 Numpy.

完成後進入 Python IDLE 介面用 __version__ 屬性檢查 SciPy 版本, 使用前先匯入 scipy 套件 :

D:\>python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy   
>>> scipy.__version__ 
'1.4.1'

使用 import scipy 方式匯入的話, 使用其屬性或模組時前面都要帶 scipy. 才行, 也可以直接匯入全部 SciPy 模組, 這樣就不需冠上 scipi. 了 (但要注意命名空間汙染問題) :

from scipy import * 

>>> from scipy import * 
>>> __version__ 
'1.4.1'


二. SciPy 的模組 : 

SciPy 由許多子套件組成, 常用的子套件如下表 :


 SciPy 常用子套件 說明
 constants 科學常數
 specials 特殊函數
 integrate 解積分或微分方程式
 linalg 線性代數
 stats 統計函數
 fftpack 快速傅立葉轉換函數
 interpolate 內插平滑函數
 optimize 最佳化與求解函數
 sparse 稀疏矩陣函數
 signal 信號處理


SciPy 所有子套件可用 dir() 檢視 :

>>> import scipy
>>> dir(scipy) 
['ALLOW_THREADS', 'AxisError', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'LowLevelCallable', 'MAXDIMS', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'MachAr', 'ModuleDeprecationWarning', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', 'TooHardError', 'True_', 'UFUNC_BUFSIZE_DEFAULT', 'UFUNC_PYVALS_NAME', 'VisibleDeprecationWarning', 'WRAP', '_UFUNC_API', '__SCIPY_SETUP__', '__all__', '__builtins__', '__cached__', '__config__', '__doc__', '__file__', '__loader__', '__name__', '__numpy_version__', '__package__', '__path__', '__spec__', '__version__', '_add_newdoc_ufunc', '_arg', '_dep_fft', '_deprecated', '_distributor_init', '_fun', '_key', '_lib', '_msg', '_sci', 'absolute', 'absolute_import', 'add', 'add_docstring', 'add_newdoc', 'add_newdoc_ufunc', 'alen', 'all', 'allclose', 'alltrue', 'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argpartition', 'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal', 'array_equiv', 'array_repr', 'array_split', 'array_str', 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'binary_repr', 'bincount', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'block', 'bmat', 'bool8', 'bool_', 'broadcast', 'broadcast_arrays', 'broadcast_to', 'busday_count', 'busday_offset', 'busdaycalendar', 'byte', 'byte_bounds', 'bytes0', 'bytes_', 'c_', 'can_cast', 'cast', 'cbrt', 'cdouble', 'ceil', 'cfloat', 'char', 'character', 'chararray', 'choose', 'clip', 'clongdouble', 'clongfloat', 'column_stack', 'common_type', 'compare_chararrays', 'complex128', 'complex64', 'complex_', 'complexfloating', 'compress', 'concatenate', 'conj', 'conjugate', 'convolve', 'copy', 'copysign', 'copyto', 'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 'cov', 'cross', 'csingle', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum', 'datetime64', 'datetime_as_string', 'datetime_data', 'deg2rad', 'degrees', 'delete', 'deprecate', 'deprecate_with_doc', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide', 'division', 'divmod', 'dot', 'double', 'dsplit', 'dstack', 'dtype', 'e', 'ediff1d', 'einsum', 'einsum_path', 'emath', 'empty', 'empty_like', 'equal', 'errstate', 'euler_gamma', 'exp', 'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fastCopyAndTranspose', 'fft', 'fft_msg', 'fill_diagonal', 'find_common_type', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'flexible', 'flip', 'fliplr', 'flipud', 'float16', 'float32', 'float64', 'float_', 'float_power', 'floating', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_float_positional', 'format_float_scientific', 'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'full', 'full_like', 'fv', 'gcd', 'generic', 'genfromtxt', 'geomspace', 'get_array_wrap', 'get_include', 'get_printoptions', 'getbufsize', 'geterr', 'geterrcall', 'geterrobj', 'gradient', 'greater', 'greater_equal', 'half', 'hamming', 'hanning', 'heaviside', 'histogram', 'histogram2d', 'histogram_bin_edges', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'ifft', 'iinfo', 'imag', 'in1d', 'index_exp', 'indices', 'inexact', 'inf', 'info', 'infty', 'inner', 'insert', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'int_asbuffer', 'intc', 'integer', 'interp', 'intersect1d', 'intp', 'invert', 'ipmt', 'irr', 'is_busday', 'isclose', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isin', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype', 'issubsctype', 'iterable', 'ix_', 'kaiser', 'kron', 'lcm', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort', 'linspace', 'little_endian', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logn', 'logspace', 'long', 'longcomplex', 'longdouble', 'longfloat', 'longlong', 'lookfor', 'ma', 'mafromtxt', 'mask_indices', 'mat', 'math', 'matmul', 'matrix', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'min_scalar_type', 'minimum', 'mintypecode', 'mirr', 'mod', 'modf', 'moveaxis', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nancumprod', 'nancumsum', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod', 'nanquantile', 'nanstd', 'nansum', 'nanvar', 'nbytes', 'ndarray', 'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'nditer', 'negative', 'nested_iters', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'nper', 'npv', 'number', 'obj2sctype', 'object0', 'object_', 'ogrid', 'ones', 'ones_like', 'outer', 'packbits', 'pad', 'partition', 'percentile', 'pi', 'piecewise', 'place', 'pmt', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'positive', 'power', 'ppmt', 'print_function', 'printoptions', 'prod', 'product', 'promote_types', 'ptp', 'put', 'put_along_axis', 'putmask', 'pv', 'quantile', 'r_', 'rad2deg', 'radians', 'rand', 'randn', 'random', 'rank', 'rate', 'ravel', 'ravel_multi_index', 'real', 'real_if_close', 'rec', 'recarray', 'recfromcsv', 'recfromtxt', 'reciprocal', 'record', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'result_type', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round_', 'row_stack', 's_', 'safe_eval', 'save', 'savetxt', 'savez', 'savez_compressed', 'sctype2char', 'sctypeDict', 'sctypeNA', 'sctypes', 'searchsorted', 'select', 'set_numeric_ops', 'set_printoptions', 'set_string_function', 'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj', 'setxor1d', 'shape', 'shares_memory', 'short', 'show_config', 'show_numpy_config', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'single', 'singlecomplex', 'sinh', 'size', 'sometrue', 'sort', 'sort_complex', 'source', 'spacing', 'split', 'sqrt', 'square', 'squeeze', 'stack', 'std', 'str0', 'str_', 'string_', 'subtract', 'sum', 'swapaxes', 'take', 'take_along_axis', 'tan', 'tanh', 'tensordot', 'test', 'tile', 'timedelta64', 'trace', 'tracemalloc_domain', 'transpose', 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'typeDict', 'typeNA', 'typecodes', 'typename', 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'unicode', 'unicode_', 'union1d', 'unique', 'unpackbits', 'unravel_index', 'unsignedinteger', 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'version', 'void', 'void0', 'vsplit', 'vstack', 'where', 'who', 'zeros', 'zeros_like']

可用 help() 查詢各子套件之說明資訊 :

>>> import scipy
>>> help(scipy.log)   
Help on function log in module numpy.lib.scimath:

log(x)
    scipy.log is deprecated and will be removed in SciPy 2.0.0, use numpy.lib.scimath.log instead


三. SciPy 的科學常數 :

SciPy 內建了一個 constants 子套件, 提供科學計算所需要的數學與自然常數, 且具有單位轉換功能. 用 dir() 可顯示 constants 子套件內容, 不過因為 constants 是子套件, 不是 scipy 的屬性, 所以 import scripy 後用 dir() 函數顯示 scipy.constants 會找不到 :

>>> import scipy  
>>> dir(scipy.constants)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'scipy' has no attribute 'constants'

要用 from scipy import constants 匯入 constants 子套件才行 :

>>> from scipy import constants 
>>> dir(constants)   
['Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'ConstantWarning', 'G', 'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg', 'Stefan_Boltzmann', 'Wien', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_obsolete_constants', 'absolute_import', 'acre', 'alpha', 'angstrom', 'arcmin', 'arcminute', 'arcsec', 'arcsecond', 'astronomical_unit', 'atm', 'atmosphere', 'atomic_mass', 'atto', 'au', 'bar', 'barrel', 'bbl', 'blob', 'c', 'calorie', 'calorie_IT', 'calorie_th', 'carat', 'centi', 'codata', 'constants', 'convert_temperature', 'day', 'deci', 'degree', 'degree_Fahrenheit', 'deka', 'division', 'dyn', 'dyne', 'e', 'eV', 'electron_mass', 'electron_volt', 'elementary_charge', 'epsilon_0', 'erg', 'exa', 'exbi', 'femto', 'fermi', 'find', 'fine_structure', 'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp', 'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp', 'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio', 'grain', 'gram', 'gravitational_constant', 'h', 'hbar', 'hectare', 'hecto', 'horsepower', 'hour', 'hp', 'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force', 'kmh', 'knot', 'lambda2nu', 'lb', 'lbf', 'light_year', 'liter', 'litre', 'long_ton', 'm_e', 'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega', 'metric_ton', 'micro', 'micron', 'mil', 'mile', 'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano', 'nautical_mile', 'neutron_mass', 'nu2lambda', 'ounce', 'oz', 'parsec', 'pebi', 'peta', 'physical_constants', 'pi', 'pico', 'point', 'pound', 'pound_force', 'precision', 'print_function', 'proton_mass', 'psi', 'pt', 'short_ton', 'sigma', 'slinch', 'slug', 'speed_of_light', 'speed_of_sound', 'stone', 'survey_foot', 'survey_mile', 'tebi', 'tera', 'test', 'ton_TNT', 'torr', 'troy_ounce', 'troy_pound', 'u', 'unit', 'value', 'week', 'yard', 'year', 'yobi', 'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta']

這些都是 constants 的成員, 可直接用屬性取得其值, 以下是數學常數 :

>>> constants.pi                         #圓周率
3.141592653589793
>>> constants.golden_ratio       #黃金比率 (同 golden)
1.618033988749895
>>> constants.golden                  #黃金比率
1.618033988749895

以下是物理常數 :

>>> constants.c                             #光速
299792458.0
>>> constants.speed_of_light      #光速
299792458.0
>>> constants.speed_of_sound    #音速
340.5
>>> constants.Planck                   #普郎克常數 (同 h)
6.62607015e-34
>>> constants.h                            #普郎克常數 (焦耳秒)
6.62607015e-34
>>> constants.Avogadro              #亞佛加厥常數 (同 N_A)
6.02214076e+23
>>> constants.N_A                       #亞佛加厥常數 (莫耳 mol)
6.02214076e+23
>>> constants.Boltzmann            #波茲曼常數 (同 k)
1.380649e-23
>>> constants.k                             #波茲曼常數 (J/K)
1.380649e-23
>>> constants.gravitational_constant     #重力常數
6.6743e-11
>>> constants.gas_constant         #氣體常數 (同 R)
8.314462618
>>> constants.R                            #氣體常數
8.314462618
>>> constants.G                            #牛頓重力常數 (m3*kg**(-1)s**(-2))
6.6743e-11
>>> constants.g                             #標準重力加速度 (m*s**(2))
9.80665
>>> constants.elementary_charge  #電荷電量 (庫倫, 同 e)
1.602176634e-19
>>> constants.e                              #電荷電量 (庫倫)
1.602176634e-19
>>> constants.m_e                         #電子質量 (公斤)
9.1093837015e-31
>>> constants.electron_mass        #電子質量 (公斤, 同 m_e)
9.1093837015e-31
>>> constants.m_p                         #質子質量 (公斤)
1.67262192369e-27
>>> constants.proton_mass           #質子質量 (公斤, 同 m_p)
1.67262192369e-27
>>> constants.m_n                          #中子質量 (公斤)
1.67492749804e-27
>>> constants.neutron_mass          #中子質量 (公斤, 同 m_n)
1.67492749804e-27
>>> constants.mu_0                         #真空磁導率 (亨利/米)
1.2566370614359173e-06
>>> constants.epsilon_0                  #真空電容率 (法拉/米)
8.854187817620389e-12
>>> constants.Wien                         #維恩位移常數 (mK) : 黑體輻射波長與溫度關係
0.002897771955
>>> constants.Rydberg                   #芮德柏常數 (1/m)
10973731.56816

注意, 如果用人名, 第一個字母均大寫, 例如波茲曼常數要用 Boltzmann.

完整的常數參見 :

https://docs.scipy.org/doc/scipy/reference/constants.html

3 則留言 :

小狐狸事務所 提到...

Thank you, Sir. This is just my learning notebook. I will be glad if it can help. Thanks a lot for your note.

JacobHarman 提到...

Up until this point, Python is by all accounts like a little glimpse of heaven for the improvement world. For sure, this programming language has strong potential in fulfilling both business needs and programmers' hunger for consistent updates. Nonetheless, it is vital to be exceptionally objective while examining any idea, so that to realize that the undertaking as a primary concern will be conveyed true to form and the financial plan spent on an independent Python web designer compensation doesn't go down the channel>> django freelancer

shantanu 提到...

great post, keep us posted Python Course in Nanded