- 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/
我有 powershell 脚本。通过调度程序,我运行 bat 文件,该文件运行 PS1 文件。 BAT文件 Powershell.exe -executionpolicy remotesigned
什么更快? 或者 $.getScript('../js/SOME.js', function (){ ... // with $.ajaxSetup({ cache: true });
需要bash脚本来显示文件 #!/bin/bash my_ls() { # save current directory then cd to "$1" pushd "$1" >/dev/nu
我有一个输入 csv 文件,实际上我需要在输入文件中选择第 2 列和第 3 列值,并且需要转换两个值的时区(从 PT 到 CT),转换后我需要替换转换后的时区值到文件。 注意: 所有输入日期值都在太平
我正在使用/etc/init.d/httpd 作为 init.d 脚本的模板。我了解文件中发生的所有内容,但以下行除外: LANG=$HTTPD_LANG daemon --pidfile=${pid
我有以下选择: python runscript.py -O start -a "-a "\"-o \\\"-f/dev/sda1 -b256k -Q8\\\" -l test -p maim\""
我对 shell 脚本完全陌生,但我需要编写一个 shell 脚本来检查文件是否存在,然后移动到另一个位置 这是我写的: 一旦设备崩溃,我就会在/storage/sdcard1/1 中收集日志 #!/
我正在使用 bash 脚本从文本文件中读取数据。 数据: 04:31 Alex M.O.R.P.H. & Natalie Gioia - My Heaven http://goo.gl/rMOa2q
这是单击按钮时运行的 javascript 的结尾 xmlObj.open ('GET', /ajax.php, true); xmlObj.send (''); } 所以这会执行根目录中的php脚本
关闭。这个问题需要debugging details .它目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and th
我需要将文件转换为可读流以通过 api 上传,有一个使用 fs.createReadStream 的 Node js 示例。任何人都可以告诉我上述声明的 python 等价物是什么? 例子 const
我有一个 shell 脚本 cron,它从同一目录调用 python 脚本,但是当这个 cron 执行时,我没有从我的 python 脚本中获得预期的输出,当我手动执行它时,我的 python 脚本的
如何使 XMLHttpRequest (ajax) 调用的 php 脚本安全。 我的意思是,不让 PHP 文件通过直接 url 运行,只能通过脚本从我的页面调用(我不想向未登录的用户显示数据库结果,并
我正在尝试添加以下内容 我正在使用经典的 asp。但我不断收到的错误是“一个脚本 block 不能放在另一个脚本 block 内。”我尝试了此处的 document.write 技术:Javasc
如何从另一个 PHP 脚本(如批处理文件)中运行多个 PHP 脚本?如果我了解 include 在做什么,我认为 include 不会起作用;因为我正在运行的每个文件都会重新声明一些相同的函数等。我想
我想创建具有动态内容的网页。我有一个 HTML 页面,我想从中调用一个 lua 脚本 如何调用 lua 脚本? ? ? 从中检索数据?我可以做类似的事情吗: int xx = 0; xx
我删除了我的第一个问题,并重新编写了更多细节和附加 jSfiddle domos。 我有一个脚本,它运行查询并返回数据,然后填充表。表中的行自动循环滚动。所有这些工作正常,并通过使用以下代码完成。然而
我尝试使用 amp 脚本,但收到此错误: “[amp-script] 脚本哈希未找到。amp-script[script="hello-world"].js 必须在元[name="amp-script
我有一个读取输入的 Shell 脚本 #!/bin/bash echo "Type the year that you want to check (4 digits), followed by [E
我正在从 nodejs 调用 Lua 脚本。我想传递一个数组作为参数。我在 Lua 中解析该数组时遇到问题。 下面是一个例子: var script = 'local actorlist = ARGV
我是一名优秀的程序员,十分优秀!