 Python  ,    
 


        Python  ,    .

     :      (NumPy, SciPy, SymPy, mpmath),   SciKits (scikit-learn, scikit-image, scikit-bio, scikit-survival, scikit-rf, scikit-opt, scikit-geometry, scikit-hep),      (Pandas, Polars, Statsmodels, xarray, NetworkX),   ,    CPU  GPU (Numba, Cython, CuPy, RAPIDS, Dask, JAX),  ,      (Pyomo, OR-Tools, python-control, FMPy, CoolProp, Cantera, PyAnsys, pandapower, SimPy),     .

    ,  ,     .   , ,    -.





 Python  ,    





 1.     


 1      Python -  NumPy, SciPy, SymPy  mpmath,    ,  ,      .

1.1.  NumPy:     

  

 NumPy (Numerical Python)      Python.    Python (, list)          ,              .

   NumPy   numpy.ndarray -     .         (dtype,  float64, int32, complex128)        (    C      Fortran).

      :

 .                 Python.        C  Fortran (  - ufunc),     (SIMD).

 (broadcasting).                  .      ,              :  ,      .

    NumPy

numpy.array(object, dtype=None) -   ndarray  ,            .

numpy.zeros(shape) / numpy.ones(shape) / numpy.empty(shape) -        ,    .

numpy.arange(start, stop, step) / numpy.linspace(start, stop, num) -              .

numpy.ndarray.reshape(newshape) -   ()       (  - view,   ).

numpy.matmul(a, b) ( @) -       .

numpy.linalg.solve(a, b) -      ()  Ax = b  LU-     .

numpy.linalg.eig(a) / numpy.linalg.svd(a) -        ;   (SVD)  .

numpy.fft.fft(a) / numpy.fft.ifft(a) -              ().

numpy.einsum(subscripts, *operands) -  , ,        .

  

python

import numpy as np



#    A (3x3)     b

A = np.array([

[4.0, -1.0, 0.0],

[-1.0, 4.0, -1.0],

[0.0, -1.0, 4.0]

], dtype=np.float64)

b = np.array([15.0, 10.0, 10.0], dtype=np.float64)



#   Ax = b   

x = np.linalg.solve(A, b)

residual = np.linalg.norm(A @ x - b, ord=2)



#      

eigenvalues, eigenvectors = np.linalg.eig(A)

cond_number = np.linalg.cond(A)



print(f"  x: {x}")

print(f"  : {residual:.2e}")

print(f" : {cond_number:.4f}")

   .



***

1.2.  SciPy:     

  

 SciPy (Scientific Python)     NumPy       ,       Fortran  C (QUADPACK, ODEPACK, MINPACK, FITPACK, FFTPACK).

      ,   :

scipy.integrate -          ();

scipy.optimize -     ,   (  ),    ;

scipy.interpolate -    ,  ;

scipy.linalg -     ( ,  , , QR);

scipy.sparse -    ( CSR, CSC, COO)      ;

scipy.signal -     , ,   ;

scipy.stats -     ,  ,      .

    SciPy

scipy.integrate.quad(func, a, b) -        -.

scipy.integrate.solve_ivp(fun, t_span, y0, method='RK45') -         .    - (RK45, DOP853)       (Radau, BDF)   .

scipy.optimize.minimize(fun, x0, method=..., bounds=..., constraints=...) -        ( -,  -  -  -  BFGS, L-BFGS-B,    SLSQP).

scipy.optimize.root(fun, x0) -      F(x) = 0.

scipy.interpolate.CubicSpline(x, y) -  -      .

scipy.signal.butter(N, Wn, btype='low') / scipy.signal.filtfilt(b, a, x) -            .

scipy.stats.kstest(rvs, cdf) -   -       .

  

python

import numpy as np

from scipy.integrate import solve_ivp

from scipy.optimize import minimize



# 1.     (  )

def duffing_oscillator(t, state, delta=0.2, alpha=-1.0, beta=1.0):

x, v = state

dxdt = v

dvdt = -delta * v - alpha * x - beta * (x ** 3)

return [dxdt, dvdt]



sol = solve_ivp(

fun=duffing_oscillator,

t_span=(0.0, 20.0),

y0=[1.0, 0.0],

method="RK45",

t_eval=np.linspace(0, 20, 500)

)



# 2.    (   )

rosenbrock = lambda x: (1.0 - x)**2 + 100.0 * (x - x**2)**2

constraint = {"type": "ineq", "fun": lambda x: 1.5 - (x**2 + x**2)}

opt_res = minimize(rosenbrock, x0=np.array([0.0, 0.0]), method="SLSQP", constraints=constraint)



print(f"  : x(20) = {sol.y[0, -1]:.4f}")

print(f"    : {opt_res.x}")

   .



***

1.3.  SymPy:   

   

 SymPy (Symbolic Python)      (CAS),     Python    .    NumPy  SciPy,      , SymPy        .

          :       ,     ,              NumPy     .

    SymPy

sympy.symbols(names) -         (, , ).

sympy.simplify(expr) / sympy.expand(expr) / sympy.factor(expr) -   ,       .

sympy.diff(expr, var, n) -    n-    var.

sympy.integrate(expr, (var, a, b)) -         .

sympy.limit(expr, var, point) / sympy.series(expr, var, point, n) -         .

sympy.solve(equations, variables) / sympy.dsolve(eq, func) -        .

sympy.Matrix.jacobian(variables) -      -.

sympy.lambdify(args, expr, modules='numpy') -       Python,    NumPy.

  

python

import sympy as sp

import numpy as np



#   

x, y, t = sp.symbols('x y t', real=True)



#  -    

F = sp.Matrix([x**2 * sp.sin(y), sp.exp(-x) + y**3])

J = F.jacobian([x, y])



#      : y''(t) + 4*y(t) = 0

func_y = sp.Function('y')

ode = sp.Eq(func_y(t).diff(t, 2) + 4 * func_y(t), 0)

general_sol = sp.dsolve(ode, func_y(t))



#       NumPy

det_J = J.det()

det_J_num = sp.lambdify((x, y), det_J, modules='numpy')

grid_val = det_J_num(np.array([1.0, 2.0]), np.array([0.5, 1.0]))



print(f"  : {det_J}")

print(f"  : {general_sol}")

print(f"   : {grid_val}")

   .



***

1.4.  mpmath:   

  

      (float64,  IEEE 754)   1517       .       ,   ,            ,      .

 mpmath          ,  .         (, ,  , - ),     ,      .

    mpmath

mpmath.mp.dps / mpmath.mp.prec -          (dps)     (prec).

mpmath.workdps(n) -           .

mpmath.mpf(val) / mpmath.mpc(real, imag) -        .

mpmath.quad(f, [a, b]) -       -  -.

mpmath.findroot(f, x0) -       .

mpmath.matrix() / mpmath.lu_solve(A, b) -         (,  ).

  

python

import mpmath as mp



#   : 60   

mp.mp.dps = 60



#         15x15

n = 15

H = mp.hilbert(n)

b = mp.matrix([mp.mpf(1) for _ in range(n)])

x = mp.lu_solve(H, b)



#     

residual = mp.norm(H * x - b)



#    zeta(3)   

apery_const = mp.zeta(3)



print(f"     (60 ): {mp.nstr(residual, 10)}")

print(f" zeta(3): {mp.nstr(apery_const, 50)}")

   .



***

    1

      numpy.ndarray    list  Python         ?

     (broadcasting)  NumPy         ?

       (view)    (copy)  NumPy?      ?

        ?       SymPy,    - SciPy?

  sympy.lambdify()      NumPy         ?

       scipy.integrate.solve_ivp()            ?

     64-     (float64)      mpmath?

    1

:        

 :     ,  ,        .

 :

  SymPy       (f(x, y) = e^{-x^2 - y^2} cos(2x)),         .       NumPy   sp.lambdify()         np.meshgrid().

  NumPy      Ax = b  100 ? 100   ,    np.linalg.solve(),     (np.linalg.cond())      (Vert{}Ax - bVert{}_2).

  scipy.integrate.solve_ivp()       (? = 10, ? = 28, ? = 8/3)   t     ,   10.     .

  mpmath         20 ? 20   15  80  ,       .

      2 (  SciKits)      .docx    ?

 2 (  SciKits)

 2   SciKits         NumPy  SciPy -     scikit-learn       (scikit-image),  (scikit-bio),   (scikit-survival),   (scikit-rf),   (scikit-opt),   (scikit-geometry)     (scikit-hep).




 2.   SciKits


 SciKits (SciPy Toolkits)         ,           NumPy   SciPy.         SciPy -       ,             .

2.1.  scikit-learn:   

   API

 scikit-learn         : , , ,  ,     .

   scikit-learn   -   (API),    :

 (Estimator) -  ,           .fit(X, y).

 (Transformer) - ,       .transform(X)  .fit_transform(X, y) (,      ).

 (Predictor) - ,         .predict(X),      (.predict_proba(X))     (.decision_function(X)).

        (Pipeline)    (data leakage)  -.

    scikit-learn

sklearn.model_selection.train_test_split(*arrays, test_size, stratify) -             .

sklearn.model_selection.StratifiedKFold(n_splits) / cross_val_score(estimator, X, y, cv) -         .

sklearn.preprocessing.StandardScaler() / OneHotEncoder() -        .

sklearn.decomposition.PCA(n_components) -          .

sklearn.ensemble.RandomForestClassifier() / GradientBoostingRegressor() -      .

sklearn.pipeline.Pipeline(steps) / sklearn.compose.ColumnTransformer(transformers) -          .

sklearn.metrics.classification_report() / roc_auc_score() / mean_squared_error() -       .

  

python

import numpy as np

from sklearn.datasets import make_classification

from sklearn.model_selection import train_test_split, cross_val_score

from sklearn.preprocessing import StandardScaler

from sklearn.decomposition import PCA

from sklearn.ensemble import RandomForestClassifier

from sklearn.pipeline import Pipeline



#      

X, y = make_classification(n_samples=1000, n_features=20, n_informative=10, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)



#     

model_pipeline = Pipeline([

("scaler", StandardScaler()),

("pca", PCA(n_components=10)),

("classifier", RandomForestClassifier(n_estimators=150, random_state=42))

])



#   5- -      

cv_scores = cross_val_score(model_pipeline, X_train, y_train, cv=5, scoring="roc_auc")

model_pipeline.fit(X_train, y_train)

test_accuracy = model_pipeline.score(X_test, y_test)



print(f" ROC-AUC  -: {np.mean(cv_scores):.4f}")

print(f"   : {test_accuracy:.4f}")

   .



***

2.2.  scikit-image:   

   

 scikit-image          ()     , ,    .     OpenCV,        , scikit-image     NumPy    -.

      (M, N),  RGB- -    (M, N, 3),    -   (Z, Y, X).

    scikit-image

skimage.io.imread(fname) / imsave(fname, arr) -        (TIFF, PNG, JPEG).

skimage.color.rgb2gray(rgb) -         .

skimage.filters.gaussian(image, sigma) / sobel(image) -          .

skimage.filters.threshold_otsu(image) -         .

skimage.morphology.erosion() / dilation() / opening() / closing() -        (skimage.morphology.disk).

skimage.segmentation.watershed(image, markers) -     .

skimage.measure.label(label_image) / regionprops_table(label_image, properties) -         (, , ,  )     .

  

python

import numpy as np

from skimage import data, filters, morphology, measure



#        

image = data.coins()

smoothed = filters.gaussian(image, sigma=1.5)



#        

thresh = filters.threshold_otsu(smoothed)

binary_mask = morphology.closing(smoothed > thresh, morphology.disk(3))



#       

labeled_objects = measure.label(binary_mask)

props = measure.regionprops_table(

labeled_objects,

intensity_image=image,

properties=["label", "area", "eccentricity", "mean_intensity"]

)



#    (  100 )

valid_areas = props["area"][props["area"] > 100]

print(f" : {len(valid_areas)},  : {np.mean(valid_areas):.1f} .")

   .



***

2.3.  scikit-bio:    

   

 scikit-bio        ,     .           ,     ,         .

    scikit-bio

skbio.DNA(sequence) / skbio.RNA(sequence) / skbio.Protein(sequence) -       ,      /.

skbio.alignment.local_pairwise_align_ssw(seq1, seq2) -      -   SIMD-.

skbio.TreeNode.read(file, format='newick') - ,      (,  UniFrac)   .

skbio.diversity.alpha_diversity(metric, counts) / beta_diversity(metric, counts) -    (, , Chao1)   (-)  .

skbio.stats.ordination.pcoa(distance_matrix) -    (  )    .

skbio.stats.distance.permanova(distance_matrix, grouping) -       .

  

python

from skbio import DNA

from skbio.diversity import alpha_diversity, beta_diversity



#     

dna_seq = DNA("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG", metadata={"id": "seq_01"})

mrna_seq = dna_seq.transcribe()

protein_seq = mrna_seq.translate()



#   -  -     (3 , 4 )

abundance_matrix = [,

,

[0, 2, 15, 8]

]

sample_ids = ["Sample_A", "Sample_B", "Sample_C"]



shannon_idx = alpha_diversity("shannon", abundance_matrix, ids=sample_ids)

bray_curtis_dm = beta_diversity("braycurtis", abundance_matrix, ids=sample_ids)



print(f"  : {protein_seq}")

print(f"   :n{shannon_idx}")

   .



***

2.4.  scikit-survival:    

   

 scikit-survival   scikit-learn         (time-to-event analysis):     ,         .

       (right-censored data),        ,        .         .

    scikit-survival

sksurv.util.Surv.from_arrays(event, time) -     (_, ),      y.

sksurv.nonparametric.kaplan_meier_estimator(event, time) -     -.

sksurv.linear_model.CoxPHSurvivalAnalysis(alpha) -        L2-.

