gpt4 book ai didi

python - 在 python 中创建具有多个可变向量属性的类

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:21 24 4
gpt4 key购买 nike

是否正确使用了类方法?

我正在开发一个程序来为 3-D N 体问题创建数据输入。目标是创建一个具有 50000 个粒子的均匀密度球体。每个粒子类实例都必须具有质量、位置和速度。位置向量必须是球形的,因此当创建粒子实例时,它位于半径为 1 的球体内。速度必须在 3 个方向上随机化。这将在以后通过添加轨道速度来改变。所有数据稍后将导出到 3 个列表中,质量、位置和速度都在笛卡尔坐标系中。

我在创建具有此类属性的粒子时遇到了问题。

第一次运行的代码是:

import math
import numpy as np

class Particle:

def__init__(self,mass,position,velocity):
self.mass = 1/50000
self.position = position
self.velocity=velocity

def position(self):
self.position = (self.r, self.theta, self.phi)

@classmethod
def set_r(cls, r):
cls.r = np.rand.uniform(0,1)

@classmethod
def set_theta(cls, theta):
cls.theta = np.rand.uniform(-(math.pi)/2 ,(math.pi)/2)

@classmethod
def set_phi(cls, phi):
cls.phi = np.rand.uniform(0,2*math.pi)

def velocity(self):
self.velocity = (self.Vx, self.Vy, self.Vz)

@classmethod
def set_Vx(cls, Vx):
cls.Vx = np.rand.uniform(0,0.001)

@classmethod
def set_Vy(cls, Vy):
cls.Vy = np.rand.uniform(0,0.001)

@classmethod
def set_Vz(cls, Vz):
cls.Vz = np.rand.uniform(0,0.001)

在与 CS 部门的 friend 交谈后,代码被编辑为:

import math
import numpy as np

class Particle():

def __init__(self,mass,position,velocity):
self.mass = 1/50000
self.position = position[]
self.velocity = velocity[]


@classmethod
def getPosition(cls):
return [cls.r, cls.theta, cls.phi]

@classmethod
def set_r(cls, r):
cls.position[0] = np.rand.uniform(0,1)

@classmethod
def set_theta(cls, theta):
cls.position[1] = np.rand.uniform(-(math.pi)/2 ,(math.pi)/2)

@classmethod
def set_phi(cls, phi):
cls.position[2] = np.rand.uniform(0,2*math.pi)

def getVelocity(cls):
return [cls.Vx, cls.Vy, cls.Vz]

@classmethod
def set_Vx(cls, Vx):
cls.velocity[0] = np.rand.uniform(0,0.001)

@classmethod
def set_Vy(cls, Vy):
cls.velocity[1] = np.rand.uniform(0,0.001)

@classmethod
def set_Vz(cls, Vz):
cls.velocity[2] = np.rand.uniform(0,0.001)

我是否需要在 init 中定义向量的各个部分,然后使用类方法创建要在以后使用和更改的数组?

编辑 1:该类将通过 for 循环运行以创建 50000 个粒子,每个粒子具有相同的质量(归一化为 1/50000)、一个位置向量和一个速度向量。所以导出到列表中的.dat文件

最佳答案

如果我没理解错的话,我认为您在这里不需要 classmethod,而是您希望单独处理每个 Particle。如果我是对的,我相信您正在寻找一个类,每个实例都知道它有自己的质量位置速度。我创建了一个类似于您的类,但我使用 namedtuples 来表示 positionvelocity

import math
import numpy as np
from collections import namedtuple

Position = namedtuple('Position', ('r', 'theta', 'phi'))
Velocity = namedtuple('Velocity', ('Vx', 'Vy', 'Vz'))

class Particle():
#With 50,000 instances being created, I suggest using __slots__ if possible.
#This will cut down some on memory consumption.
__slots__ = ('mass', 'position', 'velocity')

def __init__(self, *args, **kwargs):
self.mass = kwargs.get('mass', None)
self.position = kwargs.get('position', None)
self.velocity = kwargs.get('velocity', None)

