• python模拟上传图片For today’s recreational coding exercise, we will investigate plasma physics with particle-in-cell (PIC) simulations. We will create a simulation of two electron beams passing ...


    For today’s recreational coding exercise, we will investigate plasma physics with particle-in-cell (PIC) simulations. We will create a simulation of two electron beams passing through each other in opposite directions. An interesting phenomenon occurs, called the Two-Stream Instability.

    对于当今的娱乐性编码练习,我们将使用单元中粒子(PIC)模拟研究等离子体物理。 我们将模拟两个彼此相反的方向穿过的电子束。 发生一个有趣的现象,称为两流不稳定性。

    You may find the accompanying Python code on github.


    Before we begin, below is a gif of what running our simulation looks like:


    单元中粒子(PIC)方法 (Particle-In-Cell (PIC) Method)

    We will consider a one-dimensional system of electrons in an unmagnetized uniform medium of ions. The electrons will be described by N particles, indexed by i, each having a

    我们将考虑在未磁化的离子均匀介质中的一维电子系统。 电子将由N个粒子(由i索引)描述,每个粒子都有一个

    • position rᵢ


    • velocity vᵢ


    The electrons feel an acceleration aᵢ which is due to the electric field E at the location of the particle. The equations of motion for the electrons are given by:

    电子感到加速度aᵢ ,这是由于粒子位置处的电场E引起的 电子的运动方程式为:

    Image for post

    What remains to be done is to calculate the electric field E, which depends on the number density n of the electrons. The electric field E is defined as the negative gradient of the electric potential ϕ, which is given by Poisson’s equation sourced by the density:

    剩下要做的是计算电场E ,它取决于电子的数密度n 。 的电场E被定义为电势φ,它是由泊松方程由密度给定源的负梯度:

    Image for post

    where n₀ is the average electron density (a constant).


    The Particle-In-Cell (PIC) Method computes the density and subsequently the potential and electric field on a mesh. Hence it is called a particle-mesh method. The electric field is then extrapolated onto the location of the particles in order to advance them. That’s a long sequence of steps. Let’s dig in!

    单元中粒子(PIC)方法可计算密度,然后计算网格上的电势和电场。 因此,它被称为粒子网格方法。 然后将电场外推到粒子的位置,以使粒子前进。 这是一个很长的步骤。 让我们开始吧!

    密度计算 (Density Calculation)

    The density is obtained by binning the particles onto the mesh gridpoints. Call the separation distance between mesh points Δx. A particle with position rᵢ will lie between a pair of coordinates xⱼ and x_{j+1} on the mesh. Then, the densities nⱼ and n_{j+1} at these two points gain a contribution:

    通过将粒子合并到网格网格点上来获得密度。 称网格点之间的间隔距离Δx。 位置为rᵢ的粒子将位于网格上的一对坐标xⱼx_ {j + 1}之间。 然后,在这两个点上的密度nⱼn_ {j + 1}获得贡献:

    Image for post

    After collecting contribution from all particles, the density has to be properly normalized so that the average density is the specified n₀.


    潜力计算 (Potential Calculation)

    Knowing the density nⱼ on the mesh grid points, we now seek the potential ϕⱼ at these points. The second-derivative operator (called the ‘Laplacian’) in Poisson’s equation can be approximated on the mesh with a finite-different formula:

    知道在网格点的密度nⱼ,我们现在寻求在这些点的潜力φⱼ。 泊松方程中的二阶导数算子(称为“拉普拉斯算子”)可以使用有限差分公式在网格上近似:

    Image for post

    If all the values for nⱼ are arranged into a column vector, and similarly for ϕⱼ, then the equation can be written as a system of linear equations in matrix form:


    Image for post

    The matrix represents the Laplacian operator and is sparse and tridiagonal. We have assumed periodic boundary conditions, i.e., the endpoints of the mesh wrap around to each other, which add the ‘1’s in the top-right and bottom-left corners of the matrix. This matrix equation can be efficiently numerically inverted and solved by using pre-built linear algebra packages such as the Python Scipy package’s “spsolve” function.

    矩阵表示拉普拉斯算子,并且是稀疏的和三对角的。 我们假定了周期性边界条件,即网格的端点彼此环绕,这在矩阵的右上角和左下角加了“ 1”。 通过使用预构建的线性代数包(例如Python Scipy包的“ spsolve”函数),可以有效地对这个矩阵方程进行数值反转和求解。

    To start, we will construct the matrix for now with some code:


    # Construct matrix Lmtx to computer Laplacian (2nd derivative) 
    # on mesh size Nx, separation dx
    e = np.ones(Nx)
    diags = np.array([-1,0,1])
    vals  = np.vstack((e,-2*e,e))
    Lmtx = sp.spdiags(vals, diags, Nx, Nx);
    Lmtx = sp.lil_matrix(Lmtx) # tranform mtx type to modify entries
    Lmtx[0,Nx-1] = 1
    Lmtx[Nx-1,0] = 1
    Lmtx /= dx**2
    Lmtx = sp.csr_matrix(Lmtx) # transform mtx type

    电场计算(Electric Field Calculation)

    Given that we have solved for ϕⱼ on the mesh, we can next solve for the electric field Eⱼ by discretizing the first-derivative operator (called the ‘gradient’):


    Image for post

    Again we can write out the system of equations in matrix form:


    Image for post

    The system is simpler this time. There is no need to invert a matrix. The electric field is directly obtained by applying the matrix multiplication.

    这次系统更简单。 无需反转矩阵。 通过应用矩阵乘法直接获得电场。

    The code to construct the matrix for the gradient operator is shown below:


    # Construct matrix G to computer Gradient  (1st derivative)
    # on mesh size Nx, separation dx
    e = np.ones(Nx)
    diags = np.array([-1,1])
    vals  = np.vstack((-e,e))
    Gmtx = sp.spdiags(vals, diags, Nx, Nx);
    Gmtx = sp.lil_matrix(Gmtx) # tranform mtx type to modify entries
    Gmtx[0,Nx-1] = -1
    Gmtx[Nx-1,0] = 1
    Gmtx /= (2*dx)
    Gmtx = sp.csr_matrix(Gmtx) # transform mtx type

    加速度计算(Acceleration Calculation)

    So far we have gone from particles to mesh values of density to potential to electric field. To complete the loop, we need the electric field at the location of the particles. Fortunately, this can now be done with interpolation from the 2 nearest gridpoints xⱼ and x_{j+1}. For particle i, the electric field Eᵢ is:

    到目前为止,我们已经从粒子到密度的网格值,再到电场的电势。 为了完成循环,我们需要在粒子位置处施加电场。 幸运的是,现在可以通过从2个最近的网格点xⱼx_ {j + 1}进行插值来完成此操作。 对于粒子i,电场Eᵢ为:

    Image for post

    using similar weights as when be binned to get density.


    Putting all the steps above together, we can write a function to calculate the acceleration on each particle, given the particle distribution:


    def getAcc( pos, Nx, boxsize, n0, Gmtx, Lmtx ):
        Calculate the acceleration on each particle due to electric field
    	pos      is an Nx1 matrix of particle positions
    	Nx       is the number of mesh cells
    	boxsize  is the domain [0,boxsize]
    	n0       is the electron number density
    	Gmtx     is an Nx x Nx matrix for calculating the gradient on the grid
    	Lmtx     is an Nx x Nx matrix for calculating the laplacian on the grid
    	a        is an Nx1 matrix of accelerations
    	# Calculate Electron Number Density on the Mesh by 
    	# placing particles into the 2 nearest bins (j & j+1, with proper weights)
    	# and normalizing
    	N          = pos.shape[0]
    	dx         = boxsize / Nx
    	j          = np.floor(pos/dx).astype(int)
    	jp1        = j+1
    	weight_j   = ( jp1*dx - pos  )/dx
    	weight_jp1 = ( pos    - j*dx )/dx
    	jp1        = np.mod(jp1, Nx)   # periodic BC
    	n  = np.bincount(j[:,0],   weights=weight_j[:,0],   minlength=Nx);
    	n += np.bincount(jp1[:,0], weights=weight_jp1[:,0], minlength=Nx);
    	n *= n0 * boxsize / N / dx 
    	# Solve Poisson's Equation: laplacian(phi) = n-n0
    	phi_grid = spsolve(Lmtx, n-n0)
    	# Apply Derivative to get the Electric field
    	E_grid = - Gmtx @ phi_grid
    	# Interpolate grid value onto particle locations
    	E = weight_j * E_grid[j] + weight_jp1 * E_grid[jp1]
    	a = -E
    	return a

    时间整合(Time Integration)

    We are in the home stretch now! We will loop over timesteps and evolve the electrons using a leap-frog scheme (‘kick-drift-kick’). For each timestep Δt, each particle receives a half-step ‘kick’:

    我们现在在家中! 我们将在时间步长上循环,并使用跳越方案('kick-drift-kick')释放电子。 对于每个时间步长Δt ,每个粒子都接收一个半步“踢”:

    Image for post

    followed by a full-step ‘drift’:


    Image for post

    followed by another half-step ‘kick’.


    The evolution is performed in the code using a For-loop and our function for the acceleration from earlier:


    # Simulation Main Loop
    for i in range(Nt):
    	# (1/2) kick
    	vel += acc * dt/2.0
    	# drift (and apply periodic boundary conditions)
    	pos += vel * dt
    	pos = np.mod(pos, boxsize)
    	# update accelerations
    	acc = getAcc( pos, Nx, boxsize, n0, Gmtx, Lmtx )
    	# (1/2) kick
    	vel += acc * dt/2.0
    	# update time
    	t += dt

    In case this looks familiar, it might be because this time-stepping algorithm is a common one for particle-based simulations, and we have also used it in our tutorial on gravitational N-body simulations.


    初始条件 (Initial Conditions)

    The only thing left to do is specify the initial conditions (positions and velocities at time t=0) of the electrons in the simulation. In the code, we implement the example that we have a uniform beam traveling to the right, and another one superimposed, traveling left. Particle positions are drawn from a random uniform distribution. Velocities are drawn from a Gaussian centered about the beam velocity (one positive, one negative). Small initial perturbations in the form of a cosine function are added to the velocity distribution. Feel free to check out the code and modify or the initial conditions or explore your own.

    剩下要做的就是指定模拟中电子的初始条件(在时间t = 0时的位置和速度)。 在代码中,我们实现了一个示例,我们有一个均匀的光束向右传播,另一个光束向左传播。 粒子位置是从随机均匀分布中得出的。 速度是从以光束速度为中心的高斯中得出的(一个正,一个负)。 余弦函数形式的小的初始扰动被添加到速度分布中。 随时检查代码并进行修改或初始条件,或者自行探索。

    Running the code allows you to visualize the simulation in real time and will yield the figure:


    Plasma PIC simulation with Python

    We plot the configuration of electrons in what’s called phase-space, where the x-axis is the particle’s position and the y-axis is the velocity. This allows us to visualize all the variables in the system directly. Particles initially belonging to the right-moving beam have a blue color, while particles in the left-moving beam are red. The two beams interact with each other and go unstable in mesmerizing fashion.

    我们在所谓的相空间中绘制电子的构图,其中x轴是粒子的位置,y轴是速度。 这使我们可以直接可视化系统中的所有变量。 最初属于向右移动光束的粒子为蓝色,而向左移动的光束中的粒子为红色。 两束光相互影响,并以令人着迷的方式变得不稳定。

    So there you have it. We’ve created a plasma PIC simulation from scratch. I have here assumed the simplest scenario where electrons are non-relativistic and ions form a static background, and we’ve already learned an interesting instability can occur from counter-streaming plasma beams. Astro- and plasma physicists use these types of simulations to study all sorts of physical systems, from magnetic reconnection in the Sun to the design of tokamaks. In tokamak design, for example, the goal is to figure out a way to confine plasma to produce energy, without triggering disruptive plasma instabilities. It’s a very hard problem, but some day the technology may be an efficient way to produce clean energy.

    所以你有它。 我们从头开始创建了等离子PIC仿真。 我在这里假设了最简单的情况,其中电子是非相对论的,并且离子形成了静态背景,而且我们已经了解到,逆流等离子体束会产生有趣的不稳定性。 天体物理学家和等离子物理学家使用这些类型的模拟来研究各种物理系统,从太阳的磁重联到托卡马克的设计。 例如,在托卡马克设计中,目标是找到一种方法来限制等离子体产生能量,而不会触发破坏性的等离子体不稳定性。 这是一个非常棘手的问题,但是总有一天该技术可能是生产清洁能源的有效方法。

    Solar flares involve magnetic reconnection and release of energy
    Image for post
    wikimedia]wikimedia ]

    Download the Python code on github for our PIC algorithm to visualize the simulation in real time and play around with the initial conditions. Enjoy!

    在github上为我们的PIC算法下载Python代码,以实时可视化仿真并处理初始条件。 请享用!

    翻译自: https://medium.com/swlh/create-your-own-plasma-pic-simulation-with-python-39145c66578b


  • 本文实例为大家分享了... #python创建图片,并且添加文字 im = Image.new(RGBA,(200,200),'white') #创建一个Image对象,width=200,height=200,背景为白色 draw = ImageDraw.Draw(im)#创建一个绘画对象 fnt = Im
  • Python创建数学动画

    2021-04-16 16:09:28
    您是否曾经尝试过使用机器...幸运的是,Grant整理了一个名为manim的Python程序包,使您可以使用Python创建数学动画或图片。 在本文中,您将学习如何使用manim如下创建数学动画。 什么是Manim? Manim是用于制作精确动画

    您是否曾经尝试过使用机器学习算法的数学概念并将3Blue1Brown用作学习资源? 由于格兰特(Grant)出色的解释和出色的动画效果,许多人喜欢3Blue1Brown。


    幸运的是,Grant整理了一个名为manim的Python程序包,使您可以使用Python创建数学动画或图片。 在本文中,您将学习如何使用manim如下创建数学动画。


    Manim是用于制作精确动画的引擎,旨在创建说明性的数学视频。 请注意,有2种版本的manim。 一种是由Grant创建的,另一种是由Manim社区创建和维护的。

    要安装软件包的依赖项,请访问文档。 安装依赖项后,键入:

    pip install manim



    我们将创建一个从中心开始生长的蓝色正方形。 用于创建动画的代码位于从Scene派生的类的Construct方法中。

    将上面的脚本另存为start.py。 现在,运行以下命令为脚本生成视频。



    单独创建一个正方形并不是那么有趣。 让我们将这个正方形变成一个圆圈。






    from manim import * 
    config.background_color = DARK_GRAY















  • opencv3 for python创建图片绘制简单几何图形


    import cv2 as cv
    import numpy as np
    width = 200
    height = 200
    image = np.zeros((height, width, 3), dtype=np.uint8)
    win_name = "test"
    cv.imshow(win_name, image)
    #draw a line
    start_point = (10,10)
    end_point = (100,100)
    #line attribute
    color = (0,255,0)
    line_width = 4
    line_type = 8
    cv.line(image, start_point, end_point, color, line_width, line_type)
    x = 30
    y = 30
    rect_start = (x,y)
    x1 = 90
    y1 = 90
    rect_end = (x1,y1)
    cv.rectangle(image, rect_start, rect_end, color, 1, 0)
    x = 100
    y = 100
    radius = 60
    circle_center = (x,y)
    cv.circle(image, circle_center, radius, color)
    cv.imshow(win_name, image)

  • # 创建字体文件 def creat_font_img(value, file_name, path): # 编辑图片路径 img = cv2.imread(path) # 设置需要显示的字体 fontpath = "font/simsun.ttc" # 32为字体大小 font = ImageFont.truetype(font...


    import os
    import cv2
    import numpy as np
    from PIL import ImageFont, ImageDraw, Image
    # 生成空白文件
    def new_image(width, height, color, name):
        img = Image.new('RGB', (width, height), (color["r"], color["g"], color["b"]))
        # img.show()
    # 创建字体文件
    def creat_font_img(value, file_name, path):
        # 编辑图片路径
        img = cv2.imread(path)
        # 设置需要显示的字体
        fontpath = "font/simsun.ttc"
        # 32为字体大小
        font = ImageFont.truetype(fontpath, 32)
        img_pil = Image.fromarray(img)
        draw = ImageDraw.Draw(img_pil)
        # 获取字体宽度
        sum_width = 0
        sum_height = 0
        for char in value:
            width, height = draw.textsize(char, font)
            sum_width += width
            sum_height = height
        # 绘制文字信息
        # (100,300/350)为字体的位置,(255,255,255)为白色,(0,0,0)为黑色
        draw.text(((img.shape[1] - sum_width) / 2, (img.shape[0] - sum_height) / 2), value, font=font, fill=(0, 0, 0))
        bk_img = np.array(img_pil)
        # cv2.imshow("add_text", bk_img)
        cv2.waitKey()  # 保存图片路径
        cv2.imwrite(file_name + "_font.png", bk_img)
    def image_resize(img, size=(1500, 1100)):
            if img.mode not in ('L', 'RGB'):
                img = img.convert('RGB')
            img = img.resize(size)
        except Exception as e:
        return img
    # 合并图片(垂直)
    def image_merge(images, output_dir='./', output_name='merge.jpg', \
                    restriction_max_width=None, restriction_max_height=None):
        images - 要合并的图片路径列表
        ouput_dir - 输出路径
        output_name - 输出文件名
        restriction_max_width - 限制合并后的图片最大宽度,如果超过将等比缩小
        restriction_max_height - 限制合并后的图片最大高度,如果超过将等比缩小
        max_width = 0
        total_height = 0
        # 计算合成后图片的宽度(以最宽的为准)和高度
        for img_path in images:
            if os.path.exists(img_path):
                img = Image.open(img_path)
                width, height = img.size
                if width > max_width:
                    max_width = width
                total_height += height
                # 产生一张空白图
        new_img = Image.new('RGB', (max_width, total_height), 255)
        # 合并
        x = y = 0
        for img_path in images:
            if os.path.exists(img_path):
                img = Image.open(img_path)
                width, height = img.size
                new_img.paste(img, (x, y))
                y += height
        if restriction_max_width and max_width >= restriction_max_width:
            # 如果宽带超过限制
            # 等比例缩小
            ratio = restriction_max_height / float(max_width)
            max_width = restriction_max_width
            total_height = int(total_height * ratio)
            new_img = image_resize(new_img, size=(max_width, total_height))
        if restriction_max_height and total_height >= restriction_max_height:
            # 如果高度超过限制
            # 等比例缩小
            ratio = restriction_max_height / float(total_height)
            max_width = int(max_width * ratio)
            total_height = restriction_max_height
            new_img = image_resize(new_img, size=(max_width, total_height))
        if not os.path.exists(output_dir):
        save_path = '%s/%s' % (output_dir, output_name)
        return save_path
    color = {}
    color["r"] = 255
    color["g"] = 255
    color["b"] = 255
    new_image(430, 100, color, "a.jpg")
    creat_font_img("aaaaaaa", "a", "a.jpg")
    creat_font_img("好好好", "b", "a.jpg")
    creat_font_img("emmmmmmmm", "c", "a.jpg")
    image_merge(images=['a_font.png', 'b_font.png', 'c_font.png'], output_name='mer.png')


  • 主要介绍了python图片按照exif信息里的创建时间进行排序的方法,涉及Python操作图片exif获取信息的技巧,需要的朋友可以参考下
  • Python创建动图

    2020-08-11 20:20:40
    # 多帧图片路径 filenames = [ 'flow_official_caffe.png', 'flow_pytorch.png', 'flow_tf2.png' ] names = [ 'Official Caffe', 'Pytorch', 'This TF2' ] for i, filename in enumerate(filenames): im = ...
  • python创建压缩文件

    2019-01-22 11:24:56
    业务中需要将阿里云上存储一些图片通过浏览器进行下载,很多图片要分类并创建文件夹,然后传到本地 实现是: 先将图片下载到服务器上,然后通过python图片的文件夹,进行打包和压缩,然后将压缩文件放到内存中,...
  • 更加详细的知识点如下:Imaga模块:用来创建,打开,保存图片文件new(path):用来创建一个新的图片文件.该文件位于path所在的路径中。打开后返回Image类型的图片。open(path):用来打开已经存在的图片文件.该文件位于...
  • 0 for row in range(img_shape[0]): for col in range(img_shape[1]): for channel in range(img_shape[2]): if channel == 2: # img[row, col, channel] = 255 # 生成红色图片 img[row, col, channel] = count ...
  • 在深度学习或者机器学习的时候,常常需要对数据进行整理和分类,最常见的是通过对数据路径和标签写入 .../usr/bin/env python 4 import sys 5 import os.path 6 7 # This is a tiny scrip...
  • “images/”+kpartname) if not os.path.isdir(new_path): os.makedirs(new_path) print(“创建文件夹:”+new_path) #下载图片 def downLoadImg(url,new_path): path=sys.path[0] kpath = os.path.join(path, ...
  • Python创建Tkinter窗口

    2021-06-03 10:07:34
  • [python]使用python创建随机文件名

    千次阅读 2019-01-14 18:23:59
    web服务器在接收用户上传的音频、图片等文件时是以字节流的方式读取的,因此有必要在服务器本地创建一个对应的文件将数据写入。 为了支持多个并发上传请求,必须使用随机文件名(避免不同请求的数据写入了服务器下...
  • 那么本文教你如何使用python来做好这个分类工作但不局限于图片整理,其他文件的自动整理归类其实也是一样的逻辑,python是个好东西,你指的拥有。 import os import sys import time from s...
  • 1.首先获得图片名: 一般情况,图片的名字格式是这样的: ./data/val/000529.jpg.bmp ./data/val/000530.jpg.bmp ./data/val/000531.jpg.bmp ./data/val/000532.jpg.bmp ./data/val/000533.jpg.bmp ./data/val/...
  • ##### 前言:帮朋友做一个心理学测试程序的时候遇到了这个需求,需要把九张图片拼凑成一张图片,搜了下居然没找到合适的轮子,倒是只有把一张图裂成九张的,真·裂开。于是搞了个简单的九宫格图片合并,把之前也是用...
  • 我们在微信或者QQ聊天时会用到许多图片表情包,我们可以利用python的pillow库来实现表情包的添加 1.导入程序所需要的库 from PIL import Image,ImageDraw,ImageFont import matplotlib.pyplot as plt 如果没有...
  • 新建文件夹: import os import requests ...#创建名为test的文件夹 os.mkdir(dirname) #此处相当于文件路径 test/image.jpg,也就是在test文件夹中的image.jpg文件 filename=dirname+'/'+'im...
  • 相信大家对python-docx这个常用的操作docx文档的库都不陌生,它支持以内联形状(Inline Shape)的形式插入图片,即图片和文本之间没有重叠,遵循流动版式(flow la...
  • new(path):用来创建一个新的图片文件.该文件位于path所在的路径中。打开后返回Image类型的图片。 open(path):用来打开已经存在的图片文件.该文件位于path所在的路径中。打开后返回Image类型的图片。 save(path):...
  • 初学python,学到GUY这里时,按照书上的代码写了一段创建窗口程序,窗口倒是出来了,但是报了一堆错,请朋友们帮忙看一下怎么解决![图片说明](https://img-ask.csdn.net/upload/201504/14/1429004813_57326.png) !...
  • python如何调用图片-python调用图片

    千次阅读 2020-11-01 13:08:32
    python本身也有识别图片转文字的框架,但是相比调用接口,识别的精度就略显不行了; 这是 百度ai 的网站: https:ai.baidu.com ; 点击右上角的 控制台 ,申请或者登陆; 进去之后左侧有 【文字识别】: ? 点击【创建...
  • Python和OpenCV创建一个图片搜素引擎
  • 文/裸睡的猪哥 图片来源于网络微信,一个日活10亿的超级app,不仅在国内社交独领风骚,在国外社交也同样占有一席之地。今天我们要讲的便是如何用Python来做一个微信聊...
  • 这是一种通过Python的面向对象方法,旨在为Tikz代码提供一个巨大的包装,目的是简化为TeX文档创建复杂图形的过程。 为什么 这适用于了解基本的Python和TikZ,但已经意识到虽然TikZ很棒,但使用起来确实很烦人的人。...



1 2 3 4 5 ... 20
收藏数 4,727
精华内容 1,890


python 订阅