sksurv.ensemble.RandomSurvivalForest(n_estimators) / GradientBoostingSurvivalAnalysis() -       .

sksurv.svm.FastSurvivalSVM() -           .

sksurv.metrics.concordance_index_censored(event_indicator, event_time, estimate) -     (C-index)     .

  

python

import numpy as np

from sksurv.util import Surv

from sksurv.linear_model import CoxPHSurvivalAnalysis

from sksurv.metrics import concordance_index_censored



#     6   (True -  , False - )

events = np.array([True, False, True, True, False, True])

times = np.array([120.0, 200.0, 85.0, 150.0, 240.0, 60.0])

y_surv = Surv.from_arrays(event=events, time=times)



#    (, )

X_features = np.array([

[75.0, 1.2], [60.0, 0.8], [82.0, 1.8],

[70.0, 1.1], [58.0, 0.7], [90.0, 2.3]

])



#        C-

cox_model = CoxPHSurvivalAnalysis()

cox_model.fit(X_features, y_surv)

risk_scores = cox_model.predict(X_features)

c_index = concordance_index_censored(events, times, risk_scores)[0]



print(f"  : {cox_model.coef_}")

print(f"   (C-index): {c_index:.4f}")

   .



***

2.5.  scikit-rf:    

   

 scikit-rf (skrf)       (RF)   ,   - .             Touchstone (.s1p, .s2p, ..., .snp),    (S-, Z-, Y-, ABCD-),   ,    .

    scikit-rf

skrf.Network(file) -   -   Touchstone          S.

skrf.Network.s_db / s_deg / vswr -     S-  ,          ().

skrf.Network.cascade(other) ( **) -    .

skrf.Network.deembed(other) -      (de-embedding).

skrf.media.Coaxial(frequency, Dint, Dout, epsilon_r) / MLine() -     ( ,  ).

skrf.calibration.SOLT(ideals, measured) -       Short-Open-Load-Thru.

  

python

import numpy as np

import skrf as rf



#     1  5  (401 )    

freq = rf.Frequency(1, 5, 401, "GHz")

coax_media = rf.media.Coaxial(frequency=freq, Dint=1.0e-3, Dout=3.5e-3, epsilon_r=2.1)



#     50      

line_segment = coax_media.line(d=50, unit="mm", name="line_50mm")

cascaded_line = line_segment ** line_segment



#    S21 ( )      3 

idx_3ghz = np.argmin(np.abs(freq.f - 3e9))

s21_db = cascaded_line.s_db[idx_3ghz, 1, 0]

vswr_in = cascaded_line.s_vswr[idx_3ghz, 0, 0]



print(f"  S21  3 : {s21_db:.4f} , : {vswr_in:.4f}")

   .



***

2.6.  scikit-opt:   

  

 scikit-opt           , ,     ,      (scipy.optimize)     .

    scikit-opt

sko.GA.GA(func, n_dim, size_pop, max_iter, lb, ub) -        ,  ,   .

sko.PSO.PSO(func, n_dim, pop, max_iter, lb, ub, w, c1, c2) -     (Particle Swarm Optimization).

sko.DE.DE(func, n_dim, size_pop, max_iter, lb, ub) -   .

sko.SA.SA(func, x0, T_max, T_min, L) -    (Simulated Annealing).

sko.ACA.ACA_TSP(func, n_dim, size_pop, max_iter, distance_matrix) -        (TSP).

Algorithm.run() -    ;     best_x     best_y.

  

python

import numpy as np

from sko.DE import DE



#     (  0   x = 0)

def rastrigin(x):

return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))



#     4-    

de_optimizer = DE(

func=rastrigin,

n_dim=4,

size_pop=60,

max_iter=200,

lb=[-5.12] * 4,

ub=[5.12] * 4

)

best_x, best_y = de_optimizer.run()



print(f"  : {np.round(best_x, 5)}")

print(f"  : {best_y[0]:.6e}")

   .



2.7.  scikit-geometry:  

   

 scikit-geometry    Python     C++ CGAL (Computational Geometry Algorithms Library).           (), ,     .

    scikit-geometry

skgeom.Point2(x, y) / Segment2(p, q) / Ray2() / Line2() -    .

skgeom.Polygon(vertices) / PolygonWithHoles(outer, holes) -        .

skgeom.boolean_set.intersect(p1, p2) / join(p1, p2) / difference(p1, p2) -  -    .

skgeom.minkowski.minkowski_sum(p1, p2) -      (        ).




  .


   .

   ,     (https://www.litres.ru/pages/biblio_book/?art=74838993)  .

      Visa, MasterCard, Maestro,    ,   ,     ,  PayPal, WebMoney, ., QIWI ,       .