#Note! This will automatically set random values if any
#of mass, position, velocity are None when initialized
#so this may need to be altered if this is undesired
#this is just a skeleton example and if it works for you it works
if not any((self.mass, self.position, self.velocity)):
self.setup_random()

def setup_random(self):
self.mass = 1/1500
self.position = Position(
r = np.random.uniform(0,1),
theta = np.random.uniform(-(math.pi)/2 ,(math.pi)/2),
phi = np.random.uniform(0,2*math.pi)
)
self.velocity = Velocity(
Vx = np.random.uniform(0,0.001),
Vy = np.random.uniform(0,0.001),
Vz = np.random.uniform(0,0.001)
)

def set_r(self, r):
self.position = self.position.replace(r = r)

def set_theta(self, theta):
self.position = self.position.replace(theta = theta)

def set_phi(self, phi):
self.position = self.position.replace(phi = phi)

def set_Vx(self, Vx):
self.velocity = self.velocity.replace(Vx = Vx)

def set_Vy(self, Vy):
self.velocity = self.velocity.replace(Vy = Vy)

def set_Vz(self, Vz):
self.velocity = self.velocity.replace(Vz = Vz)

def __str__(self):
return('Mass: {}\nPosition: {}\nVelocity: {}'.format(
self.mass,
self.position,
self.velocity))

def __repr__(self):
return('Mass: {}\nPosition: {}\nVelocity: {}'.format(
self.mass,
self.position,
self.velocity))

从这里您可以使用 Particle()

根据需要制作任意数量的粒子
p = Particle()
print(p)

然后打印:

Mass: 0.0006666666666666666
Position: Position(r=0.8122849235862195, theta=-0.060787026289457646, phi=3.415049614503205)
Velocity: Velocity(Vx=0.0006988289817776562, Vy=0.00040214068163074246, Vz=0.0003347218438727625)

由于 namedtuples 也可以很容易地获得一个值:

print(p.position.r)
#0.8122849235862195

您可以使用如下预定义的值制作粒子:

p = Particle(
mass = 2/5000,
position = Position(r=1, theta = 2, phi = 3),
velocity = Velocity(Vx = 4, Vy = 5, Vz = 6))
print(p)

结果:

Mass: 0.0004
Position: Position(r=1, theta=2, phi=3)
Velocity: Velocity(Vx=4, Vy=5, Vz=6)

您仍然需要 setter 方法来设置单个值,例如 rtheta... 因为元组是不可变的,虽然您也可以轻松地设置一个全新的位置 例如:

#to set an individual value
p.set_r(1)

#setting a whole new position/velocity
p.position = Position(r = 1, theta = 2, phi = 3)
#or
p.position = Position(r = p.position.r, theta = 2, phi = 3)
#as an example

如果您想使用不同的集合类型或任何可以随意使用的东西,我只是觉得 namedtuples 很适合这里。

编辑

允许从数据文件加载和卸载;你可以制作 to_jsonfrom_json 方法。

假设您的一个 Particle 数据如下所示:

d = {'mass': 0.0006666666666666666,
'r': 0.8122849235862195,
'theta': -0.060787026289457646,
'phi': 3.415049614503205,
'Vx': 0.0006988289817776562,
'Vy': 0.00040214068163074246,
'Vz': 0.0003347218438727625
}

你的方法看起来像这样:

def to_json(self):
json_particle = {'mass': self.mass}
json_particle.update(dict(self.position._asdict()))
json_particle.update(dict(self.velocity._asdict()))

return json_particle

#here we finally use @classmethod
#as we are creating a new instance of the class
@classmethod
def from_json(cls, data):
pos = Position(r = data['r'], theta = data['theta'], phi = data['phi'])
vel = Velocity(Vx = data['Vx'], Vy = data['Vy'], Vz = data['Vz'])

return cls(data['mass'], pos, vel)

关于python - 在 python 中创建具有多个可变向量属性的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55035873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com