- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我正在运行的模拟的布局
----main directory
-----my_script.py
-----settings_centroid.py
-----utilities (directory)
-----gizmo_analysis (directory)
----gizmo_analysis.py
----gizmo_diagnostic.py
----gizmo_file.py
----gizmo_ic.py
----gizmo_io.py
----gizmo_star.py
----gizmo_track
----gizmo_yield.py
----__init__.py
----
-----gizmo_read (directory)
-----center.py
-----constant.py
-----coordinate.py
-----read.py
-----__init__.py
my_script.py
是:
import gizmo_analysis
import gizmo_read
import utilities as ut
import settings_centroid
settings_centroid.init()
.
.
.
settings_centroid.py
脚本是:
import utilities as ut
import gizmo_analysis
import rockstar_analysis
import gizmo_read
def init():
global h, omega_m, omega_l, part, species, properties
species, properties = 'all', 'all'
part=gizmo_read.read.Read.read_snapshot(species, properties, directory='./output/')
.
.
.
gizmo_analysis.py
是:
#!/usr/bin/env python3
from __future__ import absolute_import, division, print_function # python 2 compatability
import collections
import numpy as np
from numpy import Inf
import matplotlib
from matplotlib import pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from matplotlib import colors
# local ----
import utilities as ut
import gizmo_analysis
import rockstar_analysis
import settings_centroid
settings_centroid.init()
.
.
.
read.py
是:
# system ----
from __future__ import absolute_import, division, print_function # python 2 compatibility
import collections
import glob
import h5py
import numpy as np
from scipy import integrate, interpolate
# local ----
from . import center, constant, coordinate
import settings_centroid
#from .. import settings_centroid
settings_centroid.init()
snapshot_index = settings_centroid.snapshot_number
# store particles as dictionary class
class DictClass(dict):
pass
class ReadClass():
'''
Read Gizmo snapshot.
'''
def __init__(self):
'''
Set properties for snapshot files.
'''
self.snapshot_name_base = 'snap*[!txt]' # avoid accidentally reading snapshot indices file
self.file_extension = '.hdf5'
self.gas_eos = 5 / 3 # gas equation of state
# create ordered dictionary to convert particle species name to its id,
# set all possible species, and set the order in which to read species
self.species_dict = collections.OrderedDict()
# dark-matter species
self.species_dict['dark'] = 1 # dark matter at highest resolution
self.species_dict['dark.2'] = 2 # dark matter at all lower resolutions
# baryon species
self.species_dict['gas'] = 0
self.species_dict['star'] = 4
self.species_all = tuple(self.species_dict.keys())
self.species_read = list(self.species_all)
# use to translate between element name and index in element table
self.element_dict = {}
self.element_dict['total'] = 0
self.element_dict['he'] = 1
self.element_dict['c'] = 2
self.element_dict['n'] = 3
self.element_dict['o'] = 4
self.element_dict['ne'] = 5
self.element_dict['mg'] = 6
self.element_dict['si'] = 7
self.element_dict['s'] = 8
self.element_dict['ca'] = 9
self.element_dict['fe'] = 10
def read_snapshot(
self, species='all', properties='all', directory='.', particle_subsample_factor=None):
'''
Read properties for input particle species from simulation snapshot file[s].
Return particle catalog as a dictionary class.
Parameters
----------
species : string or list : name[s] of particle species:
'all' = all species in file
'star' = stars
'gas' = gas
'dark' = dark matter at highest resolution
'dark.2' = dark matter at lower resolution
properties : string or list : name[s] of particle properties to read - options:
'all' = all species in file
otherwise, list subset from among read_particles.property_dict
for example: ['mass', 'position', 'velocity']
directory : string : directory of snapshot file[s]
particle_subsample_factor : int : factor to periodically subsample particles, to save memory
Returns
-------
part : dictionary class : catalog of particles at snapshot
'''
#snapshot_index = snapshot_index # corresponds to z = 0
# parse input species to read
if species == 'all' or species == ['all'] or not species:
# read all species in snapshot
species = self.species_all
else:
# read subsample of species in snapshot
if np.isscalar(species):
species = [species] # ensure is list
# check if input species names are valid
for spec_name in list(species):
if spec_name not in self.species_dict:
species.remove(spec_name)
print('! not recognize input species = {}'.format(spec_name))
self.species_read = list(species)
# read header from snapshot file
header = self.read_header(snapshot_index, directory)
# read particles from snapshot file[s]
part = self.read_particles(snapshot_index, directory, properties, header)
# assign auxilliary information to particle dictionary class
# store header dictionary
part.info = header
for spec_name in part:
part[spec_name].info = part.info
# get and store cosmological parameters
part.Cosmology = CosmologyClass(
header['omega_lambda'], header['omega_matter'], hubble=header['hubble'])
for spec_name in part:
part[spec_name].Cosmology = part.Cosmology
# store information about snapshot time
time = part.Cosmology.get_time(header['redshift'], 'redshift')
part.snapshot = {
'index': snapshot_index,
'redshift': header['redshift'],
'scalefactor': header['scalefactor'],
'time': time,
'time.lookback': part.Cosmology.get_time(0) - time,
'time.hubble': constant.Gyr_per_sec / part.Cosmology.get_hubble_parameter(0),
}
for spec_name in part:
part[spec_name].snapshot = part.snapshot
# adjust properties for each species
self.adjust_particle_properties(part, header, particle_subsample_factor)
# assign galaxy center position and velocity, principal axes rotation vectors
self.read_galaxy_center_coordinates(part, directory)
# alternately can assign these on the fly
#center.assign_center(part)
#center.assign_principal_axes(part)
# adjust coordinates to be relative to galaxy center position and velocity
# and aligned with principal axes
self.adjust_particle_coordinates(part)
return part
def read_header(self, snapshot_index=snapshot_index, directory='.'):
'''
Read header from snapshot file.
Parameters
----------
snapshot_index : int : index (number) of snapshot file
directory : directory of snapshot
Returns
-------
header : dictionary class : header dictionary
'''
# convert name in snapshot's header dictionary to custom name preference
header_dict = {
# 6-element array of number of particles of each type in file
'NumPart_ThisFile': 'particle.numbers.in.file',
# 6-element array of total number of particles of each type (across all files)
'NumPart_Total': 'particle.numbers.total',
'NumPart_Total_HighWord': 'particle.numbers.total.high.word',
# mass of each particle species, if all particles are same
# (= 0 if they are different, which is usually true)
'MassTable': 'particle.masses',
'Time': 'time', # [Gyr/h]
'BoxSize': 'box.length', # [kpc/h comoving]
'Redshift': 'redshift',
# number of output files per snapshot
'NumFilesPerSnapshot': 'file.number.per.snapshot',
'Omega0': 'omega_matter',
'OmegaLambda': 'omega_lambda',
'HubbleParam': 'hubble',
'Flag_Sfr': 'has.star.formation',
'Flag_Cooling': 'has.cooling',
'Flag_StellarAge': 'has.star.age',
'Flag_Metals': 'has.metals',
'Flag_Feedback': 'has.feedback',
'Flag_DoublePrecision': 'has.double.precision',
'Flag_IC_Info': 'has.ic.info',
# level of compression of snapshot file
'CompactLevel': 'compression.level',
'Compactify_Version': 'compression.version',
'ReadMe': 'compression.readme',
}
header = {} # dictionary to store header information
if directory[-1] != '/':
directory += '/'
file_name = self.get_snapshot_file_name(directory, snapshot_index)
print('reading header from:\n {}'.format(file_name.replace('./', '')))
print()
# open snapshot file
with h5py.File(file_name, 'r') as file_in:
header_in = file_in['Header'].attrs # load header dictionary
for prop_in in header_in:
prop = header_dict[prop_in]
header[prop] = header_in[prop_in] # transfer to custom header dict
# convert header quantities
header['scalefactor'] = float(header['time'])
del(header['time'])
header['box.length/h'] = float(header['box.length'])
header['box.length'] /= header['hubble'] # convert to [kpc comoving]
print('snapshot contains the following number of particles:')
# keep only species that have any particles
read_particle_number = 0
species_read = list(self.species_read)
for species_name in species_read:
if species_name not in self.species_all:
species_read.append(species_name)
for spec_name in species_read:
spec_id = self.species_dict[spec_name]
print(' {:6s} (id = {}): {} particles'.format(
spec_name, spec_id, header['particle.numbers.total'][spec_id]))
if header['particle.numbers.total'][spec_id] > 0:
read_particle_number += header['particle.numbers.total'][spec_id]
elif spec_name in self.species_read:
self.species_read.remove(spec_name)
if read_particle_number <= 0:
raise ValueError('snapshot file[s] contain no particles of species = {}'.format(
self.species_read))
print()
return header
from __future__ import absolute_import # python 2 compatability
from . import gizmo_io as io
from . import gizmo_analysis as analysis
from . import gizmo_ic as ic
from . import gizmo_diagnostic as diagnostic
from . import gizmo_file as file
from . import gizmo_track as track
from . import gizmo_star as star
#from __future__ import absolute_import # python 2 compatability
from . import read
from . import center
from . import constant
from . import coordinate
#from .. import settings_centroid
my_script.py
时收到的错误消息:
Traceback (most recent call last):
File "my_script.py", line 6, in <module>
settings_centroid.init()
File "/usr5/username/settings_centroid.py", line 9, in init
part=gizmo_read.read.Read.read_snapshot(species, properties, directory='./output/')
AttributeError: module 'gizmo_read' has no attribute 'read'
settings_centroid.py
.但是,出于某种原因,我认为现在不会发生这种情况。在实现 Adam、Christian 和 J_H 建议的两个不同更改后,我仍然收到错误消息。
最佳答案
编辑:在更好地理解问题后,我改变了答案。
您的问题来自 循环进口 (例如,参见 this tutorial):您的文件 settings_centroid.py
和 gizmo_read/read.py
两者相互包含。
导入时 settings_centroid.py
, 它导入 reads.py
直接运行 settings_centroid.init()
,但此时 Python 并未加载 settings_centroid.py
中的所有符号,因此找不到 init()
.
循环导入带来了棘手的问题需要解决。
我的建议是重构您的代码以避免它们,如果您的代码库已经很大,这可能需要一些时间。
如果 settings_centroid.py
有一个选项,这可能对您的整个代码的逻辑没有意义,(如果没有,对不起,您必须考虑清楚)是一个辅助类的东西,就是用它做一个子包,并尝试限制它对其他模块的依赖。
如果实在无法重构,可以试试将您的导入限制在函数范围内。
例如,settings_centroid.py
可能成为
import utilities as ut
import gizmo_analysis
import rockstar_analysis
# import gizmo_read <-- important, remove this import
def init():
import gizmo_read # <-- do the import here
global h, omega_m, omega_l, part, species, properties
species, properties = 'all', 'all'
part=gizmo_read.read.ReadClass.read_snapshot(species, properties, directory='./output/')
关于python-3.x - 即使模块实际上包含脚本,模块也没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56138006/
渐进增强和优雅降级基本是一回事吗? 最佳答案 不完全是。他们从不同的 Angular 解决类似的问题。 “优雅的降级”意味着你有漂亮的功能,并且可以在不支持它的浏览器中处理它不那么漂亮(但仍然需要它以
在过去的几周里,我一直在调优和处理 PostgreSQL,我将在我的下一个项目中使用它。 我的规范是: DigitalOcean 8 核 16GB SSD x2(一个用于数据库,另一个用于 Web)
我看过很多关于负数模的问题的答案。每一个答案都放了标准 (a/b)*b + a%b is equal to a 解释。我可以用这种方法计算任何模数,而且我知道有必要使用一个模数函数,如果它是负数,则将
关闭。这个问题是opinion-based .它目前不接受答案。 想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它. 关闭 9 年前。 Improve
The docs假设所有标签都存储在 .hgtags 中,但这里显然存在一些黑魔法。 我的标签如下所示: mbayazit:~/test$ cat .hgtags 0d80b6ba4ba3b51a44
我正在尝试强制删除待处理的更改列表。所有文件(20 个旧文件)都是新文件,但尚未提交/提交。所以在 p4Win 中,它们显示红色 + 十字。我无法从更改列表中删除这些文件。我该如何删除这些文件? 感谢
如果我要删除的文件不属于工作区,那么如何从工作区的目录中删除文件? 我的文件系统上有一个目录,其中包含从 perforce 获取的文件,但在某些进程运行后,它会在这些目录中创建一些新文件。 是否有 p
就是好奇这个。以下是同一功能的两个代码片段: void MyFunc1() { int i = 10; object obj = null; if(something) ret
我对使用约束布局还很陌生,我在调整布局大小方面遇到了问题,我希望它能够响应,这样我就不必再为不同的屏幕尺寸制作 10 个布局。在布局编辑器中,一切在不同尺寸下看起来都很完美,但实际上并非如此。 我做了
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
如果试图修改声明为 const 的对象,const 类型限定符会导致编译器发出错误消息,但这还不够保护。例如以下程序修改声明为 const 的数组的两个元素: #include int main(v
我不得不问这个,因为:我唯一知道的是,如果断言失败,应用程序就会崩溃。这就是为什么要使用 NSAssert 的原因吗?或者这样做还有什么好处?将 NSAssert 置于我在代码中所做的任何假设之上是否
我正在处理我的操作系统项目的 POSIX 子系统,并且我已经达到了我想要处理 pthreads 支持的地步。但是,我不确定我应该在多大程度上实现它们。 最常用的 pthreads 功能是什么?现在有什
这个问题不太可能对任何 future 的访客有帮助;它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况相关,通常不适用于互联网的全局受众。如需帮助使这个问题更广泛适用,visit the h
我正在尝试运行测试类,但抛出错误实际上有零交互。 class Xtractor{ void extractValues(request,Map m1, Map m2,Map m3){
我有一个抽象类UIObject,如下所示: public abstract class UIObject { private final int tabOrder; public UI
这是我尝试在 emacs lisp 中进行一些计算时得到的... (+ 2082844800. 1274511600.0) => 1209872752.0 (+ 2082844800.0 127451
我想用一条垂直线将屏幕分成两部分。垂直线应该从屏幕底部一直延伸到导航栏。如果我们使用 html/css,我只会有 2 个 div,并在右侧 div 上放置一个左边框。如果有办法在 View 的单侧放置
我有一个EC2实例可以正常工作数月(仍在开发中,应用程序尚未启用),但是我只是意识到我什至不知道如何根据流量来扩大/缩小EC2实例。 亚马逊提供的大量服务是压倒性的,我对此感到非常困惑。 最初,虽然我
考虑这个代码: int i = 1; int x = ++i + ++i; 我们对编译器可能会为这段代码做些什么有一些猜测,假设它可以编译。 两者 ++i返回 2 ,导致 x=4 . 一 ++i返回
我是一名优秀的程序员,十分优秀!