程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了从熊猫文件中绘制多个高斯 数据高斯解决方案结果大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决从熊猫文件中绘制多个高斯 数据高斯解决方案结果?

开发过程中遇到从熊猫文件中绘制多个高斯 数据高斯解决方案结果的问题如何解决?下面主要结合日常开发的经验,给出你关于从熊猫文件中绘制多个高斯 数据高斯解决方案结果的解决方法建议,希望对你解决从熊猫文件中绘制多个高斯 数据高斯解决方案结果有所启发或帮助;

我试图在一个图上绘制多个高斯图,这些图具有不同的高度、宽度和中心来自这种类型的数据框:

hight(y) fwhM(wIDth) centers(x)
24.122348 1.827472 98
24.828252 4.333549 186
26.810812 1.728494 276
25.997897 1.882424 373
24.503944 2.222210 471
27.488572 1.750039 604
31.556823 3.844592 683
27.920951 0.891394 792
27.009054 1.917744 897

知道如何去做吗?

解决方法

我们将重复使用

中定义的高斯绘图仪
  • Creating gaussians of fixed width and std

(此处重复代码)

数据

以下代码生成上述数据帧。

data = [
    (24.122348,1.827472,98),(24.828252,4.333549,186),(26.810812,1.728494,276),(25.997897,1.882424,373),(24.503944,2.222210,471),(27.488572,1.750039,604),(31.556823,3.844592,683),(27.920951,0.891394,792),(27.009054,1.917744,897),]

df = pd.DataFrame(data,columns=["height","fwhm","center"])

高斯

摘自上面的参考帖子。


import matplotlib.cm as mpl_cm
import matplotlib.colors as mpl_colors
import matplotlib.pyplot as plt
import numpy as np

from scipy.spatial.distance import cdist


class Gaussian:
    def __init__(self,size):
        self.size = size
        self.center = np.array(self.size) / 2
        self.axis = self._calculate_axis()

    def _calculate_axis(self):
        """
            Generate a list of rows,columns over multiple axis.

            Example:
                Input: size=(5,3)
                Output: [array([0,1,2,3,4]),array([[0],[1],[2]])]
        """
        axis = [np.arange(size).reshape(-1,*np.ones(idx,dtype=np.uint8))
                for idx,size in enumerate(self.size)]
        return axis

    def update_size(self,size):
        """ Update the size and calculate new centers and axis.  """
        self.size = size
        self.center = np.array(self.size) / 2
        self.axis = self._calculate_axis()

    def create(self,dim=1,fwhm=3,center=None):
        """ Generate a gaussian distribution on the center of a certain width.  """
        center = center if center is not None else self.center[:dim]
        distance = sum((ax - ax_center) ** 2 for ax_center,ax in zip(center,self.axis))
        distribution = np.exp(-4 * np.log(2) * distance / fwhm ** 2)
        return distribution

    def creates(self,dim=2,centers: np.ndarray = None):
        """ Combines multiple gaussian distributions based on multiple centers.  """
        centers = np.array(centers or np.array([self.center]).T).T
        indices = np.indices(self.size).reshape(dim,-1).T

        distance = np.min(cdist(indices,centers,metric='euclidean'),axis=1)
        distance = np.power(distance.reshape(self.size),2)

        distribution = np.exp(-4 * np.log(2) * distance / fwhm ** 2)
        return distribution

    @staticmethod
    def plot(distribution,show=True):
        """ Plotter,in case you do not know the dimensions of your distribution,or want the same interface.  """
        if len(distribution.shape) == 1:
            return Gaussian.plot1d(distribution,show)
        if len(distribution.shape) == 2:
            return Gaussian.plot2d(distribution,show)
        if len(distribution.shape) == 3:
            return Gaussian.plot3d(distribution,show)
        raise ValueError(f"Trying to plot {len(distribution.shape)}-dimensional data,"
                         f"Only 1D,2D,and 3D distributions are valid.")

    @staticmethod
    def plot1d(distribution,show=True,vmin=None,vmax=None,cmap=None):
        norm = mpl_colors.Normalize(
                vmin=vmin if vmin is not None else distribution.min(),vmax=vmax if vmin is not None else distribution.max()
        )
        cmap = mpl_cm.ScalarMappable(norm=norm,cmap=cmap or mpl_cm.get_cmap('jet'))
        cmap.set_array(distribution)
        c = [cmap.to_rgba(value) for value in distribution]  # defines the color

        fig,ax = plt.subplots()
        ax.scatter(np.arange(len(distribution)),distribution,c=c)
        ax.plot(distribution)

        fig.colorbar(cmap)
        if show: plt.show()
        return fig

    @staticmethod
    def plot2d(distribution,show=True):
        fig,ax = plt.subplots()
        img = ax.imshow(distribution,cmap='jet')
        fig.colorbar(img)
        if show: plt.show()
        return fig

    @staticmethod
    def plot3d(distribution,show=True):
        m,n,c = distribution.shape
        x,y,z = np.mgrid[:m,:n,:c]
        out = np.column_stack((x.ravel(),y.ravel(),z.ravel(),distribution.ravel()))
        x,z,values = np.array(list(zip(*out)))

        fig = plt.figure()
        ax = fig.add_subplot(111,projection='3d')

        # Standalone colorbar,directly creating colorbar on fig results in strange artifacts.
        img = ax.scatter([0,0],[0,c=[0,1],cmap=mpl_cm.get_cmap('jet'))
        img.set_visible = False
        fig.colorbar(img)

        ax.scatter(x,c=values,cmap=mpl_cm.get_cmap('jet'))
        if show: plt.show()
        return fig

解决方案

由于我不清楚当高斯分布处于多个宽度的一部分时您希望它们如何交互,我将假设您想要最大值。

那么主要的逻辑是,我们现在可以为每个具有给定全宽半最大值 (fwhm) 的中心生成唯一的高斯分布,并取所有分布的最大值。

distribution = np.zeros((1200,))

df = pd.DataFrame(data,"center"])
gaussian = Gaussian(size=distribution.shape)

for idx,row in df.iterrows():
    distribution = np.maximum(distribution,gaussian.create(fwhm=row.fwhm,center=[row.center]))

gaussian.plot(distribution,show=True)

结果

从熊猫文件中绘制多个高斯
      
    数据高斯解决方案结果


编辑

由于问题现在要求不同的分布,您可以使用以下内容调整 create(和 creates)方法中的代码以获得不同类型的分布:

def create(self,center=None):
    """ Generate a gaussian distribution on the center of a certain width.  """
    center = center if center is not None else self.center[:dim]
    distance = sum((ax - ax_center) for ax_center,self.axis))
    distribution = sps.beta.pdf(distance / max(distance),a=3,b=100)
    return distribution

sps.beta 来自 import scipy.stats as sps 的地方,也可以通过伽玛分布进行更改。例如distribution = sps.gamma.pdf(distance,10,40)

请注意,距离不再平方,参数 fwhm 可以替换为分布所需的参数。

大佬总结

以上是大佬教程为你收集整理的从熊猫文件中绘制多个高斯 数据高斯解决方案结果全部内容,希望文章能够帮你解决从熊猫文件中绘制多个高斯 数据高斯解决方案结果所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: