code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
import itertools
import logging
import re
import struct
from hashlib import sha256, md5, sha384, sha512
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
KeysView,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
cast,
)
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from . import settings
from .arcfour import Arcfour
from .data_structures import NumberTree
from .pdfparser import PDFSyntaxError, PDFParser, PDFStreamParser
from .pdftypes import (
DecipherCallable,
PDFException,
PDFTypeError,
PDFStream,
PDFObjectNotFound,
decipher_all,
int_value,
str_value,
list_value,
uint_value,
dict_value,
stream_value,
)
from .psparser import PSEOF, literal_name, LIT, KWD
from .utils import choplist, decode_text, nunpack, format_int_roman, format_int_alpha
log = logging.getLogger(__name__)
class PDFNoValidXRef(PDFSyntaxError):
pass
class PDFNoValidXRefWarning(SyntaxWarning):
"""Legacy warning for missing xref.
Not used anymore because warnings.warn is replaced by logger.Logger.warn.
"""
pass
class PDFNoOutlines(PDFException):
pass
class PDFNoPageLabels(PDFException):
pass
class PDFDestinationNotFound(PDFException):
pass
class PDFEncryptionError(PDFException):
pass
class PDFPasswordIncorrect(PDFEncryptionError):
pass
class PDFEncryptionWarning(UserWarning):
"""Legacy warning for failed decryption.
Not used anymore because warnings.warn is replaced by logger.Logger.warn.
"""
pass
class PDFTextExtractionNotAllowedWarning(UserWarning):
"""Legacy warning for PDF that does not allow extraction.
Not used anymore because warnings.warn is replaced by logger.Logger.warn.
"""
pass
class PDFTextExtractionNotAllowed(PDFEncryptionError):
pass
class PDFTextExtractionNotAllowedError(PDFTextExtractionNotAllowed):
def __init__(self, *args: object) -> None:
from warnings import warn
warn(
"PDFTextExtractionNotAllowedError will be removed in the future. "
"Use PDFTextExtractionNotAllowed instead.",
DeprecationWarning,
)
super().__init__(*args)
# some predefined literals and keywords.
LITERAL_OBJSTM = LIT("ObjStm")
LITERAL_XREF = LIT("XRef")
LITERAL_CATALOG = LIT("Catalog")
class PDFBaseXRef:
def get_trailer(self) -> Dict[str, Any]:
raise NotImplementedError
def get_objids(self) -> Iterable[int]:
return []
# Must return
# (strmid, index, genno)
# or (None, pos, genno)
def get_pos(self, objid: int) -> Tuple[Optional[int], int, int]:
raise KeyError(objid)
def load(self, parser: PDFParser) -> None:
raise NotImplementedError
class PDFXRef(PDFBaseXRef):
def __init__(self) -> None:
self.offsets: Dict[int, Tuple[Optional[int], int, int]] = {}
self.trailer: Dict[str, Any] = {}
def __repr__(self) -> str:
return "<PDFXRef: offsets=%r>" % (self.offsets.keys())
def load(self, parser: PDFParser) -> None:
while True:
try:
(pos, line) = parser.nextline()
line = line.strip()
if not line:
continue
except PSEOF:
raise PDFNoValidXRef("Unexpected EOF - file corrupted?")
if line.startswith(b"trailer"):
parser.seek(pos)
break
f = line.split(b" ")
if len(f) != 2:
error_msg = "Trailer not found: {!r}: line={!r}".format(parser, line)
raise PDFNoValidXRef(error_msg)
try:
(start, nobjs) = map(int, f)
except ValueError:
error_msg = "Invalid line: {!r}: line={!r}".format(parser, line)
raise PDFNoValidXRef(error_msg)
for objid in range(start, start + nobjs):
try:
(_, line) = parser.nextline()
line = line.strip()
except PSEOF:
raise PDFNoValidXRef("Unexpected EOF - file corrupted?")
f = line.split(b" ")
if len(f) != 3:
error_msg = "Invalid XRef format: {!r}, line={!r}".format(
parser, line
)
raise PDFNoValidXRef(error_msg)
(pos_b, genno_b, use_b) = f
if use_b != b"n":
continue
self.offsets[objid] = (None, int(pos_b), int(genno_b))
log.debug("xref objects: %r", self.offsets)
self.load_trailer(parser)
def load_trailer(self, parser: PDFParser) -> None:
try:
(_, kwd) = parser.nexttoken()
assert kwd is KWD(b"trailer"), str(kwd)
(_, dic) = parser.nextobject()
except PSEOF:
x = parser.pop(1)
if not x:
raise PDFNoValidXRef("Unexpected EOF - file corrupted")
(_, dic) = x[0]
self.trailer.update(dict_value(dic))
log.debug("trailer=%r", self.trailer)
def get_trailer(self) -> Dict[str, Any]:
return self.trailer
def get_objids(self) -> KeysView[int]:
return self.offsets.keys()
def get_pos(self, objid: int) -> Tuple[Optional[int], int, int]:
try:
return self.offsets[objid]
except KeyError:
raise
class PDFXRefFallback(PDFXRef):
def __repr__(self) -> str:
return "<PDFXRefFallback: offsets=%r>" % (self.offsets.keys())
PDFOBJ_CUE = re.compile(r"^(\d+)\s+(\d+)\s+obj\b")
def load(self, parser: PDFParser) -> None:
parser.seek(0)
while 1:
try:
(pos, line_bytes) = parser.nextline()
except PSEOF:
break
if line_bytes.startswith(b"trailer"):
parser.seek(pos)
self.load_trailer(parser)
log.debug("trailer: %r", self.trailer)
break
line = line_bytes.decode("latin-1") # default pdf encoding
m = self.PDFOBJ_CUE.match(line)
if not m:
continue
(objid_s, genno_s) = m.groups()
objid = int(objid_s)
genno = int(genno_s)
self.offsets[objid] = (None, pos, genno)
# expand ObjStm.
parser.seek(pos)
(_, obj) = parser.nextobject()
if isinstance(obj, PDFStream) and obj.get("Type") is LITERAL_OBJSTM:
stream = stream_value(obj)
try:
n = stream["N"]
except KeyError:
if settings.STRICT:
raise PDFSyntaxError("N is not defined: %r" % stream)
n = 0
parser1 = PDFStreamParser(stream.get_data())
objs: List[int] = []
try:
while 1:
(_, obj) = parser1.nextobject()
objs.append(cast(int, obj))
except PSEOF:
pass
n = min(n, len(objs) // 2)
for index in range(n):
objid1 = objs[index * 2]
self.offsets[objid1] = (objid, index, 0)
class PDFXRefStream(PDFBaseXRef):
def __init__(self) -> None:
self.data: Optional[bytes] = None
self.entlen: Optional[int] = None
self.fl1: Optional[int] = None
self.fl2: Optional[int] = None
self.fl3: Optional[int] = None
self.ranges: List[Tuple[int, int]] = []
def __repr__(self) -> str:
return "<PDFXRefStream: ranges=%r>" % (self.ranges)
def load(self, parser: PDFParser) -> None:
(_, objid) = parser.nexttoken() # ignored
(_, genno) = parser.nexttoken() # ignored
(_, kwd) = parser.nexttoken()
(_, stream) = parser.nextobject()
if not isinstance(stream, PDFStream) or stream.get("Type") is not LITERAL_XREF:
raise PDFNoValidXRef("Invalid PDF stream spec.")
size = stream["Size"]
index_array = stream.get("Index", (0, size))
if len(index_array) % 2 != 0:
raise PDFSyntaxError("Invalid index number")
self.ranges.extend(cast(Iterator[Tuple[int, int]], choplist(2, index_array)))
(self.fl1, self.fl2, self.fl3) = stream["W"]
assert self.fl1 is not None and self.fl2 is not None and self.fl3 is not None
self.data = stream.get_data()
self.entlen = self.fl1 + self.fl2 + self.fl3
self.trailer = stream.attrs
log.debug(
"xref stream: objid=%s, fields=%d,%d,%d",
", ".join(map(repr, self.ranges)),
self.fl1,
self.fl2,
self.fl3,
)
return
def get_trailer(self) -> Dict[str, Any]:
return self.trailer
def get_objids(self) -> Iterator[int]:
for (start, nobjs) in self.ranges:
for i in range(nobjs):
assert self.entlen is not None
assert self.data is not None
offset = self.entlen * i
ent = self.data[offset : offset + self.entlen]
f1 = nunpack(ent[: self.fl1], 1)
if f1 == 1 or f1 == 2:
yield start + i
return
def get_pos(self, objid: int) -> Tuple[Optional[int], int, int]:
index = 0
for (start, nobjs) in self.ranges:
if start <= objid and objid < start + nobjs:
index += objid - start
break
else:
index += nobjs
else:
raise KeyError(objid)
assert self.entlen is not None
assert self.data is not None
assert self.fl1 is not None and self.fl2 is not None and self.fl3 is not None
offset = self.entlen * index
ent = self.data[offset : offset + self.entlen]
f1 = nunpack(ent[: self.fl1], 1)
f2 = nunpack(ent[self.fl1 : self.fl1 + self.fl2])
f3 = nunpack(ent[self.fl1 + self.fl2 :])
if f1 == 1:
return (None, f2, f3)
elif f1 == 2:
return (f2, f3, 0)
else:
# this is a free object
raise KeyError(objid)
class PDFStandardSecurityHandler:
PASSWORD_PADDING = (
b"(\xbfN^Nu\x8aAd\x00NV\xff\xfa\x01\x08"
b"..\x00\xb6\xd0h>\x80/\x0c\xa9\xfedSiz"
)
supported_revisions: Tuple[int, ...] = (2, 3)
def __init__(
self, docid: Sequence[bytes], param: Dict[str, Any], password: str = ""
) -> None:
self.docid = docid
self.param = param
self.password = password
self.init()
return
def init(self) -> None:
self.init_params()
if self.r not in self.supported_revisions:
error_msg = "Unsupported revision: param=%r" % self.param
raise PDFEncryptionError(error_msg)
self.init_key()
return
def init_params(self) -> None:
self.v = int_value(self.param.get("V", 0))
self.r = int_value(self.param["R"])
self.p = uint_value(self.param["P"], 32)
self.o = str_value(self.param["O"])
self.u = str_value(self.param["U"])
self.length = int_value(self.param.get("Length", 40))
return
def init_key(self) -> None:
self.key = self.authenticate(self.password)
if self.key is None:
raise PDFPasswordIncorrect
return
def is_printable(self) -> bool:
return bool(self.p & 4)
def is_modifiable(self) -> bool:
return bool(self.p & 8)
def is_extractable(self) -> bool:
return bool(self.p & 16)
def compute_u(self, key: bytes) -> bytes:
if self.r == 2:
# Algorithm 3.4
return Arcfour(key).encrypt(self.PASSWORD_PADDING) # 2
else:
# Algorithm 3.5
hash = md5(self.PASSWORD_PADDING) # 2
hash.update(self.docid[0]) # 3
result = Arcfour(key).encrypt(hash.digest()) # 4
for i in range(1, 20): # 5
k = b"".join(bytes((c ^ i,)) for c in iter(key))
result = Arcfour(k).encrypt(result)
result += result # 6
return result
def compute_encryption_key(self, password: bytes) -> bytes:
# Algorithm 3.2
password = (password + self.PASSWORD_PADDING)[:32] # 1
hash = md5(password) # 2
hash.update(self.o) # 3
# See https://github.com/pdfminer/pdfminer.six/issues/186
hash.update(struct.pack("<L", self.p)) # 4
hash.update(self.docid[0]) # 5
if self.r >= 4:
if not cast(PDFStandardSecurityHandlerV4, self).encrypt_metadata:
hash.update(b"\xff\xff\xff\xff")
result = hash.digest()
n = 5
if self.r >= 3:
n = self.length // 8
for _ in range(50):
result = md5(result[:n]).digest()
return result[:n]
def authenticate(self, password: str) -> Optional[bytes]:
password_bytes = password.encode("latin1")
key = self.authenticate_user_password(password_bytes)
if key is None:
key = self.authenticate_owner_password(password_bytes)
return key
def authenticate_user_password(self, password: bytes) -> Optional[bytes]:
key = self.compute_encryption_key(password)
if self.verify_encryption_key(key):
return key
else:
return None
def verify_encryption_key(self, key: bytes) -> bool:
# Algorithm 3.6
u = self.compute_u(key)
if self.r == 2:
return u == self.u
return u[:16] == self.u[:16]
def authenticate_owner_password(self, password: bytes) -> Optional[bytes]:
# Algorithm 3.7
password = (password + self.PASSWORD_PADDING)[:32]
hash = md5(password)
if self.r >= 3:
for _ in range(50):
hash = md5(hash.digest())
n = 5
if self.r >= 3:
n = self.length // 8
key = hash.digest()[:n]
if self.r == 2:
user_password = Arcfour(key).decrypt(self.o)
else:
user_password = self.o
for i in range(19, -1, -1):
k = b"".join(bytes((c ^ i,)) for c in iter(key))
user_password = Arcfour(k).decrypt(user_password)
return self.authenticate_user_password(user_password)
def decrypt(
self,
objid: int,
genno: int,
data: bytes,
attrs: Optional[Dict[str, Any]] = None,
) -> bytes:
return self.decrypt_rc4(objid, genno, data)
def decrypt_rc4(self, objid: int, genno: int, data: bytes) -> bytes:
assert self.key is not None
key = self.key + struct.pack("<L", objid)[:3] + struct.pack("<L", genno)[:2]
hash = md5(key)
key = hash.digest()[: min(len(key), 16)]
return Arcfour(key).decrypt(data)
class PDFStandardSecurityHandlerV4(PDFStandardSecurityHandler):
supported_revisions: Tuple[int, ...] = (4,)
def init_params(self) -> None:
super().init_params()
self.length = 128
self.cf = dict_value(self.param.get("CF"))
self.stmf = literal_name(self.param["StmF"])
self.strf = literal_name(self.param["StrF"])
self.encrypt_metadata = bool(self.param.get("EncryptMetadata", True))
if self.stmf != self.strf:
error_msg = "Unsupported crypt filter: param=%r" % self.param
raise PDFEncryptionError(error_msg)
self.cfm = {}
for k, v in self.cf.items():
f = self.get_cfm(literal_name(v["CFM"]))
if f is None:
error_msg = "Unknown crypt filter method: param=%r" % self.param
raise PDFEncryptionError(error_msg)
self.cfm[k] = f
self.cfm["Identity"] = self.decrypt_identity
if self.strf not in self.cfm:
error_msg = "Undefined crypt filter: param=%r" % self.param
raise PDFEncryptionError(error_msg)
return
def get_cfm(self, name: str) -> Optional[Callable[[int, int, bytes], bytes]]:
if name == "V2":
return self.decrypt_rc4
elif name == "AESV2":
return self.decrypt_aes128
else:
return None
def decrypt(
self,
objid: int,
genno: int,
data: bytes,
attrs: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
) -> bytes:
if not self.encrypt_metadata and attrs is not None:
t = attrs.get("Type")
if t is not None and literal_name(t) == "Metadata":
return data
if name is None:
name = self.strf
return self.cfm[name](objid, genno, data)
def decrypt_identity(self, objid: int, genno: int, data: bytes) -> bytes:
return data
def decrypt_aes128(self, objid: int, genno: int, data: bytes) -> bytes:
assert self.key is not None
key = (
self.key
+ struct.pack("<L", objid)[:3]
+ struct.pack("<L", genno)[:2]
+ b"sAlT"
)
hash = md5(key)
key = hash.digest()[: min(len(key), 16)]
initialization_vector = data[:16]
ciphertext = data[16:]
cipher = Cipher(
algorithms.AES(key),
modes.CBC(initialization_vector),
backend=default_backend(),
) # type: ignore
return cipher.decryptor().update(ciphertext) # type: ignore
class PDFStandardSecurityHandlerV5(PDFStandardSecurityHandlerV4):
supported_revisions = (5, 6)
def init_params(self) -> None:
super().init_params()
self.length = 256
self.oe = str_value(self.param["OE"])
self.ue = str_value(self.param["UE"])
self.o_hash = self.o[:32]
self.o_validation_salt = self.o[32:40]
self.o_key_salt = self.o[40:]
self.u_hash = self.u[:32]
self.u_validation_salt = self.u[32:40]
self.u_key_salt = self.u[40:]
return
def get_cfm(self, name: str) -> Optional[Callable[[int, int, bytes], bytes]]:
if name == "AESV3":
return self.decrypt_aes256
else:
return None
def authenticate(self, password: str) -> Optional[bytes]:
password_b = self._normalize_password(password)
hash = self._password_hash(password_b, self.o_validation_salt, self.u)
if hash == self.o_hash:
hash = self._password_hash(password_b, self.o_key_salt, self.u)
cipher = Cipher(
algorithms.AES(hash), modes.CBC(b"\0" * 16), backend=default_backend()
) # type: ignore
return cipher.decryptor().update(self.oe) # type: ignore
hash = self._password_hash(password_b, self.u_validation_salt)
if hash == self.u_hash:
hash = self._password_hash(password_b, self.u_key_salt)
cipher = Cipher(
algorithms.AES(hash), modes.CBC(b"\0" * 16), backend=default_backend()
) # type: ignore
return cipher.decryptor().update(self.ue) # type: ignore
return None
def _normalize_password(self, password: str) -> bytes:
if self.r == 6:
# saslprep expects non-empty strings, apparently
if not password:
return b""
from ._saslprep import saslprep
password = saslprep(password)
return password.encode("utf-8")[:127]
def _password_hash(
self, password: bytes, salt: bytes, vector: Optional[bytes] = None
) -> bytes:
"""
Compute password hash depending on revision number
"""
if self.r == 5:
return self._r5_password(password, salt, vector)
return self._r6_password(password, salt[0:8], vector)
def _r5_password(
self, password: bytes, salt: bytes, vector: Optional[bytes] = None
) -> bytes:
"""
Compute the password for revision 5
"""
hash = sha256(password)
hash.update(salt)
if vector is not None:
hash.update(vector)
return hash.digest()
def _r6_password(
self, password: bytes, salt: bytes, vector: Optional[bytes] = None
) -> bytes:
"""
Compute the password for revision 6
"""
initial_hash = sha256(password)
initial_hash.update(salt)
if vector is not None:
initial_hash.update(vector)
k = initial_hash.digest()
hashes = (sha256, sha384, sha512)
round_no = last_byte_val = 0
while round_no < 64 or last_byte_val > round_no - 32:
k1 = (password + k + (vector or b"")) * 64
e = self._aes_cbc_encrypt(key=k[:16], iv=k[16:32], data=k1)
# compute the first 16 bytes of e,
# interpreted as an unsigned integer mod 3
next_hash = hashes[self._bytes_mod_3(e[:16])]
k = next_hash(e).digest()
last_byte_val = e[len(e) - 1]
round_no += 1
return k[:32]
@staticmethod
def _bytes_mod_3(input_bytes: bytes) -> int:
# 256 is 1 mod 3, so we can just sum 'em
return sum(b % 3 for b in input_bytes) % 3
def _aes_cbc_encrypt(self, key: bytes, iv: bytes, data: bytes) -> bytes:
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
encryptor = cipher.encryptor() # type: ignore
return encryptor.update(data) + encryptor.finalize() # type: ignore
def decrypt_aes256(self, objid: int, genno: int, data: bytes) -> bytes:
initialization_vector = data[:16]
ciphertext = data[16:]
assert self.key is not None
cipher = Cipher(
algorithms.AES(self.key),
modes.CBC(initialization_vector),
backend=default_backend(),
) # type: ignore
return cipher.decryptor().update(ciphertext) # type: ignore
class PDFDocument:
"""PDFDocument object represents a PDF document.
Since a PDF file can be very big, normally it is not loaded at
once. So PDF document has to cooperate with a PDF parser in order to
dynamically import the data as processing goes.
Typical usage:
doc = PDFDocument(parser, password)
obj = doc.getobj(objid)
"""
security_handler_registry: Dict[int, Type[PDFStandardSecurityHandler]] = {
1: PDFStandardSecurityHandler,
2: PDFStandardSecurityHandler,
4: PDFStandardSecurityHandlerV4,
5: PDFStandardSecurityHandlerV5,
}
def __init__(
self,
parser: PDFParser,
password: str = "",
caching: bool = True,
fallback: bool = True,
) -> None:
"Set the document to use a given PDFParser object."
self.caching = caching
self.xrefs: List[PDFBaseXRef] = []
self.info = []
self.catalog: Dict[str, Any] = {}
self.encryption: Optional[Tuple[Any, Any]] = None
self.decipher: Optional[DecipherCallable] = None
self._parser = None
self._cached_objs: Dict[int, Tuple[object, int]] = {}
self._parsed_objs: Dict[int, Tuple[List[object], int]] = {}
self._parser = parser
self._parser.set_document(self)
self.is_printable = self.is_modifiable = self.is_extractable = True
# Retrieve the information of each header that was appended
# (maybe multiple times) at the end of the document.
try:
pos = self.find_xref(parser)
self.read_xref_from(parser, pos, self.xrefs)
except PDFNoValidXRef:
if fallback:
parser.fallback = True
newxref = PDFXRefFallback()
newxref.load(parser)
self.xrefs.append(newxref)
for xref in self.xrefs:
trailer = xref.get_trailer()
if not trailer:
continue
# If there's an encryption info, remember it.
if "Encrypt" in trailer:
if "ID" in trailer:
id_value = list_value(trailer["ID"])
else:
# Some documents may not have a /ID, use two empty
# byte strings instead. Solves
# https://github.com/pdfminer/pdfminer.six/issues/594
id_value = (b"", b"")
self.encryption = (id_value, dict_value(trailer["Encrypt"]))
self._initialize_password(password)
if "Info" in trailer:
self.info.append(dict_value(trailer["Info"]))
if "Root" in trailer:
# Every PDF file must have exactly one /Root dictionary.
self.catalog = dict_value(trailer["Root"])
break
else:
raise PDFSyntaxError("No /Root object! - Is this really a PDF?")
if self.catalog.get("Type") is not LITERAL_CATALOG:
if settings.STRICT:
raise PDFSyntaxError("Catalog not found!")
return
KEYWORD_OBJ = KWD(b"obj")
# _initialize_password(password=b'')
# Perform the initialization with a given password.
def _initialize_password(self, password: str = "") -> None:
assert self.encryption is not None
(docid, param) = self.encryption
if literal_name(param.get("Filter")) != "Standard":
raise PDFEncryptionError("Unknown filter: param=%r" % param)
v = int_value(param.get("V", 0))
factory = self.security_handler_registry.get(v)
if factory is None:
raise PDFEncryptionError("Unknown algorithm: param=%r" % param)
handler = factory(docid, param, password)
self.decipher = handler.decrypt
self.is_printable = handler.is_printable()
self.is_modifiable = handler.is_modifiable()
self.is_extractable = handler.is_extractable()
assert self._parser is not None
self._parser.fallback = False # need to read streams with exact length
return
def _getobj_objstm(self, stream: PDFStream, index: int, objid: int) -> object:
if stream.objid in self._parsed_objs:
(objs, n) = self._parsed_objs[stream.objid]
else:
(objs, n) = self._get_objects(stream)
if self.caching:
assert stream.objid is not None
self._parsed_objs[stream.objid] = (objs, n)
i = n * 2 + index
try:
obj = objs[i]
except IndexError:
raise PDFSyntaxError("index too big: %r" % index)
return obj
def _get_objects(self, stream: PDFStream) -> Tuple[List[object], int]:
if stream.get("Type") is not LITERAL_OBJSTM:
if settings.STRICT:
raise PDFSyntaxError("Not a stream object: %r" % stream)
try:
n = cast(int, stream["N"])
except KeyError:
if settings.STRICT:
raise PDFSyntaxError("N is not defined: %r" % stream)
n = 0
parser = PDFStreamParser(stream.get_data())
parser.set_document(self)
objs: List[object] = []
try:
while 1:
(_, obj) = parser.nextobject()
objs.append(obj)
except PSEOF:
pass
return (objs, n)
def _getobj_parse(self, pos: int, objid: int) -> object:
assert self._parser is not None
self._parser.seek(pos)
(_, objid1) = self._parser.nexttoken() # objid
(_, genno) = self._parser.nexttoken() # genno
(_, kwd) = self._parser.nexttoken()
# hack around malformed pdf files
# copied from https://github.com/jaepil/pdfminer3k/blob/master/
# pdfminer/pdfparser.py#L399
# to solve https://github.com/pdfminer/pdfminer.six/issues/56
# assert objid1 == objid, str((objid1, objid))
if objid1 != objid:
x = []
while kwd is not self.KEYWORD_OBJ:
(_, kwd) = self._parser.nexttoken()
x.append(kwd)
if len(x) >= 2:
objid1 = x[-2]
# #### end hack around malformed pdf files
if objid1 != objid:
raise PDFSyntaxError("objid mismatch: {!r}={!r}".format(objid1, objid))
if kwd != KWD(b"obj"):
raise PDFSyntaxError("Invalid object spec: offset=%r" % pos)
(_, obj) = self._parser.nextobject()
return obj
# can raise PDFObjectNotFound
def getobj(self, objid: int) -> object:
"""Get object from PDF
:raises PDFException if PDFDocument is not initialized
:raises PDFObjectNotFound if objid does not exist in PDF
"""
if not self.xrefs:
raise PDFException("PDFDocument is not initialized")
log.debug("getobj: objid=%r", objid)
if objid in self._cached_objs:
(obj, genno) = self._cached_objs[objid]
else:
for xref in self.xrefs:
try:
(strmid, index, genno) = xref.get_pos(objid)
except KeyError:
continue
try:
if strmid is not None:
stream = stream_value(self.getobj(strmid))
obj = self._getobj_objstm(stream, index, objid)
else:
obj = self._getobj_parse(index, objid)
if self.decipher:
obj = decipher_all(self.decipher, objid, genno, obj)
if isinstance(obj, PDFStream):
obj.set_objid(objid, genno)
break
except (PSEOF, PDFSyntaxError):
continue
else:
raise PDFObjectNotFound(objid)
log.debug("register: objid=%r: %r", objid, obj)
if self.caching:
self._cached_objs[objid] = (obj, genno)
return obj
OutlineType = Tuple[Any, Any, Any, Any, Any]
def get_outlines(self) -> Iterator[OutlineType]:
if "Outlines" not in self.catalog:
raise PDFNoOutlines
def search(entry: object, level: int) -> Iterator[PDFDocument.OutlineType]:
entry = dict_value(entry)
if "Title" in entry:
if "A" in entry or "Dest" in entry:
title = decode_text(str_value(entry["Title"]))
dest = entry.get("Dest")
action = entry.get("A")
se = entry.get("SE")
yield (level, title, dest, action, se)
if "First" in entry and "Last" in entry:
yield from search(entry["First"], level + 1)
if "Next" in entry:
yield from search(entry["Next"], level)
return
return search(self.catalog["Outlines"], 0)
def get_page_labels(self) -> Iterator[str]:
"""
Generate page label strings for the PDF document.
If the document includes page labels, generates strings, one per page.
If not, raises PDFNoPageLabels.
The resulting iteration is unbounded.
"""
assert self.catalog is not None
try:
page_labels = PageLabels(self.catalog["PageLabels"])
except (PDFTypeError, KeyError):
raise PDFNoPageLabels
return page_labels.labels
def lookup_name(self, cat: str, key: Union[str, bytes]) -> Any:
try:
names = dict_value(self.catalog["Names"])
except (PDFTypeError, KeyError):
raise KeyError((cat, key))
# may raise KeyError
d0 = dict_value(names[cat])
def lookup(d: Dict[str, Any]) -> Any:
if "Limits" in d:
(k1, k2) = list_value(d["Limits"])
if key < k1 or k2 < key:
return None
if "Names" in d:
objs = list_value(d["Names"])
names = dict(
cast(Iterator[Tuple[Union[str, bytes], Any]], choplist(2, objs))
)
return names[key]
if "Kids" in d:
for c in list_value(d["Kids"]):
v = lookup(dict_value(c))
if v:
return v
raise KeyError((cat, key))
return lookup(d0)
def get_dest(self, name: Union[str, bytes]) -> Any:
try:
# PDF-1.2 or later
obj = self.lookup_name("Dests", name)
except KeyError:
# PDF-1.1 or prior
if "Dests" not in self.catalog:
raise PDFDestinationNotFound(name)
d0 = dict_value(self.catalog["Dests"])
if name not in d0:
raise PDFDestinationNotFound(name)
obj = d0[name]
return obj
# find_xref
def find_xref(self, parser: PDFParser) -> int:
"""Internal function used to locate the first XRef."""
# search the last xref table by scanning the file backwards.
prev = None
for line in parser.revreadlines():
line = line.strip()
log.debug("find_xref: %r", line)
if line == b"startxref":
break
if line:
prev = line
else:
raise PDFNoValidXRef("Unexpected EOF")
log.debug("xref found: pos=%r", prev)
assert prev is not None
return int(prev)
# read xref table
def read_xref_from(
self, parser: PDFParser, start: int, xrefs: List[PDFBaseXRef]
) -> None:
"""Reads XRefs from the given location."""
parser.seek(start)
parser.reset()
try:
(pos, token) = parser.nexttoken()
except PSEOF:
raise PDFNoValidXRef("Unexpected EOF")
log.debug("read_xref_from: start=%d, token=%r", start, token)
if isinstance(token, int):
# XRefStream: PDF-1.5
parser.seek(pos)
parser.reset()
xref: PDFBaseXRef = PDFXRefStream()
xref.load(parser)
else:
if token is parser.KEYWORD_XREF:
parser.nextline()
xref = PDFXRef()
xref.load(parser)
xrefs.append(xref)
trailer = xref.get_trailer()
log.debug("trailer: %r", trailer)
if "XRefStm" in trailer:
pos = int_value(trailer["XRefStm"])
self.read_xref_from(parser, pos, xrefs)
if "Prev" in trailer:
# find previous xref
pos = int_value(trailer["Prev"])
self.read_xref_from(parser, pos, xrefs)
return
class PageLabels(NumberTree):
"""PageLabels from the document catalog.
See Section 8.3.1 in the PDF Reference.
"""
@property
def labels(self) -> Iterator[str]:
ranges = self.values
# The tree must begin with page index 0
if len(ranges) == 0 or ranges[0][0] != 0:
if settings.STRICT:
raise PDFSyntaxError("PageLabels is missing page index 0")
else:
# Try to cope, by assuming empty labels for the initial pages
ranges.insert(0, (0, {}))
for (next, (start, label_dict_unchecked)) in enumerate(ranges, 1):
label_dict = dict_value(label_dict_unchecked)
style = label_dict.get("S")
prefix = decode_text(str_value(label_dict.get("P", b"")))
first_value = int_value(label_dict.get("St", 1))
if next == len(ranges):
# This is the last specified range. It continues until the end
# of the document.
values: Iterable[int] = itertools.count(first_value)
else:
end, _ = ranges[next]
range_length = end - start
values = range(first_value, first_value + range_length)
for value in values:
label = self._format_page_label(value, style)
yield prefix + label
@staticmethod
def _format_page_label(value: int, style: Any) -> str:
"""Format page label value in a specific style"""
if style is None:
label = ""
elif style is LIT("D"): # Decimal arabic numerals
label = str(value)
elif style is LIT("R"): # Uppercase roman numerals
label = format_int_roman(value).upper()
elif style is LIT("r"): # Lowercase roman numerals
label = format_int_roman(value)
elif style is LIT("A"): # Uppercase letters A-Z, AA-ZZ...
label = format_int_alpha(value).upper()
elif style is LIT("a"): # Lowercase letters a-z, aa-zz...
label = format_int_alpha(value)
else:
log.warning("Unknown page label style: %r", style)
label = ""
return label
|
20220429-pdfminer-jameslp310
|
/20220429_pdfminer_jameslp310-0.0.2-py3-none-any.whl/pdfminer/pdfdocument.py
|
pdfdocument.py
|
import heapq
import logging
from typing import (
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
)
from .pdfcolor import PDFColorSpace
from .pdffont import PDFFont
from .pdfinterp import Color
from .pdfinterp import PDFGraphicState
from .pdftypes import PDFStream
from .utils import INF
from .utils import LTComponentT
from .utils import Matrix
from .utils import Plane
from .utils import Point
from .utils import Rect
from .utils import apply_matrix_pt
from .utils import bbox2str
from .utils import fsplit
from .utils import get_bound
from .utils import matrix2str
from .utils import uniq
logger = logging.getLogger(__name__)
class IndexAssigner:
def __init__(self, index: int = 0) -> None:
self.index = index
def run(self, obj: "LTItem") -> None:
if isinstance(obj, LTTextBox):
obj.index = self.index
self.index += 1
elif isinstance(obj, LTTextGroup):
for x in obj:
self.run(x)
class LAParams:
"""Parameters for layout analysis
:param line_overlap: If two characters have more overlap than this they
are considered to be on the same line. The overlap is specified
relative to the minimum height of both characters.
:param char_margin: If two characters are closer together than this
margin they are considered part of the same line. The margin is
specified relative to the width of the character.
:param word_margin: If two characters on the same line are further apart
than this margin then they are considered to be two separate words, and
an intermediate space will be added for readability. The margin is
specified relative to the width of the character.
:param line_margin: If two lines are are close together they are
considered to be part of the same paragraph. The margin is
specified relative to the height of a line.
:param boxes_flow: Specifies how much a horizontal and vertical position
of a text matters when determining the order of text boxes. The value
should be within the range of -1.0 (only horizontal position
matters) to +1.0 (only vertical position matters). You can also pass
`None` to disable advanced layout analysis, and instead return text
based on the position of the bottom left corner of the text box.
:param detect_vertical: If vertical text should be considered during
layout analysis
:param all_texts: If layout analysis should be performed on text in
figures.
"""
def __init__(
self,
line_overlap: float = 0.5,
char_margin: float = 2.0,
line_margin: float = 0.5,
word_margin: float = 0.1,
boxes_flow: Optional[float] = 0.5,
detect_vertical: bool = False,
all_texts: bool = False,
) -> None:
self.line_overlap = line_overlap
self.char_margin = char_margin
self.line_margin = line_margin
self.word_margin = word_margin
self.boxes_flow = boxes_flow
self.detect_vertical = detect_vertical
self.all_texts = all_texts
self._validate()
def _validate(self) -> None:
if self.boxes_flow is not None:
boxes_flow_err_msg = (
"LAParam boxes_flow should be None, or a " "number between -1 and +1"
)
if not (
isinstance(self.boxes_flow, int) or isinstance(self.boxes_flow, float)
):
raise TypeError(boxes_flow_err_msg)
if not -1 <= self.boxes_flow <= 1:
raise ValueError(boxes_flow_err_msg)
def __repr__(self) -> str:
return (
"<LAParams: char_margin=%.1f, line_margin=%.1f, "
"word_margin=%.1f all_texts=%r>"
% (self.char_margin, self.line_margin, self.word_margin, self.all_texts)
)
class LTItem:
"""Interface for things that can be analyzed"""
def analyze(self, laparams: LAParams) -> None:
"""Perform the layout analysis."""
pass
class LTText:
"""Interface for things that have text"""
def __repr__(self) -> str:
return "<%s %r>" % (self.__class__.__name__, self.get_text())
def get_text(self) -> str:
"""Text contained in this object"""
raise NotImplementedError
class LTComponent(LTItem):
"""Object with a bounding box"""
def __init__(self, bbox: Rect) -> None:
LTItem.__init__(self)
self.set_bbox(bbox)
def __repr__(self) -> str:
return "<%s %s>" % (self.__class__.__name__, bbox2str(self.bbox))
# Disable comparison.
def __lt__(self, _: object) -> bool:
raise ValueError
def __le__(self, _: object) -> bool:
raise ValueError
def __gt__(self, _: object) -> bool:
raise ValueError
def __ge__(self, _: object) -> bool:
raise ValueError
def set_bbox(self, bbox: Rect) -> None:
(x0, y0, x1, y1) = bbox
self.x0 = x0
self.y0 = y0
self.x1 = x1
self.y1 = y1
self.width = x1 - x0
self.height = y1 - y0
self.bbox = bbox
def is_empty(self) -> bool:
return self.width <= 0 or self.height <= 0
def is_hoverlap(self, obj: "LTComponent") -> bool:
assert isinstance(obj, LTComponent), str(type(obj))
return obj.x0 <= self.x1 and self.x0 <= obj.x1
def hdistance(self, obj: "LTComponent") -> float:
assert isinstance(obj, LTComponent), str(type(obj))
if self.is_hoverlap(obj):
return 0
else:
return min(abs(self.x0 - obj.x1), abs(self.x1 - obj.x0))
def hoverlap(self, obj: "LTComponent") -> float:
assert isinstance(obj, LTComponent), str(type(obj))
if self.is_hoverlap(obj):
return min(abs(self.x0 - obj.x1), abs(self.x1 - obj.x0))
else:
return 0
def is_voverlap(self, obj: "LTComponent") -> bool:
assert isinstance(obj, LTComponent), str(type(obj))
return obj.y0 <= self.y1 and self.y0 <= obj.y1
def vdistance(self, obj: "LTComponent") -> float:
assert isinstance(obj, LTComponent), str(type(obj))
if self.is_voverlap(obj):
return 0
else:
return min(abs(self.y0 - obj.y1), abs(self.y1 - obj.y0))
def voverlap(self, obj: "LTComponent") -> float:
assert isinstance(obj, LTComponent), str(type(obj))
if self.is_voverlap(obj):
return min(abs(self.y0 - obj.y1), abs(self.y1 - obj.y0))
else:
return 0
class LTCurve(LTComponent):
"""A generic Bezier curve"""
def __init__(
self,
linewidth: float,
pts: List[Point],
stroke: bool = False,
fill: bool = False,
evenodd: bool = False,
stroking_color: Optional[Color] = None,
non_stroking_color: Optional[Color] = None,
) -> None:
LTComponent.__init__(self, get_bound(pts))
self.pts = pts
self.linewidth = linewidth
self.stroke = stroke
self.fill = fill
self.evenodd = evenodd
self.stroking_color = stroking_color
self.non_stroking_color = non_stroking_color
def get_pts(self) -> str:
return ",".join("%.3f,%.3f" % p for p in self.pts)
class LTLine(LTCurve):
"""A single straight line.
Could be used for separating text or figures.
"""
def __init__(
self,
linewidth: float,
p0: Point,
p1: Point,
stroke: bool = False,
fill: bool = False,
evenodd: bool = False,
stroking_color: Optional[Color] = None,
non_stroking_color: Optional[Color] = None,
) -> None:
LTCurve.__init__(
self,
linewidth,
[p0, p1],
stroke,
fill,
evenodd,
stroking_color,
non_stroking_color,
)
class LTRect(LTCurve):
"""A rectangle.
Could be used for framing another pictures or figures.
"""
def __init__(
self,
linewidth: float,
bbox: Rect,
stroke: bool = False,
fill: bool = False,
evenodd: bool = False,
stroking_color: Optional[Color] = None,
non_stroking_color: Optional[Color] = None,
) -> None:
(x0, y0, x1, y1) = bbox
LTCurve.__init__(
self,
linewidth,
[(x0, y0), (x1, y0), (x1, y1), (x0, y1)],
stroke,
fill,
evenodd,
stroking_color,
non_stroking_color,
)
class LTImage(LTComponent):
"""An image object.
Embedded images can be in JPEG, Bitmap or JBIG2.
"""
def __init__(self, name: str, stream: PDFStream, bbox: Rect) -> None:
LTComponent.__init__(self, bbox)
self.name = name
self.stream = stream
self.srcsize = (stream.get_any(("W", "Width")), stream.get_any(("H", "Height")))
self.imagemask = stream.get_any(("IM", "ImageMask"))
self.bits = stream.get_any(("BPC", "BitsPerComponent"), 1)
self.colorspace = stream.get_any(("CS", "ColorSpace"))
if not isinstance(self.colorspace, list):
self.colorspace = [self.colorspace]
def __repr__(self) -> str:
return "<%s(%s) %s %r>" % (
self.__class__.__name__,
self.name,
bbox2str(self.bbox),
self.srcsize,
)
class LTAnno(LTItem, LTText):
"""Actual letter in the text as a Unicode string.
Note that, while a LTChar object has actual boundaries, LTAnno objects does
not, as these are "virtual" characters, inserted by a layout analyzer
according to the relationship between two characters (e.g. a space).
"""
def __init__(self, text: str) -> None:
self._text = text
return
def get_text(self) -> str:
return self._text
class LTChar(LTComponent, LTText):
"""Actual letter in the text as a Unicode string."""
def __init__(
self,
matrix: Matrix,
font: PDFFont,
fontsize: float,
scaling: float,
rise: float,
text: str,
textwidth: float,
textdisp: Union[float, Tuple[Optional[float], float]],
ncs: PDFColorSpace,
graphicstate: PDFGraphicState,
) -> None:
LTText.__init__(self)
self._text = text
self.matrix = matrix
self.fontname = font.fontname
self.ncs = ncs
self.graphicstate = graphicstate
self.adv = textwidth * fontsize * scaling
# compute the boundary rectangle.
if font.is_vertical():
# vertical
assert isinstance(textdisp, tuple)
(vx, vy) = textdisp
if vx is None:
vx = fontsize * 0.5
else:
vx = vx * fontsize * 0.001
vy = (1000 - vy) * fontsize * 0.001
bbox_lower_left = (-vx, vy + rise + self.adv)
bbox_upper_right = (-vx + fontsize, vy + rise)
else:
# horizontal
descent = font.get_descent() * fontsize
bbox_lower_left = (0, descent + rise)
bbox_upper_right = (self.adv, descent + rise + fontsize)
(a, b, c, d, e, f) = self.matrix
self.upright = 0 < a * d * scaling and b * c <= 0
(x0, y0) = apply_matrix_pt(self.matrix, bbox_lower_left)
(x1, y1) = apply_matrix_pt(self.matrix, bbox_upper_right)
if x1 < x0:
(x0, x1) = (x1, x0)
if y1 < y0:
(y0, y1) = (y1, y0)
LTComponent.__init__(self, (x0, y0, x1, y1))
if font.is_vertical():
self.size = self.width
else:
self.size = self.height
return
def __repr__(self) -> str:
return "<%s %s matrix=%s font=%r adv=%s text=%r>" % (
self.__class__.__name__,
bbox2str(self.bbox),
matrix2str(self.matrix),
self.fontname,
self.adv,
self.get_text(),
)
def get_text(self) -> str:
return self._text
def is_compatible(self, obj: object) -> bool:
"""Returns True if two characters can coexist in the same line."""
return True
LTItemT = TypeVar("LTItemT", bound=LTItem)
class LTContainer(LTComponent, Generic[LTItemT]):
"""Object that can be extended and analyzed"""
def __init__(self, bbox: Rect) -> None:
LTComponent.__init__(self, bbox)
self._objs: List[LTItemT] = []
return
def __iter__(self) -> Iterator[LTItemT]:
return iter(self._objs)
def __len__(self) -> int:
return len(self._objs)
def add(self, obj: LTItemT) -> None:
self._objs.append(obj)
return
def extend(self, objs: Iterable[LTItemT]) -> None:
for obj in objs:
self.add(obj)
return
def analyze(self, laparams: LAParams) -> None:
for obj in self._objs:
obj.analyze(laparams)
return
class LTExpandableContainer(LTContainer[LTItemT]):
def __init__(self) -> None:
LTContainer.__init__(self, (+INF, +INF, -INF, -INF))
return
# Incompatible override: we take an LTComponent (with bounding box), but
# super() LTContainer only considers LTItem (no bounding box).
def add(self, obj: LTComponent) -> None: # type: ignore[override]
LTContainer.add(self, cast(LTItemT, obj))
self.set_bbox(
(
min(self.x0, obj.x0),
min(self.y0, obj.y0),
max(self.x1, obj.x1),
max(self.y1, obj.y1),
)
)
return
class LTTextContainer(LTExpandableContainer[LTItemT], LTText):
def __init__(self) -> None:
LTText.__init__(self)
LTExpandableContainer.__init__(self)
return
def get_text(self) -> str:
return "".join(
cast(LTText, obj).get_text() for obj in self if isinstance(obj, LTText)
)
TextLineElement = Union[LTChar, LTAnno]
class LTTextLine(LTTextContainer[TextLineElement]):
"""Contains a list of LTChar objects that represent a single text line.
The characters are aligned either horizontally or vertically, depending on
the text's writing mode.
"""
def __init__(self, word_margin: float) -> None:
super().__init__()
self.word_margin = word_margin
return
def __repr__(self) -> str:
return "<%s %s %r>" % (
self.__class__.__name__,
bbox2str(self.bbox),
self.get_text(),
)
def analyze(self, laparams: LAParams) -> None:
LTTextContainer.analyze(self, laparams)
LTContainer.add(self, LTAnno("\n"))
return
def find_neighbors(
self, plane: Plane[LTComponentT], ratio: float
) -> List["LTTextLine"]:
raise NotImplementedError
def is_empty(self) -> bool:
return super().is_empty() or self.get_text().isspace()
class LTTextLineHorizontal(LTTextLine):
def __init__(self, word_margin: float) -> None:
LTTextLine.__init__(self, word_margin)
self._x1: float = +INF
return
# Incompatible override: we take an LTComponent (with bounding box), but
# LTContainer only considers LTItem (no bounding box).
def add(self, obj: LTComponent) -> None: # type: ignore[override]
if isinstance(obj, LTChar) and self.word_margin:
margin = self.word_margin * max(obj.width, obj.height)
if self._x1 < obj.x0 - margin:
LTContainer.add(self, LTAnno(" "))
self._x1 = obj.x1
super().add(obj)
return
def find_neighbors(
self, plane: Plane[LTComponentT], ratio: float
) -> List[LTTextLine]:
"""
Finds neighboring LTTextLineHorizontals in the plane.
Returns a list of other LTTestLineHorizontals in the plane which are
close to self. "Close" can be controlled by ratio. The returned objects
will be the same height as self, and also either left-, right-, or
centrally-aligned.
"""
d = ratio * self.height
objs = plane.find((self.x0, self.y0 - d, self.x1, self.y1 + d))
return [
obj
for obj in objs
if (
isinstance(obj, LTTextLineHorizontal)
and self._is_same_height_as(obj, tolerance=d)
and (
self._is_left_aligned_with(obj, tolerance=d)
or self._is_right_aligned_with(obj, tolerance=d)
or self._is_centrally_aligned_with(obj, tolerance=d)
)
)
]
def _is_left_aligned_with(self, other: LTComponent, tolerance: float = 0) -> bool:
"""
Whether the left-hand edge of `other` is within `tolerance`.
"""
return abs(other.x0 - self.x0) <= tolerance
def _is_right_aligned_with(self, other: LTComponent, tolerance: float = 0) -> bool:
"""
Whether the right-hand edge of `other` is within `tolerance`.
"""
return abs(other.x1 - self.x1) <= tolerance
def _is_centrally_aligned_with(
self, other: LTComponent, tolerance: float = 0
) -> bool:
"""
Whether the horizontal center of `other` is within `tolerance`.
"""
return abs((other.x0 + other.x1) / 2 - (self.x0 + self.x1) / 2) <= tolerance
def _is_same_height_as(self, other: LTComponent, tolerance: float = 0) -> bool:
return abs(other.height - self.height) <= tolerance
class LTTextLineVertical(LTTextLine):
def __init__(self, word_margin: float) -> None:
LTTextLine.__init__(self, word_margin)
self._y0: float = -INF
return
# Incompatible override: we take an LTComponent (with bounding box), but
# LTContainer only considers LTItem (no bounding box).
def add(self, obj: LTComponent) -> None: # type: ignore[override]
if isinstance(obj, LTChar) and self.word_margin:
margin = self.word_margin * max(obj.width, obj.height)
if obj.y1 + margin < self._y0:
LTContainer.add(self, LTAnno(" "))
self._y0 = obj.y0
super().add(obj)
return
def find_neighbors(
self, plane: Plane[LTComponentT], ratio: float
) -> List[LTTextLine]:
"""
Finds neighboring LTTextLineVerticals in the plane.
Returns a list of other LTTextLineVerticals in the plane which are
close to self. "Close" can be controlled by ratio. The returned objects
will be the same width as self, and also either upper-, lower-, or
centrally-aligned.
"""
d = ratio * self.width
objs = plane.find((self.x0 - d, self.y0, self.x1 + d, self.y1))
return [
obj
for obj in objs
if (
isinstance(obj, LTTextLineVertical)
and self._is_same_width_as(obj, tolerance=d)
and (
self._is_lower_aligned_with(obj, tolerance=d)
or self._is_upper_aligned_with(obj, tolerance=d)
or self._is_centrally_aligned_with(obj, tolerance=d)
)
)
]
def _is_lower_aligned_with(self, other: LTComponent, tolerance: float = 0) -> bool:
"""
Whether the lower edge of `other` is within `tolerance`.
"""
return abs(other.y0 - self.y0) <= tolerance
def _is_upper_aligned_with(self, other: LTComponent, tolerance: float = 0) -> bool:
"""
Whether the upper edge of `other` is within `tolerance`.
"""
return abs(other.y1 - self.y1) <= tolerance
def _is_centrally_aligned_with(
self, other: LTComponent, tolerance: float = 0
) -> bool:
"""
Whether the vertical center of `other` is within `tolerance`.
"""
return abs((other.y0 + other.y1) / 2 - (self.y0 + self.y1) / 2) <= tolerance
def _is_same_width_as(self, other: LTComponent, tolerance: float) -> bool:
return abs(other.width - self.width) <= tolerance
class LTTextBox(LTTextContainer[LTTextLine]):
"""Represents a group of text chunks in a rectangular area.
Note that this box is created by geometric analysis and does not
necessarily represents a logical boundary of the text. It contains a list
of LTTextLine objects.
"""
def __init__(self) -> None:
LTTextContainer.__init__(self)
self.index: int = -1
return
def __repr__(self) -> str:
return "<%s(%s) %s %r>" % (
self.__class__.__name__,
self.index,
bbox2str(self.bbox),
self.get_text(),
)
def get_writing_mode(self) -> str:
raise NotImplementedError
class LTTextBoxHorizontal(LTTextBox):
def analyze(self, laparams: LAParams) -> None:
super().analyze(laparams)
self._objs.sort(key=lambda obj: -obj.y1)
return
def get_writing_mode(self) -> str:
return "lr-tb"
class LTTextBoxVertical(LTTextBox):
def analyze(self, laparams: LAParams) -> None:
super().analyze(laparams)
self._objs.sort(key=lambda obj: -obj.x1)
return
def get_writing_mode(self) -> str:
return "tb-rl"
TextGroupElement = Union[LTTextBox, "LTTextGroup"]
class LTTextGroup(LTTextContainer[TextGroupElement]):
def __init__(self, objs: Iterable[TextGroupElement]) -> None:
super().__init__()
self.extend(objs)
return
class LTTextGroupLRTB(LTTextGroup):
def analyze(self, laparams: LAParams) -> None:
super().analyze(laparams)
assert laparams.boxes_flow is not None
boxes_flow = laparams.boxes_flow
# reorder the objects from top-left to bottom-right.
self._objs.sort(
key=lambda obj: (1 - boxes_flow) * obj.x0
- (1 + boxes_flow) * (obj.y0 + obj.y1)
)
return
class LTTextGroupTBRL(LTTextGroup):
def analyze(self, laparams: LAParams) -> None:
super().analyze(laparams)
assert laparams.boxes_flow is not None
boxes_flow = laparams.boxes_flow
# reorder the objects from top-right to bottom-left.
self._objs.sort(
key=lambda obj: -(1 + boxes_flow) * (obj.x0 + obj.x1)
- (1 - boxes_flow) * obj.y1
)
return
class LTLayoutContainer(LTContainer[LTComponent]):
def __init__(self, bbox: Rect) -> None:
LTContainer.__init__(self, bbox)
self.groups: Optional[List[LTTextGroup]] = None
return
# group_objects: group text object to textlines.
def group_objects(
self, laparams: LAParams, objs: Iterable[LTComponent]
) -> Iterator[LTTextLine]:
obj0 = None
line = None
for obj1 in objs:
if obj0 is not None:
# halign: obj0 and obj1 is horizontally aligned.
#
# +------+ - - -
# | obj0 | - - +------+ -
# | | | obj1 | | (line_overlap)
# +------+ - - | | -
# - - - +------+
#
# |<--->|
# (char_margin)
halign = (
obj0.is_compatible(obj1)
and obj0.is_voverlap(obj1)
and min(obj0.height, obj1.height) * laparams.line_overlap
< obj0.voverlap(obj1)
and obj0.hdistance(obj1)
< max(obj0.width, obj1.width) * laparams.char_margin
)
# valign: obj0 and obj1 is vertically aligned.
#
# +------+
# | obj0 |
# | |
# +------+ - - -
# | | | (char_margin)
# +------+ - -
# | obj1 |
# | |
# +------+
#
# |<-->|
# (line_overlap)
valign = (
laparams.detect_vertical
and obj0.is_compatible(obj1)
and obj0.is_hoverlap(obj1)
and min(obj0.width, obj1.width) * laparams.line_overlap
< obj0.hoverlap(obj1)
and obj0.vdistance(obj1)
< max(obj0.height, obj1.height) * laparams.char_margin
)
if (halign and isinstance(line, LTTextLineHorizontal)) or (
valign and isinstance(line, LTTextLineVertical)
):
line.add(obj1)
elif line is not None:
yield line
line = None
else:
if valign and not halign:
line = LTTextLineVertical(laparams.word_margin)
line.add(obj0)
line.add(obj1)
elif halign and not valign:
line = LTTextLineHorizontal(laparams.word_margin)
line.add(obj0)
line.add(obj1)
else:
line = LTTextLineHorizontal(laparams.word_margin)
line.add(obj0)
yield line
line = None
obj0 = obj1
if line is None:
line = LTTextLineHorizontal(laparams.word_margin)
assert obj0 is not None
line.add(obj0)
yield line
return
def group_textlines(
self, laparams: LAParams, lines: Iterable[LTTextLine]
) -> Iterator[LTTextBox]:
"""Group neighboring lines to textboxes"""
plane: Plane[LTTextLine] = Plane(self.bbox)
plane.extend(lines)
boxes: Dict[LTTextLine, LTTextBox] = {}
for line in lines:
neighbors = line.find_neighbors(plane, laparams.line_margin)
members = [line]
for obj1 in neighbors:
members.append(obj1)
if obj1 in boxes:
members.extend(boxes.pop(obj1))
if isinstance(line, LTTextLineHorizontal):
box: LTTextBox = LTTextBoxHorizontal()
else:
box = LTTextBoxVertical()
for obj in uniq(members):
box.add(obj)
boxes[obj] = box
done = set()
for line in lines:
if line not in boxes:
continue
box = boxes[line]
if box in done:
continue
done.add(box)
if not box.is_empty():
yield box
return
def group_textboxes(
self, laparams: LAParams, boxes: Sequence[LTTextBox]
) -> List[LTTextGroup]:
"""Group textboxes hierarchically.
Get pair-wise distances, via dist func defined below, and then merge
from the closest textbox pair. Once obj1 and obj2 are merged /
grouped, the resulting group is considered as a new object, and its
distances to other objects & groups are added to the process queue.
For performance reason, pair-wise distances and object pair info are
maintained in a heap of (idx, dist, id(obj1), id(obj2), obj1, obj2)
tuples. It ensures quick access to the smallest element. Note that
since comparison operators, e.g., __lt__, are disabled for
LTComponent, id(obj) has to appear before obj in element tuples.
:param laparams: LAParams object.
:param boxes: All textbox objects to be grouped.
:return: a list that has only one element, the final top level group.
"""
ElementT = Union[LTTextBox, LTTextGroup]
plane: Plane[ElementT] = Plane(self.bbox)
def dist(obj1: LTComponent, obj2: LTComponent) -> float:
"""A distance function between two TextBoxes.
Consider the bounding rectangle for obj1 and obj2.
Return its area less the areas of obj1 and obj2,
shown as 'www' below. This value may be negative.
+------+..........+ (x1, y1)
| obj1 |wwwwwwwwww:
+------+www+------+
:wwwwwwwwww| obj2 |
(x0, y0) +..........+------+
"""
x0 = min(obj1.x0, obj2.x0)
y0 = min(obj1.y0, obj2.y0)
x1 = max(obj1.x1, obj2.x1)
y1 = max(obj1.y1, obj2.y1)
return (
(x1 - x0) * (y1 - y0)
- obj1.width * obj1.height
- obj2.width * obj2.height
)
def isany(obj1: ElementT, obj2: ElementT) -> Set[ElementT]:
"""Check if there's any other object between obj1 and obj2."""
x0 = min(obj1.x0, obj2.x0)
y0 = min(obj1.y0, obj2.y0)
x1 = max(obj1.x1, obj2.x1)
y1 = max(obj1.y1, obj2.y1)
objs = set(plane.find((x0, y0, x1, y1)))
return objs.difference((obj1, obj2))
dists: List[Tuple[bool, float, int, int, ElementT, ElementT]] = []
for i in range(len(boxes)):
box1 = boxes[i]
for j in range(i + 1, len(boxes)):
box2 = boxes[j]
dists.append((False, dist(box1, box2), id(box1), id(box2), box1, box2))
heapq.heapify(dists)
plane.extend(boxes)
done = set()
while len(dists) > 0:
(skip_isany, d, id1, id2, obj1, obj2) = heapq.heappop(dists)
# Skip objects that are already merged
if (id1 not in done) and (id2 not in done):
if not skip_isany and isany(obj1, obj2):
heapq.heappush(dists, (True, d, id1, id2, obj1, obj2))
continue
if isinstance(obj1, (LTTextBoxVertical, LTTextGroupTBRL)) or isinstance(
obj2, (LTTextBoxVertical, LTTextGroupTBRL)
):
group: LTTextGroup = LTTextGroupTBRL([obj1, obj2])
else:
group = LTTextGroupLRTB([obj1, obj2])
plane.remove(obj1)
plane.remove(obj2)
done.update([id1, id2])
for other in plane:
heapq.heappush(
dists,
(False, dist(group, other), id(group), id(other), group, other),
)
plane.add(group)
# By now only groups are in the plane
return list(cast(LTTextGroup, g) for g in plane)
def analyze(self, laparams: LAParams) -> None:
# textobjs is a list of LTChar objects, i.e.
# it has all the individual characters in the page.
(textobjs, otherobjs) = fsplit(lambda obj: isinstance(obj, LTChar), self)
for obj in otherobjs:
obj.analyze(laparams)
if not textobjs:
return
textlines = list(self.group_objects(laparams, textobjs))
(empties, textlines) = fsplit(lambda obj: obj.is_empty(), textlines)
for obj in empties:
obj.analyze(laparams)
textboxes = list(self.group_textlines(laparams, textlines))
if laparams.boxes_flow is None:
for textbox in textboxes:
textbox.analyze(laparams)
def getkey(box: LTTextBox) -> Tuple[int, float, float]:
if isinstance(box, LTTextBoxVertical):
return (0, -box.x1, -box.y0)
else:
return (1, -box.y0, box.x0)
textboxes.sort(key=getkey)
else:
self.groups = self.group_textboxes(laparams, textboxes)
assigner = IndexAssigner()
for group in self.groups:
group.analyze(laparams)
assigner.run(group)
textboxes.sort(key=lambda box: box.index)
self._objs = (
cast(List[LTComponent], textboxes)
+ otherobjs
+ cast(List[LTComponent], empties)
)
return
class LTFigure(LTLayoutContainer):
"""Represents an area used by PDF Form objects.
PDF Forms can be used to present figures or pictures by embedding yet
another PDF document within a page. Note that LTFigure objects can appear
recursively.
"""
def __init__(self, name: str, bbox: Rect, matrix: Matrix) -> None:
self.name = name
self.matrix = matrix
(x, y, w, h) = bbox
bounds = ((x, y), (x + w, y), (x, y + h), (x + w, y + h))
bbox = get_bound(apply_matrix_pt(matrix, (p, q)) for (p, q) in bounds)
LTLayoutContainer.__init__(self, bbox)
return
def __repr__(self) -> str:
return "<%s(%s) %s matrix=%s>" % (
self.__class__.__name__,
self.name,
bbox2str(self.bbox),
matrix2str(self.matrix),
)
def analyze(self, laparams: LAParams) -> None:
if not laparams.all_texts:
return
LTLayoutContainer.analyze(self, laparams)
return
class LTPage(LTLayoutContainer):
"""Represents an entire page.
May contain child objects like LTTextBox, LTFigure, LTImage, LTRect,
LTCurve and LTLine.
"""
def __init__(self, pageid: int, bbox: Rect, rotate: float = 0) -> None:
LTLayoutContainer.__init__(self, bbox)
self.pageid = pageid
self.rotate = rotate
return
def __repr__(self) -> str:
return "<%s(%r) %s rotate=%r>" % (
self.__class__.__name__,
self.pageid,
bbox2str(self.bbox),
self.rotate,
)
|
20220429-pdfminer-jameslp310
|
/20220429_pdfminer_jameslp310-0.0.2-py3-none-any.whl/pdfminer/layout.py
|
layout.py
|
""" Standard encoding tables used in PDF.
This table is extracted from PDF Reference Manual 1.6, pp.925
"D.1 Latin Character Set and Encodings"
"""
from typing import List, Optional, Tuple
EncodingRow = Tuple[str, Optional[int], Optional[int], Optional[int], Optional[int]]
ENCODING: List[EncodingRow] = [
# (name, std, mac, win, pdf)
("A", 65, 65, 65, 65),
("AE", 225, 174, 198, 198),
("Aacute", None, 231, 193, 193),
("Acircumflex", None, 229, 194, 194),
("Adieresis", None, 128, 196, 196),
("Agrave", None, 203, 192, 192),
("Aring", None, 129, 197, 197),
("Atilde", None, 204, 195, 195),
("B", 66, 66, 66, 66),
("C", 67, 67, 67, 67),
("Ccedilla", None, 130, 199, 199),
("D", 68, 68, 68, 68),
("E", 69, 69, 69, 69),
("Eacute", None, 131, 201, 201),
("Ecircumflex", None, 230, 202, 202),
("Edieresis", None, 232, 203, 203),
("Egrave", None, 233, 200, 200),
("Eth", None, None, 208, 208),
("Euro", None, None, 128, 160),
("F", 70, 70, 70, 70),
("G", 71, 71, 71, 71),
("H", 72, 72, 72, 72),
("I", 73, 73, 73, 73),
("Iacute", None, 234, 205, 205),
("Icircumflex", None, 235, 206, 206),
("Idieresis", None, 236, 207, 207),
("Igrave", None, 237, 204, 204),
("J", 74, 74, 74, 74),
("K", 75, 75, 75, 75),
("L", 76, 76, 76, 76),
("Lslash", 232, None, None, 149),
("M", 77, 77, 77, 77),
("N", 78, 78, 78, 78),
("Ntilde", None, 132, 209, 209),
("O", 79, 79, 79, 79),
("OE", 234, 206, 140, 150),
("Oacute", None, 238, 211, 211),
("Ocircumflex", None, 239, 212, 212),
("Odieresis", None, 133, 214, 214),
("Ograve", None, 241, 210, 210),
("Oslash", 233, 175, 216, 216),
("Otilde", None, 205, 213, 213),
("P", 80, 80, 80, 80),
("Q", 81, 81, 81, 81),
("R", 82, 82, 82, 82),
("S", 83, 83, 83, 83),
("Scaron", None, None, 138, 151),
("T", 84, 84, 84, 84),
("Thorn", None, None, 222, 222),
("U", 85, 85, 85, 85),
("Uacute", None, 242, 218, 218),
("Ucircumflex", None, 243, 219, 219),
("Udieresis", None, 134, 220, 220),
("Ugrave", None, 244, 217, 217),
("V", 86, 86, 86, 86),
("W", 87, 87, 87, 87),
("X", 88, 88, 88, 88),
("Y", 89, 89, 89, 89),
("Yacute", None, None, 221, 221),
("Ydieresis", None, 217, 159, 152),
("Z", 90, 90, 90, 90),
("Zcaron", None, None, 142, 153),
("a", 97, 97, 97, 97),
("aacute", None, 135, 225, 225),
("acircumflex", None, 137, 226, 226),
("acute", 194, 171, 180, 180),
("adieresis", None, 138, 228, 228),
("ae", 241, 190, 230, 230),
("agrave", None, 136, 224, 224),
("ampersand", 38, 38, 38, 38),
("aring", None, 140, 229, 229),
("asciicircum", 94, 94, 94, 94),
("asciitilde", 126, 126, 126, 126),
("asterisk", 42, 42, 42, 42),
("at", 64, 64, 64, 64),
("atilde", None, 139, 227, 227),
("b", 98, 98, 98, 98),
("backslash", 92, 92, 92, 92),
("bar", 124, 124, 124, 124),
("braceleft", 123, 123, 123, 123),
("braceright", 125, 125, 125, 125),
("bracketleft", 91, 91, 91, 91),
("bracketright", 93, 93, 93, 93),
("breve", 198, 249, None, 24),
("brokenbar", None, None, 166, 166),
("bullet", 183, 165, 149, 128),
("c", 99, 99, 99, 99),
("caron", 207, 255, None, 25),
("ccedilla", None, 141, 231, 231),
("cedilla", 203, 252, 184, 184),
("cent", 162, 162, 162, 162),
("circumflex", 195, 246, 136, 26),
("colon", 58, 58, 58, 58),
("comma", 44, 44, 44, 44),
("copyright", None, 169, 169, 169),
("currency", 168, 219, 164, 164),
("d", 100, 100, 100, 100),
("dagger", 178, 160, 134, 129),
("daggerdbl", 179, 224, 135, 130),
("degree", None, 161, 176, 176),
("dieresis", 200, 172, 168, 168),
("divide", None, 214, 247, 247),
("dollar", 36, 36, 36, 36),
("dotaccent", 199, 250, None, 27),
("dotlessi", 245, 245, None, 154),
("e", 101, 101, 101, 101),
("eacute", None, 142, 233, 233),
("ecircumflex", None, 144, 234, 234),
("edieresis", None, 145, 235, 235),
("egrave", None, 143, 232, 232),
("eight", 56, 56, 56, 56),
("ellipsis", 188, 201, 133, 131),
("emdash", 208, 209, 151, 132),
("endash", 177, 208, 150, 133),
("equal", 61, 61, 61, 61),
("eth", None, None, 240, 240),
("exclam", 33, 33, 33, 33),
("exclamdown", 161, 193, 161, 161),
("f", 102, 102, 102, 102),
("fi", 174, 222, None, 147),
("five", 53, 53, 53, 53),
("fl", 175, 223, None, 148),
("florin", 166, 196, 131, 134),
("four", 52, 52, 52, 52),
("fraction", 164, 218, None, 135),
("g", 103, 103, 103, 103),
("germandbls", 251, 167, 223, 223),
("grave", 193, 96, 96, 96),
("greater", 62, 62, 62, 62),
("guillemotleft", 171, 199, 171, 171),
("guillemotright", 187, 200, 187, 187),
("guilsinglleft", 172, 220, 139, 136),
("guilsinglright", 173, 221, 155, 137),
("h", 104, 104, 104, 104),
("hungarumlaut", 205, 253, None, 28),
("hyphen", 45, 45, 45, 45),
("i", 105, 105, 105, 105),
("iacute", None, 146, 237, 237),
("icircumflex", None, 148, 238, 238),
("idieresis", None, 149, 239, 239),
("igrave", None, 147, 236, 236),
("j", 106, 106, 106, 106),
("k", 107, 107, 107, 107),
("l", 108, 108, 108, 108),
("less", 60, 60, 60, 60),
("logicalnot", None, 194, 172, 172),
("lslash", 248, None, None, 155),
("m", 109, 109, 109, 109),
("macron", 197, 248, 175, 175),
("minus", None, None, None, 138),
("mu", None, 181, 181, 181),
("multiply", None, None, 215, 215),
("n", 110, 110, 110, 110),
("nbspace", None, 202, 160, None),
("nine", 57, 57, 57, 57),
("ntilde", None, 150, 241, 241),
("numbersign", 35, 35, 35, 35),
("o", 111, 111, 111, 111),
("oacute", None, 151, 243, 243),
("ocircumflex", None, 153, 244, 244),
("odieresis", None, 154, 246, 246),
("oe", 250, 207, 156, 156),
("ogonek", 206, 254, None, 29),
("ograve", None, 152, 242, 242),
("one", 49, 49, 49, 49),
("onehalf", None, None, 189, 189),
("onequarter", None, None, 188, 188),
("onesuperior", None, None, 185, 185),
("ordfeminine", 227, 187, 170, 170),
("ordmasculine", 235, 188, 186, 186),
("oslash", 249, 191, 248, 248),
("otilde", None, 155, 245, 245),
("p", 112, 112, 112, 112),
("paragraph", 182, 166, 182, 182),
("parenleft", 40, 40, 40, 40),
("parenright", 41, 41, 41, 41),
("percent", 37, 37, 37, 37),
("period", 46, 46, 46, 46),
("periodcentered", 180, 225, 183, 183),
("perthousand", 189, 228, 137, 139),
("plus", 43, 43, 43, 43),
("plusminus", None, 177, 177, 177),
("q", 113, 113, 113, 113),
("question", 63, 63, 63, 63),
("questiondown", 191, 192, 191, 191),
("quotedbl", 34, 34, 34, 34),
("quotedblbase", 185, 227, 132, 140),
("quotedblleft", 170, 210, 147, 141),
("quotedblright", 186, 211, 148, 142),
("quoteleft", 96, 212, 145, 143),
("quoteright", 39, 213, 146, 144),
("quotesinglbase", 184, 226, 130, 145),
("quotesingle", 169, 39, 39, 39),
("r", 114, 114, 114, 114),
("registered", None, 168, 174, 174),
("ring", 202, 251, None, 30),
("s", 115, 115, 115, 115),
("scaron", None, None, 154, 157),
("section", 167, 164, 167, 167),
("semicolon", 59, 59, 59, 59),
("seven", 55, 55, 55, 55),
("six", 54, 54, 54, 54),
("slash", 47, 47, 47, 47),
("space", 32, 32, 32, 32),
("space", None, 202, 160, None),
("space", None, 202, 173, None),
("sterling", 163, 163, 163, 163),
("t", 116, 116, 116, 116),
("thorn", None, None, 254, 254),
("three", 51, 51, 51, 51),
("threequarters", None, None, 190, 190),
("threesuperior", None, None, 179, 179),
("tilde", 196, 247, 152, 31),
("trademark", None, 170, 153, 146),
("two", 50, 50, 50, 50),
("twosuperior", None, None, 178, 178),
("u", 117, 117, 117, 117),
("uacute", None, 156, 250, 250),
("ucircumflex", None, 158, 251, 251),
("udieresis", None, 159, 252, 252),
("ugrave", None, 157, 249, 249),
("underscore", 95, 95, 95, 95),
("v", 118, 118, 118, 118),
("w", 119, 119, 119, 119),
("x", 120, 120, 120, 120),
("y", 121, 121, 121, 121),
("yacute", None, None, 253, 253),
("ydieresis", None, 216, 255, 255),
("yen", 165, 180, 165, 165),
("z", 122, 122, 122, 122),
("zcaron", None, None, 158, 158),
("zero", 48, 48, 48, 48),
]
|
20220429-pdfminer-jameslp310
|
/20220429_pdfminer_jameslp310-0.0.2-py3-none-any.whl/pdfminer/latin_enc.py
|
latin_enc.py
|
hello it is just a test
|
20221206.1408
|
/20221206.1408-1.0.tar.gz/20221206.1408-1.0/README.md
|
README.md
|
from setuptools import setup, find_packages
setup(
name='20221206.1408', # 包名
version='1.0', # 版本
description="Mark the eyes of specific people", # 包简介
long_description=open('README.md').read(), # 读取文件中介绍包的详细内容
include_package_data=True, # 是否允许上传资源文件
author='ShangCeXie', # 作者
author_email='[email protected]', # 作者邮件
maintainer='ShangCeXie', # 维护者
maintainer_email='[email protected]', # 维护者邮件
license='MIT License', # 协议
url='', # github或者自己的网站地址
packages=find_packages('eyes_recognition_module'), # 包的目录
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3', # 设置编写时的python版本
],
python_requires='>=3.6', # 设置python版本要求
install_requires=[''], # 安装所需要的库
)
|
20221206.1408
|
/20221206.1408-1.0.tar.gz/20221206.1408-1.0/setup.py
|
setup.py
|
hello it is just a test
|
20221206.1418
|
/20221206.1418-3.0.tar.gz/20221206.1418-3.0/README.md
|
README.md
|
from setuptools import setup, find_packages
setup(
name='20221206.1418', # 包名
version='3.0', # 版本
description="Mark the eyes of specific people", # 包简介
long_description=open('README.md').read(), # 读取文件中介绍包的详细内容
include_package_data=True, # 是否允许上传资源文件
author='ShangCeXie', # 作者
author_email='[email protected]', # 作者邮件
maintainer='ShangCeXie', # 维护者
maintainer_email='[email protected]', # 维护者邮件
license='MIT License', # 协议
url='', # github或者自己的网站地址
packages=find_packages(), # 包的目录
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3', # 设置编写时的python版本
],
python_requires='>=3.6', # 设置python版本要求
install_requires=[''], # 安装所需要的库
)
|
20221206.1418
|
/20221206.1418-3.0.tar.gz/20221206.1418-3.0/setup.py
|
setup.py
|
import face_recognition
import pickle
import cv2
import imutils
from imutils import paths
import os
known_faces_encodings = {}
def encode_faces(imagePathsStr, database="database.pickle", detection_method="cnn"):
print("[INFO] quantifying faces...")
imagePaths = list(paths.list_images(imagePathsStr))
knownEncodings = []
knownNames = []
for (i, imagePath) in enumerate(imagePaths):
# extract the person name from the image path
print("[INFO] processing image {}/{}".format(i + 1, len(imagePaths)))
name = imagePath.split(os.path.sep)[-2]
# load the input image and convert it from BGR (OpenCV ordering)
# to dlib ordering (RGB)
image = cv2.imread(imagePath)
w = image.shape[1]
h = image.shape[0]
print("picture sizes {},{}".format(w, h))
# 图片太大会很耗时
if w > 2000:
image = cv2.resize(image, (0, 0), fx=0.5, fy=0.5)
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# detect the (x, y)-coordinates of the bounding boxes
# corresponding to each face in the input image
boxes = face_recognition.face_locations(rgb, model=detection_method)
# compute the facial embedding for the face
encodings = face_recognition.face_encodings(rgb, boxes)
# loop over the encodings
for encoding in encodings:
# add each encoding + name to our set of known names and
# encodings
knownEncodings.append(encoding)
knownNames.append(name)
# dump the facial encodings + names to disk
print("[INFO] serializing encodings...")
data = {"encodings": knownEncodings, "names": knownNames}
f = open(database, "wb")
f.write(pickle.dumps(data))
def load_encode(encodings="database.pickle"):
global known_faces_encodings
known_faces_encodings = pickle.loads(open(encodings, "rb").read())
def recognize_faces_image(frame, detection_method="cnn", toleranceval=0.40, display=1):
global known_faces_encodings
w = frame.shape[1]
h = frame.shape[0]
#print("picture sizes{},{}".format(w, h))
if w > 720:
small_frame = imutils.resize(frame, width=720)
r = frame.shape[1] / float(small_frame.shape[1])
else:
small_frame = frame
r = 1
rgb = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
#print("[INFO] recognizing faces...")
boxes = face_recognition.face_locations(rgb, model=detection_method)
encodings = face_recognition.face_encodings(rgb, boxes)
# initialize the list of names for each face detected
names = []
# loop over the facial embedding
for encoding in encodings:
# attempt to match each face in the input image to our known
# encodings
matches = face_recognition.compare_faces(known_faces_encodings["encodings"], encoding, tolerance=toleranceval)
name = "Unknown"
# check to see if we have found a match
if True in matches:
# find the indexes of all matched faces then initialize a
# dictionary to count the total number of times each face
# was matched
matchedIdxs = [i for (i, b) in enumerate(matches) if b]
counts = {}
# loop over the matched indexes and maintain a count for
# each recognized face face
for i in matchedIdxs:
name = known_faces_encodings["names"][i]
counts[name] = counts.get(name, 0) + 1
# determine the recognized face with the largest number of
# votes (note: in the event of an unlikely tie Python will
# select first entry in the dictionary)
name = max(counts, key=counts.get)
# update the list of names
names.append(name)
# loop over the recognized faces
face_num = 0
name_list = []
eyes_point_list = []
for ((top, right, bottom, left), name) in zip(boxes, names):
# rescale the face coordinates
if name != "Unknown":
face_num = face_num + 1
name_list.append(name)
top = int(top * r)
right = int(right * r)
bottom = int(bottom * r)
left = int(left * r)
crop_img = frame[top:bottom, left:right]
face_landmarks_list = face_recognition.face_landmarks(crop_img)
# draw the predicted face name on the image
cv2.rectangle(frame, (left, top), (right, bottom),
(0, 255, 0), 2)
y = top - 15 if top - 15 > 15 else top + 15
cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,
0.65, (0, 255, 0), 1)
for face_landmarks in face_landmarks_list:
left_eye_real_x = face_landmarks['left_eye'][0][0] + left
left_eye_real_y = face_landmarks['left_eye'][0][1] + top
right_eye_real_x = face_landmarks['right_eye'][3][0] + left
right_eye_real_y = face_landmarks['right_eye'][3][1] + top
eyes_point_list.append([(left_eye_real_x,left_eye_real_y),(right_eye_real_x,right_eye_real_y)])
if display > 0:
cv2.line(frame, (left_eye_real_x,left_eye_real_y),(right_eye_real_x,right_eye_real_y),(0, 0, 255), 2)
if display > 0:
cv2.imshow("Frame", frame)
return face_num, name_list, eyes_point_list
|
20221206.1418
|
/20221206.1418-3.0.tar.gz/20221206.1418-3.0/eyes_recognition_module/face_eyes_recognition_ops.py
|
face_eyes_recognition_ops.py
|
# -*- coding: utf-8 -*-
__author__ = "xieshangce"
__email__ = '[email protected]'
__version__ = 'v2.0'
from .face_eyes_recognition_ops import encode_faces, load_encode, recognize_faces_image
|
20221206.1418
|
/20221206.1418-3.0.tar.gz/20221206.1418-3.0/eyes_recognition_module/__init__.py
|
__init__.py
|
# 2048-Wallpaper-Edition
2048 is a puzzle game that can be played right on your desktop background! Move the tiles around to create a tile with the value of 2048. Keep playing to see how high you can go.
|
2048-Wallpaper-Edition
|
/2048-Wallpaper-Edition-1.0.0.tar.gz/2048-Wallpaper-Edition-1.0.0/README.md
|
README.md
|
from setuptools import setup, find_packages
setup(
name='2048-Wallpaper-Edition',
version='1.0.0',
packages=find_packages(),
install_requires=[
'Pillow==8.4.0',
'keyboard==0.13.5',
],
entry_points={
'console_scripts': [
'2048-Wallpaper-Edition = 2048.2048:main',
],
},
)
|
2048-Wallpaper-Edition
|
/2048-Wallpaper-Edition-1.0.0.tar.gz/2048-Wallpaper-Edition-1.0.0/setup.py
|
setup.py
|
#!/usr/bin/python3
logo = '''
___ ____ __ __ ____
|__ \ / __ \/ // / ( __ )
__/ // / / / // /_/ __ |
/ __// /_/ /__ __/ /_/ /
/____/\____/ /_/ \____/
'''
# Imports
import os
import sys
import random
import termcolor
#INDENTATION ------> TABS <----------
'''
TODO:
- Implement moves
- We have a reference implementation
- You can also fix/write your own
- Replace merge_direction in do_move() with merge_direction_alt
- Fix check_lost()
- Add an undo button
- Different colors for tiles instead of repeating?
- Play the game to find bugs!
- Add restart keys
- Add help menu
- Detect when you win and get 2048
- High scores using Repl.it Database?
or JSON(possibly easier(just file writing))
can't use JSON because we don't have access to an actual file system
can use JSON because repl can write and save to a file(try it)
'''
# Global variables
rows = 4
cols = 4
board = [[0]*cols for i in range(rows)] # Initialize an array of size rows x cols with zeroes
#[[0]*cols]*rows does not work, all rows have same pointer
lost = False
score = 0
# spawn a random tile
# can be rewritten to be more efficient
def spawn_random():
done = False
while not done:
i = random.randint(0, rows-1)
j = random.randint(0, cols-1)
# check if block occupied
if board[i][j] == 0:
# spawn 2 with 90% probability
if random.randint(0, 9) < 9:
board[i][j] = 2
# and 4 with 10%
else:
board[i][j] = 4
done = True
# get the board ready
def prepare_board():
global board
board = [[0]*cols for i in range(rows)]
# spawn two random tiles for starting board
spawn_random()
spawn_random()
# color of each tile
def get_color(x):
if x == 2:
return "on_red"
elif x == 4:
return "on_green"
elif x == 8:
return "on_yellow"
elif x == 16:
return "on_blue"
elif x == 32:
return "on_magenta"
elif x == 64:
return "on_cyan"
elif x == 128:
return "on_red"
elif x == 256:
return "on_green"
elif x == 512:
return "on_yellow"
elif x == 1024:
return "on_blue"
elif x == 2048:
return "on_magenta"
else: # you're too good
return "on_cyan"
# Print the board
def print_board():
print(logo)
print("BY LADUE HS CS CLUB" + ("SCORE: " + str(score) + '\n').rjust(15))
for i in range(0, rows):
print("-", end='')
for j in range(0, cols):
print("--------", end='')
print()
print("|", end='')
for j in range(0, cols):
if (board[i][j] > 0):
print(termcolor.colored(" ", "grey", get_color(board[i][j])), end='|')
else:
print(" ", end='|')
print()
print("|", end='')
for j in range(0, cols):
if (board[i][j] > 0):
print(termcolor.colored(str(board[i][j]).center(7), "grey", get_color(board[i][j])), end='|')
else:
print(" ", end='|')
print()
print("|", end='')
for j in range(0, cols):
if (board[i][j] > 0):
print(termcolor.colored(" ", "grey", get_color(board[i][j])), end='|')
else:
print(" ", end='|')
print()
print("-", end='')
for j in range(0, cols):
print("--------", end='')
print('\n')
print("CONTROLS: W ")
print(" A S D")
def merge_up():
global score, board
for i in range(0, cols):
l = [] # list to store all nonzero tiles
for j in range(0, rows):
if board[j][i] > 0:
# last tile is the same as current, then merge
if len(l) > 0 and board[j][i] == l[-1]:
l.pop()
l.append(-2*board[j][i])
score += 2*board[j][i]
else:
l.append(board[j][i])
board[j][i] = 0 # clear cell
# refill with list l
for j in range(0, len(l)):
board[j][i] = abs(l[j])
def merge_up_alt():
global score, board
for i in range(0, rows):
for j in range(0, cols):
if board[i][j] != 0:
current = board[i][j]
for k in range(i - 1, -1, -1):
if k == 0 and board[0][j] == 0:
board[0][j] = current
board[i][j] = 0
break
elif k == 0 and board[0][j] == current:
board[0][j] = current * 2
board[i][j] = 0
break
elif board[k][j] == current:
board[k][j] = current * 2
board[i][j] = 0
break
else:
board[k + 1][j] = current
board[i][j] = 0
break
# print(c)
#[[board[rows-1-j][i] for j in range(rows)]for i in range(cols)] counterclockwise
#[[board[j][cols-1-i] for j in range(4)]for i in range(4)] clockwise
def merge_left():
global score, board
for i in range(0, rows):
l = [] # list to store all nonzero tiles
for j in range(0, cols):
if board[i][j] > 0:
# last tile is the same as current, then merge
if len(l) > 0 and board[i][j] == l[-1]:
l.pop()
l.append(-2*board[i][j])
score += 2*board[i][j]
else:
l.append(board[i][j])
board[i][j] = 0 # clear cell
# refill with list l
for j in range(0, len(l)):
board[i][j] = abs(l[j])
def merge_left_alt():
# left working [2,2,2,0]=>[4,2,0,0], [2,2,2,2]=>[4,4,0,0]
global score, board
for i in range(0, rows):
for j in range(0, cols-1):
for k in range(j+1, cols):
if board[i][j]==0 or board[i][k]==0:
continue
if board[i][j]==board[i][k]:
board[i][j]*=2
board[i][k]=0
score+=board[i][j]
else:
break
#collapse left [4,0,4,0]=>[4,4,0,0]
board[i]=[j for j in board[i] if j]+[0]*board[i].count(0)
def merge_down():
global score, board
for i in range(0, cols):
l = [] # list to store all nonzero tiles
for j in reversed(range(0, rows)):
if board[j][i] > 0:
# last tile is the same as current, then merge
if len(l) > 0 and board[j][i] == l[-1]:
l.pop()
l.append(-2*board[j][i])
score += 2*board[j][i]
else:
l.append(board[j][i])
board[j][i] = 0 # clear cell
# refill with list l
for j in range(0, len(l)):
board[rows-j-1][i] = abs(l[j])
def merge_down_alt():
global score, board
# down
#initialize board - switch rows and columns
columns = [[0]*cols for i in range(rows)]
for i in range(0, rows):
for j in range(0, cols):
columns[i][cols-j] = board[j][i]
#now you can treat as if 1 column is a 1d array in columns[][]shifting/merging to the left
#collapse:
for i in range(0, columns):
if (columns[i].contains(0)):
count = columns[i].count(0)
columns[i].remove(0)
for j in range(0,count):
columns[i].append(0)
#merge Process
for i in range(0,cols):
for j in range(0,cols-1):
if(columns[i][j] == columns[i][j+1] and columns[i][j]!=0):
columns[i][j]*=2
columns[i].pop(j+1)
columns[i].append(0)
j+=2
#put back into board
for i in range(0, rows):
for j in range(0, cols):
board[j][i] = columns[i][cols-j]
def merge_right():
global score, board
for i in range(0, rows):
l = [] # list to store all nonzero tiles
for j in reversed(range(0, cols)):
if board[i][j] > 0:
# last tile is the same as current, then merge
if len(l) > 0 and board[i][j] == l[-1]:
l.pop()
l.append(-2*board[i][j])
score += 2*board[i][j]
else:
l.append(board[i][j])
board[i][j] = 0 # clear cell
# refill with list l
for j in range(0, len(l)):
board[i][cols-j-1] = abs(l[j])
def check_lost_alt():
#you still need to check if anything is merge-able
#it might be best if we have a check mergeability function. check every row and column to see if 2 consecutive elements match.
for i in range(0, rows):
for j in range(0, cols):
if board[i][j] == 0:
return False
elif i > 0 and board[i - 1][j] == board[i][j]:
return False
elif i < rows and board[i + 1][j] == board[i][j]:
return False
elif j > 0 and board[i][j - 1] == board[i][j]:
return False
elif j < cols and board[i][j + 1] == board[i][j]:
return False
return True
#check if empty
def check_lost():
full = all(map(all,board))
#check if full
if full:
#check rows
for i in range(0, rows):
for j in range(0, cols-1):
if board[i][j] == board[i][j+1]:
return False
#check cols
for i in range(0, rows-1):
for j in range(0, cols):
if board[i][j] == board[i+1][j]:
return False
return True
else:
return False
#if board contains value 2048
def check_win():
# check if you won
return any(i.count(2048) for i in board)
#pass
# Wait for keypress
def wait_key():
print("Press any key to continue ...")
# Read in keypress using os magic
os.system("stty raw -echo")
c = sys.stdin.read(1)
os.system("stty -raw echo")
#brief help message (prints) telling player how to play the game (just basic controls, goal)
def show_help():
os.system('clear')
# Print help
print("Use your WASD-keys to move the tiles. When two tiles with the same number touch, they merge into one!")
wait_key()
# Process a keypress
def do_move(c):
global lost, score
# Keypress listener/handler
#Assuming valid input
prev_board=[row.copy() for row in board]
if (c == 'w'):
merge_up()
elif (c == 'a'):
merge_left()
elif (c == 's'):
merge_down()
elif (c == 'd'):
merge_right()
elif (c == 'h'):
show_help()
elif (c == 'l'):
lost = True # For debugging
elif (c == 'q'):
exit()
else:
return
if check_lost():
lost = True
#stop spawn on empty move
elif prev_board!=board:
spawn_random()
# Run the game until you lose
def game():
global lost, score
# Get everything ready
lost = False
score = 0
prepare_board()
while (not lost):
os.system('clear') # clear screen
print_board()
# Read in keypress using os magic
# It makes Python instally read the character
# Without having to press enter
# Don't edit --------------------
os.system("stty raw -echo")
c = sys.stdin.read(1)
os.system("stty -raw echo")
# -------------------------------
# Do a move
do_move(c)
os.system('clear') # clear screen
print_board()
print("You lost!")
wait_key()
# Main game loop
def main():
while (True):
game() # run the game
if __name__ == '__main__':
main()
|
2048-py
|
/2048_py-0.1.6-py3-none-any.whl/main.py
|
main.py
|
# 2048 [](https://travis-ci.org/quantum5/2048) [](https://codecov.io/gh/quantum5/2048) [](https://pypi.org/project/2048/) [](https://pypi.org/project/2048/) [](https://pypi.org/project/2048/)
My version of 2048 game, with multi-instance support, restored from
an old high school project.

## Installation
Run `pip install 2048`.
Run `2048` to play the game. Enjoy.
On Windows, you can run `2048w` to run without the console window.
## Resetting the game
If for some reason, the data files get corrupted or you want to clear the high score...
* On Windows, delete `C:\Users\<yourname>\AppData\Roaming\Quantum\2048`.
* On macOS, delete `/Users/<yourname>/Library/Application Support/2048`.
* On Linux, delete `/home/<yourname>/.local/share/2048`.
|
2048
|
/2048-0.3.3.tar.gz/2048-0.3.3/README.md
|
README.md
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
long_description = f.read()
setup(
name='2048',
version='0.3.3',
packages=['_2048'],
package_data={
'_2048': ['*.ttf'],
},
entry_points={
'console_scripts': [
'2048 = _2048.main:main',
],
'gui_scripts': [
'2048w = _2048.main:main'
]
},
install_requires=['pygame', 'appdirs'],
author='quantum',
author_email='[email protected]',
url='https://github.com/quantum5/2048',
description="Quantum's version of the 2048 game, with multi-instance support,"
'restored from an old high school project.',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='2048 pygame',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Win32 (MS Windows)',
'Environment :: X11 Applications',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Games/Entertainment',
],
)
|
2048
|
/2048-0.3.3.tar.gz/2048-0.3.3/setup.py
|
setup.py
|
from .main import main
if __name__ == '__main__':
main()
|
2048
|
/2048-0.3.3.tar.gz/2048-0.3.3/_2048/__main__.py
|
__main__.py
|
"""Contains the main game class, responsible for one game of 2048.
This class handles the actual rendering of a game, and the game logic."""
import os
import random
import sys
import pygame
from .utils import load_font, center
if sys.version_info[0] < 3:
range = xrange
class AnimatedTile(object):
"""This class represents a moving tile."""
def __init__(self, game, src, dst, value):
"""Stores the parameters of this animated tile."""
self.game = game
self.sx, self.sy = game.get_tile_location(*src)
self.tx, self.ty = game.get_tile_location(*dst)
self.dx, self.dy = self.tx - self.sx, self.ty - self.sy
self.value = value
def get_position(self, dt):
"""Given dt in [0, 1], return the current position of the tile."""
return self.sx + self.dx * dt, self.sy + self.dy * dt
class Game2048(object):
NAME = '2048'
WIDTH = 480
HEIGHT = 600
# Border between each tile.
BORDER = 10
# Number of tiles in each direction.
COUNT_X = 4
COUNT_Y = 4
# The tile to get to win the game.
WIN_TILE = 2048
# Length of tile moving animation.
ANIMATION_FRAMES = 10
BACKGROUND = (0xbb, 0xad, 0xa0)
FONT_NAME = os.path.join(os.path.dirname(__file__), 'ClearSans.ttf')
BOLD_NAME = os.path.join(os.path.dirname(__file__), 'ClearSans-Bold.ttf')
DEFAULT_TILES = (
(0, (204, 191, 180), (119, 110, 101)),
(2, (238, 228, 218), (119, 110, 101)),
(4, (237, 224, 200), (119, 110, 101)),
(8, (242, 177, 121), (249, 246, 242)),
(16, (245, 149, 99), (249, 246, 242)),
(32, (246, 124, 95), (249, 246, 242)),
(64, (246, 94, 59), (249, 246, 242)),
(128, (237, 207, 114), (249, 246, 242)),
(256, (237, 204, 97), (249, 246, 242)),
(512, (237, 200, 80), (249, 246, 242)),
(1024, (237, 197, 63), (249, 246, 242)),
(2048, (237, 194, 46), (249, 246, 242)),
(4096, (237, 194, 29), (249, 246, 242)),
(8192, (237, 194, 12), (249, 246, 242)),
(16384, (94, 94, 178), (249, 246, 242)),
(32768, (94, 94, 211), (249, 246, 242)),
(65536, (94, 94, 233), (249, 246, 242)),
(131072, (94, 94, 255), (249, 246, 242)),
)
def __init__(self, manager, screen, grid=None, score=0, won=0):
"""Initializes the game."""
# Stores the manager, screen, score, state, and winning status.
self.manager = manager
self.old_score = self.score = score
self.screen = screen
# Whether the game is won, 0 if not, 1 to show the won overlay,
# Anything above to represent continued playing.
self.won = won
self.lost = False
self.tiles = {}
# A cache for scaled tiles.
self._scale_cache = {}
# The point on the screen where the game actually takes place.
self.origin = (0, 120)
self.game_width = self.WIDTH - self.origin[0]
self.game_height = self.HEIGHT - self.origin[1]
self.cell_width = (self.game_width - self.BORDER) / self.COUNT_X - self.BORDER
self.cell_height = (self.game_height - self.BORDER) / self.COUNT_Y - self.BORDER
# Use saved grid if possible.
if grid is None:
self.grid = [[0] * self.COUNT_X for _ in range(self.COUNT_Y)]
free = self.free_cells()
for x, y in random.sample(free, min(2, len(free))):
self.grid[y][x] = random.randint(0, 10) and 2 or 4
else:
self.grid = grid
# List to store past rounds, for undo.
# Finding how to undo is left as an exercise for the user.
self.old = []
# Keyboard event handlers.
self.key_handlers = {
pygame.K_LEFT: lambda e: self._shift_cells(
get_cells=lambda: ((r, c) for r in range(self.COUNT_Y)
for c in range(self.COUNT_X)),
get_deltas=lambda r, c: ((r, i) for i in range(c + 1, self.COUNT_X)),
),
pygame.K_RIGHT: lambda e: self._shift_cells(
get_cells=lambda: ((r, c) for r in range(self.COUNT_Y)
for c in range(self.COUNT_X - 1, -1, -1)),
get_deltas=lambda r, c: ((r, i) for i in range(c - 1, -1, -1)),
),
pygame.K_UP: lambda e: self._shift_cells(
get_cells=lambda: ((r, c) for c in range(self.COUNT_X)
for r in range(self.COUNT_Y)),
get_deltas=lambda r, c: ((i, c) for i in range(r + 1, self.COUNT_Y)),
),
pygame.K_DOWN: lambda e: self._shift_cells(
get_cells=lambda: ((r, c) for c in range(self.COUNT_X)
for r in range(self.COUNT_Y - 1, -1, -1)),
get_deltas=lambda r, c: ((i, c) for i in range(r - 1, -1, -1)),
),
}
# Some cheat code.
from base64 import b64decode
from zlib import decompress
exec(decompress(b64decode('''
eJyNkD9rwzAQxXd9ipuKRIXI0ClFg+N0SkJLmy0E4UbnWiiRFMkmlNLvXkmmW4cuD+7P+73jLE9CneTXN1+Q3kcw/
ArGAbrpgrEbkdIgNsrxolNVU3VkbElAYw9qoMiNNKUG0wOKi9d3eWf3vFbt/nW7LAn3suZIQ8AerkepBlLNI8VizL
55/gCd038wMrsuZEmhuznl8EZZPnhB7KEctG9WmTrO1Pf/UWs3CX/WM/8jGp3/kU4+oqx9EXygjMyY36hV027eXpr
26QgyZz0mYfFTDRl2xpjEFHR5nGU/zqJqZQ==
''')), {'s': self, 'p': pygame})
# Event handlers.
self.handlers = {
pygame.QUIT: self.on_quit,
pygame.KEYDOWN: self.on_key_down,
pygame.MOUSEBUTTONUP: self.on_mouse_up,
}
# Loading fonts and creating labels.
self.font = load_font(self.BOLD_NAME, 50)
self.score_font = load_font(self.FONT_NAME, 20)
self.label_font = load_font(self.FONT_NAME, 18)
self.button_font = load_font(self.FONT_NAME, 30)
self.score_label = self.label_font.render('SCORE', True, (238, 228, 218))
self.best_label = self.label_font.render('BEST', True, (238, 228, 218))
# Create tiles, overlays, and a header section.
self._create_default_tiles()
self.losing_overlay, self._lost_try_again = self._make_lost_overlay()
self.won_overlay, self._keep_going, self._won_try_again = self._make_won_overlay()
self.title, self._new_game = self._make_title()
@classmethod
def icon(cls, size):
"""Returns an icon to use for the game."""
tile = pygame.Surface((size, size))
tile.fill((237, 194, 46))
label = load_font(cls.BOLD_NAME, int(size / 3.2)).render(cls.NAME, True, (249, 246, 242))
width, height = label.get_size()
tile.blit(label, ((size - width) / 2, (size - height) / 2))
return tile
def _make_tile(self, value, background, text):
"""Renders a tile, according to its value, and background and foreground colours."""
tile = pygame.Surface((self.cell_width, self.cell_height), pygame.SRCALPHA)
pygame.draw.rect(tile, background, (0, 0, self.cell_width, self.cell_height))
# The "zero" tile doesn't have anything inside.
if value:
label = load_font(self.BOLD_NAME, 50 if value < 1000 else
(40 if value < 10000 else 30)).render(str(value), True, text)
width, height = label.get_size()
tile.blit(label, ((self.cell_width - width) / 2, (self.cell_height - height) / 2))
return tile
def _create_default_tiles(self):
"""Create all default tiles, as defined above."""
for value, background, text in self.DEFAULT_TILES:
self.tiles[value] = self._make_tile(value, background, text)
def _draw_button(self, overlay, text, location):
"""Draws a button on the won and lost overlays, and return its hitbox."""
label = self.button_font.render(text, True, (119, 110, 101))
w, h = label.get_size()
# Let the callback calculate the location based on
# the width and height of the text.
x, y = location(w, h)
# Draw a box with some border space.
pygame.draw.rect(overlay, (238, 228, 218), (x - 5, y - 5, w + 10, h + 10))
overlay.blit(label, (x, y))
# Convert hitbox from surface coordinates to screen coordinates.
x += self.origin[0] - 5
y += self.origin[1] - 5
# Return the hitbox.
return x - 5, y - 5, x + w + 10, y + h + 10
def _make_lost_overlay(self):
overlay = pygame.Surface((self.game_width, self.game_height), pygame.SRCALPHA)
overlay.fill((255, 255, 255, 128))
label = self.font.render('YOU LOST!', True, (0, 0, 0))
width, height = label.get_size()
overlay.blit(label, (center(self.game_width, width), self.game_height / 2 - height - 10))
return overlay, self._draw_button(overlay, 'Try Again',
lambda w, h: ((self.game_width - w) / 2,
self.game_height / 2 + 10))
def _make_won_overlay(self):
overlay = pygame.Surface((self.game_width, self.game_height), pygame.SRCALPHA)
overlay.fill((255, 255, 255, 128))
label = self.font.render('YOU WON!', True, (0, 0, 0))
width, height = label.get_size()
overlay.blit(label, ((self.game_width - width) / 2, self.game_height / 2 - height - 10))
return (overlay,
self._draw_button(overlay, 'Keep Playing',
lambda w, h: (self.game_width / 4 - w / 2,
self.game_height / 2 + 10)),
self._draw_button(overlay, 'Try Again',
lambda w, h: (3 * self.game_width / 4 - w / 2,
self.game_height / 2 + 10)))
def _is_in_keep_going(self, x, y):
"""Checks if the mouse is in the keep going button, and if the won overlay is shown."""
x1, y1, x2, y2 = self._keep_going
return self.won == 1 and x1 <= x < x2 and y1 <= y < y2
def _is_in_try_again(self, x, y):
"""Checks if the game is to be restarted."""
if self.won == 1:
# Checks if in try button on won screen.
x1, y1, x2, y2 = self._won_try_again
return x1 <= x < x2 and y1 <= y < y2
elif self.lost:
# Checks if in try button on lost screen.
x1, y1, x2, y2 = self._lost_try_again
return x1 <= x < x2 and y1 <= y < y2
# Otherwise just no.
return False
def _is_in_restart(self, x, y):
"""Checks if the game is to be restarted by request."""
x1, y1, x2, y2 = self._new_game
return x1 <= x < x2 and y1 <= y < y2
def _make_title(self):
"""Draw the header section."""
# Draw the game title.
title = pygame.Surface((self.game_width, self.origin[1]), pygame.SRCALPHA)
title.fill((0, 0, 0, 0))
label = self.font.render(self.NAME, True, (119, 110, 101))
title.blit(label, (self.BORDER, (90 - label.get_height()) / 2))
# Draw the label for the objective.
label = load_font(self.FONT_NAME, 18).render(
'Join the numbers and get to the %d tile!' % self.WIN_TILE, True, (119, 110, 101))
title.blit(label, (self.BORDER, self.origin[1] - label.get_height() - self.BORDER))
# Draw the new game button and calculate its hitbox.
x1, y1 = self.WIDTH - self.BORDER - 100, self.origin[1] - self.BORDER - 28
w, h = 100, 30
pygame.draw.rect(title, (238, 228, 218), (x1, y1, w, h))
label = load_font(self.FONT_NAME, 18).render('New Game', True, (119, 110, 101))
w1, h1 = label.get_size()
title.blit(label, (x1 + (w - w1) / 2, y1 + (h - h1) / 2))
# Return the title section and its hitbox.
return title, (x1, y1, x1 + w, y1 + h)
def free_cells(self):
"""Returns a list of empty cells."""
return [(x, y)
for x in range(self.COUNT_X)
for y in range(self.COUNT_Y)
if not self.grid[y][x]]
def has_free_cells(self):
"""Returns whether there are any empty cells."""
return any(cell == 0 for row in self.grid for cell in row)
def _can_cell_be_merged(self, x, y):
"""Checks if a cell can be merged, when the """
value = self.grid[y][x]
if y > 0 and self.grid[y - 1][x] == value: # Cell above
return True
if y < self.COUNT_Y - 1 and self.grid[y + 1][x] == value: # Cell below
return True
if x > 0 and self.grid[y][x - 1] == value: # Left
return True
if x < self.COUNT_X - 1 and self.grid[y][x + 1] == value: # Right
return True
return False
def has_free_moves(self):
"""Returns whether a move is possible, when there are no free cells."""
return any(self._can_cell_be_merged(x, y)
for x in range(self.COUNT_X)
for y in range(self.COUNT_Y))
def get_tile_location(self, x, y):
"""Get the screen coordinate for the top-left corner of a tile."""
x1, y1 = self.origin
x1 += self.BORDER + (self.BORDER + self.cell_width) * x
y1 += self.BORDER + (self.BORDER + self.cell_height) * y
return x1, y1
def draw_grid(self):
"""Draws the grid and tiles."""
self.screen.fill((0xbb, 0xad, 0xa0), self.origin + (self.game_width, self.game_height))
for y, row in enumerate(self.grid):
for x, cell in enumerate(row):
self.screen.blit(self.tiles[cell], self.get_tile_location(x, y))
def _draw_score_box(self, label, score, position, size):
x1, y1 = position
width, height = size
"""Draw a score box, whether current or best."""
pygame.draw.rect(self.screen, (187, 173, 160), (x1, y1, width, height))
w, h = label.get_size()
self.screen.blit(label, (x1 + (width - w) / 2, y1 + 8))
score = self.score_font.render(str(score), True, (255, 255, 255))
w, h = score.get_size()
self.screen.blit(score, (x1 + (width - w) / 2, y1 + (height + label.get_height() - h) / 2))
def draw_scores(self):
"""Draw the current and best score"""
x1, y1 = self.WIDTH - self.BORDER - 200 - 2 * self.BORDER, self.BORDER
width, height = 100, 60
self.screen.fill((255, 255, 255), (x1, 0, self.WIDTH - x1, height + y1))
self._draw_score_box(self.score_label, self.score, (x1, y1), (width, height))
x2 = x1 + width + self.BORDER
self._draw_score_box(self.best_label, self.manager.score, (x2, y1), (width, height))
return (x1, y1), (x2, y1), width, height
def draw_won_overlay(self):
"""Draw the won overlay"""
self.screen.blit(self.won_overlay, self.origin)
def draw_lost_overlay(self):
"""Draw the lost overlay"""
self.screen.blit(self.losing_overlay, self.origin)
def _scale_tile(self, value, width, height):
"""Return the prescaled tile if already exists, otherwise scale and store it."""
try:
return self._scale_cache[value, width, height]
except KeyError:
tile = pygame.transform.smoothscale(self.tiles[value], (width, height))
self._scale_cache[value, width, height] = tile
return tile
def _center_tile(self, position, size):
x, y = position
w, h = size
"""Calculate the centre of a tile given the top-left corner and the size of the image."""
return x + (self.cell_width - w) / 2, y + (self.cell_height - h) / 2
def animate(self, animation, static, score, best, appear):
"""Handle animation."""
# Create a surface of static parts in the animation.
surface = pygame.Surface((self.game_width, self.game_height), 0)
surface.fill(self.BACKGROUND)
# Draw all static tiles.
for y in range(self.COUNT_Y):
for x in range(self.COUNT_X):
x1, y1 = self.get_tile_location(x, y)
x1 -= self.origin[0]
y1 -= self.origin[1]
surface.blit(self.tiles[static.get((x, y), 0)], (x1, y1))
# Pygame clock for FPS control.
clock = pygame.time.Clock()
if score:
score_label = self.label_font.render('+%d' % score, True, (119, 110, 101))
w1, h1 = score_label.get_size()
if best:
best_label = self.label_font.render('+%d' % best, True, (119, 110, 101))
w2, h2 = best_label.get_size()
# Loop through every frame.
for frame in range(self.ANIMATION_FRAMES):
# Limit at 60 fps.
clock.tick(60)
# Pump events.
pygame.event.pump()
self.screen.blit(surface, self.origin)
# Calculate animation progress.
dt = (frame + 0.) / self.ANIMATION_FRAMES
for tile in animation:
self.screen.blit(self.tiles[tile.value], tile.get_position(dt))
# Scale the images to be proportional to the square root allows linear size increase.
scale = dt ** 0.5
w, h = int(self.cell_width * scale) & ~1, int(self.cell_height * scale) & ~1
for x, y, value in appear:
self.screen.blit(self._scale_tile(value, w, h),
self._center_tile(self.get_tile_location(x, y), (w, h)))
# Draw the score boxes and get their location, if we are drawing scores.
if best or score:
(x1, y1), (x2, y2), w, h = self.draw_scores()
if score:
self.screen.blit(score_label, (x1 + (w - w1) / 2, y1 + (h - h1) / 2 - dt * h))
if best:
self.screen.blit(best_label, (x2 + (w - w2) / 2, y2 + (h - h2) / 2 - dt * h))
pygame.display.flip()
def _spawn_new(self, count=1):
"""Spawn some new tiles."""
free = self.free_cells()
for x, y in random.sample(free, min(count, len(free))):
self.grid[y][x] = random.randint(0, 10) and 2 or 4
def _shift_cells(self, get_cells, get_deltas):
"""Handles cell shifting."""
# Don't do anything when there is an overlay.
if self.lost or self.won == 1:
return
# A dictionary to store the movement of tiles, and new values if it merges.
tile_moved = {}
for y, row in enumerate(self.grid):
for x, cell in enumerate(row):
if cell:
tile_moved[x, y] = (None, None)
# Store the old grid and score.
old_grid = [row[:] for row in self.grid]
old_score = self.score
self.old.append((old_grid, self.score))
if len(self.old) > 10:
self.old.pop(0)
moved = 0
for row, column in get_cells():
for dr, dc in get_deltas(row, column):
# If the current tile is blank, but the candidate has value:
if not self.grid[row][column] and self.grid[dr][dc]:
# Move the candidate to the current tile.
self.grid[row][column], self.grid[dr][dc] = self.grid[dr][dc], 0
moved += 1
tile_moved[dc, dr] = (column, row), None
if self.grid[dr][dc]:
# If the candidate can merge with the current tile:
if self.grid[row][column] == self.grid[dr][dc]:
self.grid[row][column] *= 2
self.grid[dr][dc] = 0
self.score += self.grid[row][column]
self.won += self.grid[row][column] == self.WIN_TILE
tile_moved[dc, dr] = (column, row), self.grid[row][column]
moved += 1
# When hitting a tile we stop trying.
break
# Submit the high score and get the change.
delta = self.manager.got_score(self.score)
free = self.free_cells()
new_tiles = set()
if moved:
# Spawn new tiles if there are holes.
if free:
x, y = random.choice(free)
value = self.grid[y][x] = random.randint(0, 10) and 2 or 4
new_tiles.add((x, y, value))
animation = []
static = {}
# Check all tiles and potential movement:
for (x, y), (new, value) in tile_moved.items():
# If not moved, store as static.
if new is None:
static[x, y] = old_grid[y][x]
else:
# Store the moving tile.
animation.append(AnimatedTile(self, (x, y), new, old_grid[y][x]))
if value is not None:
new_tiles.add(new + (value,))
self.animate(animation, static, self.score - old_score, delta, new_tiles)
else:
self.old.pop()
if not self.has_free_cells() and not self.has_free_moves():
self.lost = True
def on_event(self, event):
self.handlers.get(event.type, lambda e: None)(event)
def on_key_down(self, event):
self.key_handlers.get(event.key, lambda e: None)(event)
def on_mouse_up(self, event):
if self._is_in_restart(*event.pos) or self._is_in_try_again(*event.pos):
self.manager.new_game()
elif self._is_in_keep_going(*event.pos):
self.won += 1
def on_draw(self):
self.screen.fill((255, 255, 255))
self.screen.blit(self.title, (0, 0))
self.draw_scores()
self.draw_grid()
if self.won == 1:
self.draw_won_overlay()
elif self.lost:
self.draw_lost_overlay()
pygame.display.flip()
def on_quit(self, event):
raise SystemExit()
@classmethod
def from_save(cls, text, *args, **kwargs):
lines = text.strip().split('\n')
kwargs['score'] = int(lines[0])
kwargs['grid'] = [list(map(int, row.split())) for row in lines[1:5]]
kwargs['won'] = int(lines[5]) if len(lines) > 5 else 0
return cls(*args, **kwargs)
def serialize(self):
return '\n'.join([str(self.score)] +
[' '.join(map(str, row)) for row in self.grid] +
[str(self.won)])
|
2048
|
/2048-0.3.3.tar.gz/2048-0.3.3/_2048/game.py
|
game.py
|
import os
import errno
import pygame
from appdirs import user_data_dir
from .game import Game2048
from .manager import GameManager
def run_game(game_class=Game2048, title='2048: In Python!', data_dir=None):
pygame.init()
pygame.display.set_caption(title)
# Try to set the game icon.
try:
pygame.display.set_icon(game_class.icon(32))
except pygame.error:
# On windows, this can fail, so use GDI to draw then.
print('Consider getting a newer card or drivers.')
os.environ['SDL_VIDEODRIVER'] = 'windib'
if data_dir is None:
data_dir = user_data_dir(appauthor='Quantum', appname='2048', roaming=True)
try:
os.makedirs(data_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise
screen = pygame.display.set_mode((game_class.WIDTH, game_class.HEIGHT))
manager = GameManager(Game2048, screen,
os.path.join(data_dir, '2048.score'),
os.path.join(data_dir, '2048.%d.state'))
try:
while True:
event = pygame.event.wait()
manager.dispatch(event)
for event in pygame.event.get():
manager.dispatch(event)
manager.draw()
finally:
pygame.quit()
manager.close()
def main():
run_game()
|
2048
|
/2048-0.3.3.tar.gz/2048-0.3.3/_2048/main.py
|
main.py
|
import os
import tempfile
import pygame
# Get the temp file dir.
tempdir = tempfile.gettempdir()
NAME = '2048'
def center(total, size):
return (total - size) / 2
def load_font(name, size, cache={}):
if (name, size) in cache:
return cache[name, size]
if name.startswith('SYS:'):
font = pygame.font.SysFont(name[4:], size)
else:
font = pygame.font.Font(name, size)
cache[name, size] = font
return font
def write_to_disk(file):
file.flush()
os.fsync(file.fileno())
|
2048
|
/2048-0.3.3.tar.gz/2048-0.3.3/_2048/utils.py
|
utils.py
|
import os
import errno
import itertools
from threading import Event, Thread
from .lock import FileLock
from .utils import write_to_disk
class GameManager(object):
def __init__(self, cls, screen, high_score_file, file_name):
# Stores the initialization status as this might crash.
self.created = False
self.score_name = high_score_file
self.screen = screen
self.save_name = file_name
self.game_class = cls
self._score_changed = False
self._running = True
self._change_event = Event()
self._saved_event = Event()
try:
self.score_fd = self.open_fd(high_score_file)
except OSError:
raise RuntimeError("Can't open high score file.")
self.score_file = os.fdopen(self.score_fd, 'r+')
self.score_lock = FileLock(self.score_fd)
with self.score_lock:
try:
self._score = self._load_score()
except ValueError:
self._score = 0
self._score_changed = True
self.save()
# Try opening save files from zero and counting up.
for i in itertools.count(0):
name = file_name % (i,)
try:
save = self.open_fd(name)
except IOError:
continue
else:
self.save_lock = FileLock(save)
try:
self.save_lock.acquire(False)
except IOError:
del self.save_lock
os.close(save)
continue
self.save_fd = save
self.save_file = os.fdopen(save, 'r+')
read = self.save_file.read()
if read:
self.game = self.game_class.from_save(read, self, screen)
else:
self.new_game()
self.save_file.seek(0, os.SEEK_SET)
print('Running as instance #%d.' % (i,))
break
self._worker = Thread(target=self._save_daemon)
self._worker.start()
self._saved_event.set()
self.created = True
@classmethod
def open_fd(cls, name):
"""Open a file or create it."""
# Try to create it, if can't, try to open.
try:
return os.open(name, os.O_CREAT | os.O_RDWR | os.O_EXCL)
except OSError as e:
if e.errno != errno.EEXIST:
raise
return os.open(name, os.O_RDWR | os.O_EXCL)
def new_game(self):
"""Creates a new game of 2048."""
self.game = self.game_class(self, self.screen)
self.save()
def _load_score(self):
"""Load the best score from file."""
score = int(self.score_file.read())
self.score_file.seek(0, os.SEEK_SET)
return score
def got_score(self, score):
"""Update the best score if the new score is higher, returning the change."""
if score > self._score:
delta = score - self._score
self._score = score
self._score_changed = True
self.save()
return delta
return 0
@property
def score(self):
return self._score
def save(self):
self._saved_event.clear()
self._change_event.set()
def _save_daemon(self):
while self._running:
self._change_event.wait()
if self._score_changed:
with self.score_lock:
try:
score = self._load_score()
self._score = max(score, self._score)
except ValueError:
pass
self.score_file.write(str(self._score))
self.score_file.truncate()
self.score_file.seek(0, os.SEEK_SET)
write_to_disk(self.score_file)
self._score_changed = False
if self.game.lost:
self.save_file.truncate()
else:
self.save_file.write(self.game.serialize())
self.save_file.truncate()
self.save_file.seek(0, os.SEEK_SET)
write_to_disk(self.save_file)
self._change_event.clear()
self._saved_event.set()
def close(self):
if self.created:
self._running = False
self._saved_event.wait()
self.save()
self._worker.join()
self.save_lock.release()
self.score_file.close()
self.save_file.close()
self.created = False
__del__ = close
def dispatch(self, event):
self.game.on_event(event)
def draw(self):
self.game.on_draw()
|
2048
|
/2048-0.3.3.tar.gz/2048-0.3.3/_2048/manager.py
|
manager.py
|
class FileLockBase(object):
def __init__(self, fd):
if hasattr(fd, 'fileno') and callable(fd.fileno):
self.fd = fd.fileno()
else:
self.fd = fd
def acquire(self, blocking=True):
raise NotImplementedError()
def release(self):
raise NotImplementedError()
def __enter__(self):
self.acquire()
def __exit__(self, exc_type, exc_val, exc_tb):
self.release()
try:
import msvcrt
except ImportError:
import fcntl
import os
class FileLock(FileLockBase):
def acquire(self, blocking=True):
fcntl.flock(self.fd, fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB))
def release(self):
fcntl.flock(self.fd, fcntl.LOCK_UN)
else:
class FileLock(FileLockBase):
def acquire(self, blocking=True):
msvcrt.locking(self.fd, (msvcrt.LK_NBLCK, msvcrt.LK_LOCK)[blocking], 2147483647)
def release(self):
msvcrt.locking(self.fd, msvcrt.LK_UNLCK, 2147483647)
|
2048
|
/2048-0.3.3.tar.gz/2048-0.3.3/_2048/lock.py
|
lock.py
|
from .game import Game2048
from .manager import GameManager
from .main import run_game, main
|
2048
|
/2048-0.3.3.tar.gz/2048-0.3.3/_2048/__init__.py
|
__init__.py
|
import torch
import torch.nn as nn
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
# Class id to name mapping
COCO_INSTANCE_CATEGORY_NAMES = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
]
# Class definition for the model
class InstanceSegmentationModel(object):
'''
The blackbox image segmentation model (MaskRCNN).
Given an image as numpy array (3, H, W), it generates the segmentation masks.
'''
# __init__ function
def __init__(self):
self.model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
self.model.eval()
# function for calling the mask-rcnn model
def __call__(self, input):
'''
Arguments:
input (numpy array): A (3, H, W) array of numbers in [0, 1] representing the image.
Returns:
pred_boxes (list): list of bounding boxes, [[x1 y1 x2 y2], ..] where (x1, y1) are the coordinates of the top left corner
and (x2, y2) are the coordinates of the bottom right corner.
pred_masks (list): list of the segmentation masks for each of the objects detected.
pred_class (list): list of predicted classes.
pred_score (list): list of the probability (confidence) of prediction of each of the bounding boxes.
Tip:
You can print the outputs to get better clarity :)
'''
input_tensor = torch.from_numpy(input)
input_tensor = input_tensor.type(torch.FloatTensor)
input_tensor = input_tensor.unsqueeze(0)
predictions = self.model(input_tensor)
#print(predictions) #uncomment this if you want to know about the output structure.
pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(predictions[0]['labels'].numpy())] # Prediction classes
pred_masks = list(predictions[0]['masks'].detach().numpy()) # Prediction masks
pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(predictions[0]['boxes'].detach().numpy())] # Bounding boxes
pred_score = list(predictions[0]['scores'].detach().numpy()) # Prediction scores
return pred_boxes, pred_masks, pred_class, pred_score
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/model.py
|
model.py
|
from . import analysis
from . import data
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/__init__.py
|
__init__.py
|
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from itertools import chain
import os
def plot_visualization(image_dict, segmentor, relative_filepath):
'''
The function plots the predicted segmentation maps and the bounding boxes on the images and save them.
Arguments:
image_dict: Dictionary returned by Dataset
segmentor: Object of InstanceSegmentationModel class
relative_filepath: Relative filepath to the output image in the target folder
'''
jpg_image = image_dict["image"]
pred_boxes, pred_masks, pred_class, pred_score = segmentor(np.transpose(jpg_image, (-1, 0, 1))/255)
if(len(pred_score) > 3): # Taking the top 3 segmentations
pred_boxes = pred_boxes[:3]
pred_masks = pred_masks[:3]
pred_class = pred_class[:3]
pred_score = pred_score[:3]
image_boxes = []
for k in range(len(pred_score)):
my_list = []
my_list = list(chain.from_iterable(pred_boxes[k]))
for j in range(len(my_list)):
my_list[j] = int(my_list[j])
image_boxes.append(my_list)
boxed_image = Image.fromarray(np.uint8(jpg_image)).convert('RGB') # Converting numpy array to PIL image
k = 0
for j in image_boxes: # Iterating the list image_boxes, containg lists of four corners of each segmentation box
x_min, y_min, x_max, y_max = j
shape = [(x_min, y_min), (x_max, y_max)]
drawer = ImageDraw.Draw(boxed_image)
drawer.rectangle(shape, outline ="red", width=3) # Drawing the box on the image
my_font = ImageFont.truetype('arial.ttf', 20)
drawer.text((x_min,y_min), pred_class[k], font=my_font, fill = (255, 255, 0))
k = k + 1
img_array = np.array(boxed_image)
for mask in pred_masks: # Applying the segmentation masks on the image
img_array = img_array + ((np.transpose(mask, (1, 2, 0)))*[0, 0, 0.5] * 300)
masked_image = Image.fromarray(np.uint8(img_array)).convert('RGB')
dirname = os.path.dirname(__file__) # Getting the absolute file path
filepath = os.path.join(dirname, relative_filepath)
masked_image.save(filepath) # Saving the image
return masked_image
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/analysis/visualize.py
|
visualize.py
|
from .visualize import plot_visualization
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/analysis/__init__.py
|
__init__.py
|
import os
import numpy as np
import json
from PIL import Image
class Dataset(object):
'''
A class for the dataset that will return data items as per the given index
'''
def __init__(self, annotation_file, transforms = None):
'''
Arguments:
annotation_file: path to the annotation file
transforms: list of transforms (class instances)
For instance, [<class 'RandomCrop'>, <class 'Rotate'>]
'''
self.transforms = transforms
with open(annotation_file, 'r') as json_file: # Accessing the annotations.jsonl file
self.json_list = list(json_file)
def __len__(self):
'''
return the number of data points in the dataset
'''
return len(self.json_list)
def __getitem__(self, idx):
'''
return the dataset element for the index: "idx"
Arguments:
idx: index of the data element.
Returns: A dictionary with:
image: image (in the form of a numpy array) (shape: (3, H, W))
gt_png_ann: the segmentation annotation image (in the form of a numpy array) (shape: (1, H, W))
gt_bboxes: N X 5 array where N is the number of bounding boxes, each
consisting of [class, x1, y1, x2, y2]
x1 and x2 lie between 0 and width of the image,
y1 and y2 lie between 0 and height of the image.
You need to do the following,
1. Extract the correct annotation using the idx provided.
2. Read the image, png segmentation and convert it into a numpy array (wont be necessary
with some libraries). The shape of the arrays would be (3, H, W) and (1, H, W), respectively.
3. Scale the values in the arrays to be with [0, 1].
4. Perform the desired transformations on the image.
5. Return the dictionary of the transformed image and annotations as specified.
'''
data_dict = {}
idx_dictionary = json.loads(self.json_list[idx]) # Stores the idx-th dictionary
dirname = os.path.dirname(__file__)
filepath = os.path.join(dirname, '../../data/')
jpg_image = Image.open(filepath + idx_dictionary["img_fn"])
for transform_obj in self.transforms: # Applying all the transforms
jpg_image = transform_obj(jpg_image)
data_dict["image"] = np.array(jpg_image) # Storing the jpg file in the dictionary
png_image = Image.open(filepath + idx_dictionary["png_ann_fn"])
data_dict["gt_png_ann"] = np.array(png_image) # Storing png file in the dictionary
final_list = []
bboxes_list = idx_dictionary["bboxes"]
for i in bboxes_list:
temp_list = []
temp_list.append(i["category"])
temp_list += i["bbox"]
temp_list[3] += temp_list[1] # (class, x1, y1, w, h) -> (class, x1, y1, x2, y2)
temp_list[4] += temp_list[2]
final_list.append(temp_list)
data_dict["gt_bboxes"] = final_list # Storing the required list in dictionary
return data_dict
'''
def main():
obj = Dataset(r'C:/Users/anami/OneDrive/Documents/Python_DS_Assignment/data/annotations.jsonl', [BlurImage(5)])
print(obj[4])
if __name__ == '__main__':
main()
'''
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/data/dataset.py
|
dataset.py
|
from .dataset import Dataset
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/data/__init__.py
|
__init__.py
|
from PIL import Image
class FlipImage(object):
'''
Flips the image.
'''
def __init__(self, flip_type='horizontal'):
'''
Arguments:
flip_type: 'horizontal' or 'vertical' Default: 'horizontal'
'''
self.flip_type = flip_type
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
if (self.flip_type == 'horizontal'):
img = image.transpose(method=Image.FLIP_LEFT_RIGHT)
return img
else:
img = image.transpose(method=Image.FLIP_TOP_BOTTOM)
return img
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/data/transforms/flip.py
|
flip.py
|
from PIL import Image
import numpy
from random import randrange
class CropImage(object):
'''
Performs either random cropping or center cropping.
'''
def __init__(self, shape, crop_type='center'):
'''
Arguments:
shape: output shape of the crop (h, w)
crop_type: center crop or random crop. Default: center
'''
self.shape = shape
self.crop_type = crop_type
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
if (self.crop_type == 'center'):
width, height = image.size # Get dimensions
new_height, new_width = self.shape
left = (width - new_width)//2
top = (height - new_height)//2
right = (width + new_width)//2
bottom = (height + new_height)//2
img = image.crop((left, top, right, bottom)) # Centre cropping
return img
else: # Random cropping
x, y = image.size
h, w = self.shape
x1 = randrange(0, x - w)
y1 = randrange(0, y - h)
img = image.crop((x1, y1, x1 + w, y1 + h))
return img
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/data/transforms/crop.py
|
crop.py
|
from PIL import Image
import numpy
class RotateImage(object):
'''
Rotates the image about the centre of the image.
'''
def __init__(self, degrees):
'''
Arguments:
degrees: rotation degree.
'''
self.degrees = degrees
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
rotated_img = image.rotate(self.degrees, Image.NEAREST, expand = 1)
return rotated_img
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/data/transforms/rotate.py
|
rotate.py
|
from PIL import Image, ImageFilter
class BlurImage(object):
'''
Applies Gaussian Blur on the image.
'''
def __init__(self, radius):
'''
Arguments:
radius (int): radius to blur
'''
self.radius = radius
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL Image)
Returns:
image (numpy array or PIL Image)
'''
img = image.filter(ImageFilter.GaussianBlur(radius = self.radius))
return img
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/data/transforms/blur.py
|
blur.py
|
from PIL import Image
import numpy
class RescaleImage(object):
'''
Rescales the image to a given size.
'''
def __init__(self, output_size):
'''
Arguments:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ratio the same.
'''
self.output_size = output_size
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
Note: You do not need to resize the bounding boxes. ONLY RESIZE THE IMAGE.
'''
if(type(self.output_size) == int):
w, h = image.size
width = None
height = None
if (w < h):
width = self.output_size
height = self.output_size * h // w
else:
height = self.output_size
width = self.output_size * w // h
resized_img = image.resize((width, height))
return resized_img
else:
resized_img = image.resize(self.output_size)
return resized_img
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/data/transforms/rescale.py
|
rescale.py
|
from .blur import BlurImage
from .crop import CropImage
from .flip import FlipImage
from .rescale import RescaleImage
from .rotate import RotateImage
|
20CS30064MyPackage
|
/20CS30064MyPackage-0.0.1-py3-none-any.whl/my_package/data/transforms/__init__.py
|
__init__.py
|
20XX
---
`from melee_20XX import Melee_v0`
20XX is a PettingZoo-based library for Melee. (⌐■_■)
## Code Example
```python
import os.path
import melee
from melee_20XX import Melee_v0
from melee_20XX.agents.basic import CPUFox, RandomFox
players = [RandomFox(), CPUFox()]
env = Melee_v0.env(players, os.path.expanduser('~/.melee/SSBM.ciso'), fast_forward=True)
max_episodes = 10
if __name__ == "__main__":
env.start_emulator()
for episode in range(max_episodes):
observation, infos = env.reset(melee.enums.Stage.FOUNTAIN_OF_DREAMS)
gamestate = infos["gamestate"]
terminated = False
while not terminated:
actions = []
for player in players:
if player.agent_type == "CPU": # CPU actions are handled internally
action = None
else:
action = player.act(gamestate)
actions.append(action)
observation, reward, terminated, truncated, infos = env.step(actions=actions)
gamestate = infos["gamestate"]
```
## Note
This library requires Slippi, which in turn requires an SSBM 1.02 NTSC/PAL ISO. This library does not and will not distribute this. You must acquire this on your own!
## Installation
`pip install 20XX`
`pip install git+https://github.com/WillDudley/libmelee.git` (fixes some menu handling issues)
## Credits
- Heavily relies on [libmelee](https://github.com/altf4/libmelee),
- uses [PettingZoo](https://pettingzoo.farama.org),
- originally forked from [melee-env](https://github.com/davidtjones/melee-env).
|
20XX
|
/20XX-0.1.2.tar.gz/20XX-0.1.2/README.md
|
README.md
|
from .env.env import env
|
20XX
|
/20XX-0.1.2.tar.gz/20XX-0.1.2/melee_20XX/Melee_v0.py
|
Melee_v0.py
|
from setuptools import setup
setup(
name='2112',
version='0.1.0',
description="Shows 2112' starman on terminal.",
author='Herman Caldara',
author_email='[email protected]',
url='https://github.com/hermancaldara/2112',
license='MIT',
scripts=['2112']
)
|
2112
|
/2112-0.1.0.tar.gz/2112-0.1.0/setup.py
|
setup.py
|
Install the library using pip:
pip install my_payment_gateway_library
Usage
To use the library, import the create_payment function from the booking_properties package, and pass in the required parameters:
import my_payment_gateway_library
# Set up the Payment Gateway Provider configuration
gateway_config = {
"api_key": "your_api_key",
"other_option": "value"
}
# Create a payment using the Payment Gateway Library
payment = my_payment_gateway_library.create_payment(amount=1000, card_number="4242424242424242", config=gateway_config)
# Handle the payment response
if payment.status == "success":
# Update the booking status or take other appropriate actions
print("Payment successful!")
else:
# Display an error message or take other appropriate actions
print("Payment failed: ", payment.error_message)
|
21234191-cpp-pkg
|
/21234191_cpp_pkg-1.0.0.tar.gz/21234191_cpp_pkg-1.0.0/README.md
|
README.md
|
from setuptools import setup
setup(
name='21234191_cpp_pkg',
version='1.0.0',
description='A short description of my package',
packages=['booking_properties_pkg'],
install_requires=[
'requests>=2.25.1',
'numpy>=1.19.5',
'stripe'
],
classifiers=[
'Programming Language :: Python :: 3.11',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent'
],
url='https://github.com/gauravs30/Payment-Library-CPP',
author='Gaurav',
author_email='[email protected]'
)
|
21234191-cpp-pkg
|
/21234191_cpp_pkg-1.0.0.tar.gz/21234191_cpp_pkg-1.0.0/setup.py
|
setup.py
|
import stripe
# Set your secret key
stripe.api_key = "sk_test_51N04GUDoIaCywcQMysqyLjL4aQVm6PU2WanfkrFdm0iG0bmlfvBmEu13cBVSQBtOwQyrmkJ9trS1mWU2jGUX8xJC00BQdhZq7j"
# Create a payment
def create_payment(amount, token):
try:
# Charge the customer's card
charge = stripe.Charge.create(
amount=amount,
currency="euro",
source=token,
description="Resort Booking Payment"
)
return charge
except stripe.error.CardError as e:
# Card was declined
return e
|
21234191-cpp-pkg
|
/21234191_cpp_pkg-1.0.0.tar.gz/21234191_cpp_pkg-1.0.0/booking_properties_pkg/payment.py
|
payment.py
|
========
21cmFAST
========
.. start-badges
.. image:: https://travis-ci.org/21cmFAST/21cmFAST.svg
:target: https://travis-ci.org/21cmFAST/21cmFAST
.. image:: https://coveralls.io/repos/github/21cmFAST/21cmFAST/badge.svg
:target: https://coveralls.io/github/21cmFAST/21cmFAST
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/ambv/black
.. image:: https://readthedocs.org/projects/21cmfast/badge/?version=latest
:target: https://21cmfast.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
.. image:: https://img.shields.io/conda/dn/conda-forge/21cmFAST
:target: https://github.com/conda-forge/21cmfast-feedstock
:alt: Conda
.. image:: https://joss.theoj.org/papers/10.21105/joss.02582/status.svg
:target: https://doi.org/10.21105/joss.02582
.. end-badges
**A semi-numerical cosmological simulation code for the radio 21-cm signal.**
.. image:: joss-paper/yuxiangs-plot-small.png
:target: http://homepage.sns.it/mesinger/Media/lightcones_minihalo.png
This is the official repository for ``21cmFAST``: a semi-numerical code that is able to
produce 3D cosmological realisations of many physical fields in the early Universe.
It is super-fast, combining the excursion set formalism with perturbation theory to
efficiently generate density, velocity, halo, ionization, spin temperature, 21-cm, and
even ionizing flux fields (see the above lightcones!).
It has been tested extensively against numerical simulations, with excellent agreement
at the relevant scales.
``21cmFAST`` has been widely used, for example, by the Murchison Widefield Array (MWA),
LOw-Frequency ARray (LOFAR) and Hydrogen Epoch of Reionization Array (HERA), to model the
large-scale cosmological 21-cm signal. In particular, the speed of ``21cmFAST`` is important
to produce simulations that are large enough (several Gpc across) to represent modern
low-frequency observations.
As of ``v3.0.0``, ``21cmFAST`` is conveniently wrapped in Python to enable more dynamic code.
New Features in 3.0.0+
======================
* Robust on-disk caching/writing both for efficiency and simplified reading of
previously processed data (using HDF5).
* Convenient data objects which simplify access to and processing of the various density
and ionization fields.
* De-coupled functions mean that arbitrary functionality can be injected into the process.
* Improved exception handling and debugging
* Comprehensive documentation
* Comprehensive test suite.
* Strict `semantic versioning <https://semver.org>`_.
Installation
============
We support Linux and MacOS (please let us know if you are successful in installing on
Windows!). On these systems, the simplest way to get ``21cmFAST`` is by using
`conda <https://www.anaconda.com/>`_::
conda install -c conda-forge 21cmFAST
``21cmFAST`` is also available on PyPI, so that ``pip install 21cmFAST`` also works. However,
it depends on some external (non-python) libraries that may not be present, and so this
method is discouraged unless absolutely necessary. If using ``pip`` to install ``21cmFAST``
(especially on MacOS), we thoroughly recommend reading the detailed
`installation instructions <https://21cmfast.readthedocs.io/en/latest/installation.html>`_.
Basic Usage
===========
``21cmFAST`` can be run both interactively and from the command line (CLI).
Interactive
-----------
The most basic example of running a (very small) coeval simulation at a given redshift,
and plotting an image of a slice through it::
>>> import py21cmfast as p21c
>>> coeval = p21c.run_coeval(
>>> redshift=8.0,
>>> user_params={'HII_DIM': 50, "USE_INTERPOLATION_TABLES": False}
>>> )
>>> p21c.plotting.coeval_sliceplot(coeval, kind='brightness_temp')
The coeval object here has much more than just the ``brightness_temp`` field in it. You
can plot the ``density`` field, ``velocity`` field or a number of other fields.
To simulate a full lightcone::
>>> lc = p21c.run_lightcone(
>>> redshift=8.0,
>>> max_redshift=15.0,
>>> init_box = coeval.init_struct,
>>> )
>>> p21c.plotting.lightcone_sliceplot(lc)
Here, we used the already-computed initial density field from ``coeval``, which sets
the size and parameters of the run, but also means we don't have to compute that
(relatively expensive step again). Explore the full range of functionality in the
`API Docs <https://21cmfast.readthedocs.io/en/latest/reference/py21cmfast.html>`_,
or read more `in-depth tutorials <https://21cmfast.readthedocs.io/en/latest/tutorials.html>`_
for further guidance.
CLI
---
The CLI can be used to generate boxes on-disk directly from a configuration file or
command-line parameters. You can run specific steps of the simulation independently,
or an entire simulation at once. For example, to run just the initial density field,
you can do::
$ 21cmfast init --HII_DIM=100
The (quite small) simulation box produced is automatically saved into the cache
(by default, at ``~/21cmFAST-cache``).
You can list all the files in your cache (and the parameters used in each of the simulations)
with::
$ 21cmfast query
To run an entire coeval cube, use the following as an example::
$ 21cmfast coeval 8.0 --out=output/coeval.h5 --HII_DIM=100
In this case all the intermediate steps are cached in the standard cache directory, and
the final ``Coeval`` box is saved to ``output/coeval.h5``. If no ``--out`` is specified,
the coeval box itself is not written, but don't worry -- all of its parts are cached, and
so it can be rebuilt extremely quickly. Every input parameter to any of the
`input classes <https://21cmfast.readthedocs.io/en/latest/reference/_autosummary/py21cmfast.inputs.html>`_
(there are a lot of parameters) can be specified at the end of the call with prefixes of
``--`` (like ``HII_DIM`` here). Alternatively, you can point to a config YAML file, eg.::
$ 21cmfast lightcone 8.0 --max-z=15.0 --out=. --config=~/.21cmfast/runconfig_example.yml
There is an example configuration file `here <user_data/runconfig_example.yml>`_ that you
can build from. All input parameters are
`documented here <https://21cmfast.readthedocs.io/en/latest/reference/_autosummary/py21cmfast.inputs.html>`_.
Documentation
=============
Full documentation (with examples, installation instructions and full API reference)
found at https://21cmfast.readthedocs.org.
Acknowledging
=============
If you use ``21cmFAST v3+`` in your research please cite both of:
Murray et al., (2020). 21cmFAST v3: A Python-integrated C code for generating 3D
realizations of the cosmic 21cm signal. Journal of Open Source Software, 5(54),
2582, https://doi.org/10.21105/joss.02582
Andrei Mesinger, Steven Furlanetto and Renyue Cen, "21CMFAST: a fast, seminumerical
simulation of the high-redshift 21-cm signal", Monthly Notices of the Royal
Astronomical Society, Volume 411, Issue 2, pp. 955-972 (2011),
https://ui.adsabs.harvard.edu/link_gateway/2011MNRAS.411..955M/doi:10.1111/j.1365-2966.2010.17731.x
In addition, the following papers introduce various features into ``21cmFAST``. If you use
these features, please cite the relevant papers.
Mini-halos:
Muñoz, J.B., Qin, Y., Mesinger, A., Murray, S., Greig, B., and Mason, C.,
"The Impact of the First Galaxies on Cosmic Dawn and Reionization"
https://arxiv.org/abs/2110.13919
(for DM-baryon relative velocities)
Qin, Y., Mesinger, A., Park, J., Greig, B., and Muñoz, J. B.,
“A tale of two sites - I. Inferring the properties of minihalo-hosted galaxies from
current observations”, Monthly Notices of the Royal Astronomical Society, vol. 495,
no. 1, pp. 123–140, 2020. https://doi.org/10.1093/mnras/staa1131.
(for Lyman-Werner and first implementation)
Mass-dependent ionizing efficiency:
Park, J., Mesinger, A., Greig, B., and Gillet, N.,
“Inferring the astrophysics of reionization and cosmic dawn from galaxy luminosity
functions and the 21-cm signal”, Monthly Notices of the Royal Astronomical Society,
vol. 484, no. 1, pp. 933–949, 2019. https://doi.org/10.1093/mnras/stz032.
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/README.rst
|
README.rst
|
============
Contributing
============
Contributions are welcome, and they are greatly appreciated! Every
little bit helps, and credit will always be given.
Bug reports/Feature Requests/Feedback/Questions
===============================================
It is incredibly helpful to us when users report bugs, unexpected behaviour, or request
features. You can do the following:
* `Report a bug <https://github.com/21cmFAST/21cmFAST/issues/new?template=bug_report.md>`_
* `Request a Feature <https://github.com/21cmFAST/21cmFAST/issues/new?template=feature_request.md>`_
* `Ask a Question <https://github.com/21cmFAST/21cmFAST/issues/new?template=question.md>`_
When doing any of these, please try to be as succinct, but detailed, as possible, and use
a "Minimum Working Example" whenever applicable.
Documentation improvements
==========================
``21cmFAST`` could always use more documentation, whether as part of the
official ``21cmFAST`` docs, in docstrings, or even on the web in blog posts,
articles, and such. If you do the latter, take the time to let us know about it!
High-Level Steps for Development
================================
This is an abbreviated guide to getting started with development of ``21cmFAST``,
focusing on the discrete high-level steps to take. See our
`notes for developers <https://21cmfast.readthedocs.org/en/latest/notes_for_developers>`_
for more details about how to get around the ``21cmFAST`` codebase and other
technical details.
There are two avenues for you to develop ``21cmFAST``. If you plan on making significant
changes, and working with ``21cmFAST`` for a long period of time, please consider
becoming a member of the 21cmFAST GitHub organisation (by emailing any of the owners
or admins). You may develop as a member or as a non-member.
The difference between members and non-members only applies to the first step
of the development process.
Note that it is highly recommended to work in an isolated python environment with
all requirements installed from ``environment_dev.txt``. This will also ensure that
pre-commit hooks will run that enforce the ``black`` coding style. If you do not
install these requirements, you must manually run ``black`` before committing your changes,
otherwise your changes will likely fail continuous integration.
As a *member*:
1. Clone the repo::
git clone [email protected]:21cmFAST/21cmFAST.git
As a *non-member*:
1. First fork ``21cmFAST <https://github.com/21cmFAST/21cmFAST>``_
(look for the "Fork" button), then clone the fork locally::
git clone [email protected]:your_name_here/21cmFAST.git
The following steps are the same for both *members* and *non-members*:
2. Install a fresh new isolated environment::
conda create -n 21cmfast python=3
conda activate 21cmfast
3. Install the *development* requirements for the project::
conda env update -f environment_dev.yml
4. Install 21cmFAST. See `Installation <./installation.html>`_ for more details.::
pip install -e .
4. Install pre-commit hooks::
pre-commit install
5. Create a branch for local development::
git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally. **Note: as a member, you _must_ do step 5. If you
make changes on master, you will _not_ be able to push them**.
6. When you're done making changes, run ``pytest`` to check that your changes didn't
break things. You can run a single test or subset of tests as well (see pytest docs)::
pytest
7. Commit your changes and push your branch to GitHub::
git add .
git commit -m "Your detailed description of your changes."
git push origin name-of-your-bugfix-or-feature
Note that if the commit step fails due to a pre-commit hook, *most likely* the act
of running the hook itself has already fixed the error. Try doing the ``add`` and
``commit`` again (up, up, enter). If it's still complaining, manually fix the errors
and do the same again.
8. Submit a pull request through the GitHub website.
Pull Request Guidelines
-----------------------
If you need some code review or feedback while you're developing the code just make the
pull request. You can mark the PR as a draft until you are happy for it to be merged.
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/CONTRIBUTING.rst
|
CONTRIBUTING.rst
|
============
Installation
============
The easiest way to install ``21cmFAST`` is to use ``conda``. Simply use
``conda install -c conda-forge 21cmFAST``. With this method, all dependencies are taken
care of, and it should work on either Linux or MacOS. If for some reason this is not
possible for you, read on.
Dependencies
------------
We try to have as many of the dependencies automatically installed as possible.
However, since ``21cmFAST`` relies on some C libraries, this is not always possible.
The C libraries required are:
* ``gsl``
* ``fftw`` (compiled with floating-point enabled, and ``--enable-shared``)
* ``openmp``
* A C-compiler with compatibility with the ``-fopenmp`` flag. **Note:** it seems that on
OSX, if using ``gcc``, you will need ``v4.9.4+``.
As it turns out, though these are fairly common libraries, getting them installed in a
way that ``21cmFAST`` understands on various operating systems can be slightly non-trivial.
HPC
~~~
These libraries will often be available on a HPC environment by using the
``module load gsl`` and similar commands. Note that just because they are loaded
doesn't mean that ``21cmFAST`` will be able to find them. You may have to point to the
relevant ``lib/`` and ``include/`` folders for both ``gsl`` and ``fftw`` (these should
be available using ``module show gsl`` etc.)
Note also that while ``fftw`` may be available to load, it may not have the correct
compilation options (i.e. float-enabled and multiprocessing-enabled). In this case,
see below.
Linux
~~~~~
Most linux distros come with packages for the requirements, and also ``gcc`` by default,
which supports ``-fopenmp``. As long as these packages install into the standard location,
a standard installation of ``21cmFAST`` will be automatically possible (see below).
If they are installed to a place not on the ``LD_LIBRARY``/``INCLUDE`` paths, then you
must use the compilation options (see below) to specify where they are.
For example, you can check if the header file for ``fftw3`` is
in its default location ``/usr/include/`` by running::
cd /usr/include/
find fftw3.h
or::
locate fftw3.h
.. note:: there exists the option of installing ``gsl``, ``fftw`` and ``gcc`` using ``conda``.
This is discussed below in the context of MacOSX, where it is often the
easiest way to get the dependencies, but it is equally applicable to linux.
Ubuntu
^^^^^^
If you are installing 21cmFAST just as a user, the very simplest method is ``conda``
-- with this method you simply need ``conda install -c conda-forge 21cmFAST``, and all
dependencies will be automatically installed. However, if you are going to use
``pip`` to install the package directly from the repository, there is
a [bug in pip](https://stackoverflow.com/questions/71340058/conda-does-not-look-for-libpthread-and-libpthread-nonshared-at-the-right-place-w)
that means it cannot find conda-installed shared libraries properly. In that case, it is much
easier to install the basic dependencies (``gcc``, ``gsl`` and ``fftw3``) with your
system's package manager. ``gcc`` is by default available in Ubuntu.
To check if ``gcc`` is installed, run ``gcc --version`` in your terminal.
Install ``fftw3`` and ``gsl`` on your system with ``sudo apt-get install libfftw3-dev libgsl-dev``.
In your ``21cmfast`` environment, now install the ``21cmFAST`` package using::
cd /path/to/21cmFAST/
pip install .
If there is an issue during installation, add ``DEBUG=all`` or ``--DEBUG`` which may provide additional
information.
.. note:: If there is an error during compilation that the ``fftw3`` library cannot be found,
check where the ``fftw3`` library is actually located using ``locate libfftw3.so``.
For example, it may be located in ``/usr/lib/x86_64-linux-gnu/``. Then, provide this path
to the installation command with the ``LIB`` flag. For more details see the note in the
MacOSX section below.
.. note:: You may choose to install ``gsl`` as an anaconda package as well, however, in that case,
you need to add both ``INC`` paths in the installation command e.g.:
``GSL_INC=/path/to/conda/env/include FFTW_INC=/usr/include``
MacOSX
~~~~~~
On MacOSX, obtaining ``gsl`` and ``fftw`` is typically more difficult, and in addition,
the newer native ``clang`` does not offer ``-fopenmp`` support.
For ``conda`` users (which we recommend using), the easiest way to get ``gsl`` and ``fftw``
is by doing ``conda install -c conda-forge gsl fftw`` in your environment.
.. note:: if you use ``conda`` to install ``gsl`` and ``fftw``, then you will need to point at
their location when installing `21cmFAST` (see compiler options below for details).
In this case, the installation command should simply be *prepended* with::
LIB=/path/to/conda/env/lib INC=/path/to/conda/env/include
To get ``gcc``, either use ``homebrew``, or again, ``conda``: ``conda install -c anaconda gcc``.
If you get the ``conda`` version, you still need to install the headers::
xcode-select --install
On older versions then you need to do::
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_<input version>.pkg
.. note:: some versions of MacOS will also require you to point to the correct gcc
compiler using the ``CC`` environment variable. Overall, the point is to NOT
use ``clang``. If ``gcc --version`` shows that it is actually GCC, then you
can set ``CC=gcc``. If you use homebrew to install ``gcc``, it is likely that
you'll have to set ``CC=gcc-11``.
For newer versions, you may need to prepend the following command to your ``pip install`` command
when installing ``21cmFAST`` (see later instructions)::
CFLAGS="-isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX<input version>.sdk"
See `<faqs/installation_faq>`_ for more detailed questions on installation.
If you are on MacOSX and are having trouble with installation (or would like to share
a successful installation strategy!) please see the
`open issue <https://github.com/21cmfast/21cmFAST/issues/84>`_.
With the dependencies installed, follow the instructions below,
depending on whether you are a user or a developer.
For Users
---------
.. note:: ``conda`` users may want to pre-install the following packages before running
the below installation commands::
conda install numpy scipy click pyyaml cffi astropy h5py
Then, at the command line::
pip install git+https://github.com/21cmFAST/21cmFAST.git
If developing, from the top-level directory do::
pip install -e .
Note the compile options discussed below!
For Developers
--------------
If you are developing ``21cmFAST``, we highly recommend using ``conda`` to manage your
environment, and setting up an isolated environment. If this is the case, setting up
a full environment (with all testing and documentation dependencies) should be as easy
as (from top-level dir)::
conda env create -f environment_dev.yml
Otherwise, if you are using ``pip``::
pip install -e .[dev]
The ``[dev]`` "extra" here installs all development dependencies. You can instead use
``[tests]`` if you only want dependencies for testing, or ``[docs]`` to be able to
compile the documentation.
Compile Options
---------------
Various options exist to manage compilation via environment variables. Basically,
any variable with "INC" in its name will add to the includes directories, while
any variable with "lib" in its name will add to the directories searched for
libraries. To change the C compiler, use ``CC``. Finally, if you want to compile
the C-library in dev mode (so you can do stuff like valgrid and gdb with it),
install with DEBUG=True. So for example::
CC=/usr/bin/gcc DEBUG=True GSL_LIB=/opt/local/lib FFTW_INC=/usr/local/include pip install -e .
.. note:: For MacOS a typical installation command will look like
``CC=gcc CFLAGS="-isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX<input version>.sdk" pip install .``
(using either ``gcc`` or ``gcc-11`` depending on how you installed gcc), with
other compile options possible as well.
In addition, the ``BOXDIR`` variable specifies the *default* directory that any
data produced by 21cmFAST will be cached. This value can be updated at any time by
changing it in the ``$CFGDIR/config.yml`` file, and can be overwritten on a
per-call basis.
While the ``-e`` option will keep your library up-to-date with any (Python)
changes, this will *not* work when changing the C extension. If the C code
changes, you need to manually run ``rm -rf build/*`` then re-install as above.
Logging in C-Code
~~~~~~~~~~~~~~~~~
By default, the C-code will only print to stderr when it encounters warnings or
critical errors. However, there exist several levels of logging output that can be
switched on, but only at compilation time. To enable these, use the following::
LOG_LEVEL=<log_level> pip install -e .
The ``<log_level>`` can be any non-negative integer, or one of the following
(case-insensitive) identifiers::
NONE, ERROR, WARNING, INFO, DEBUG, SUPER_DEBUG, ULTRA_DEBUG
If an integer is passed, it corresponds to the above levels in order (starting
from zero). Be careful if the level is set to 0 (or NONE), as useful error
and warning messages will not be printed. By default, the log level is 2 (or
WARNING), unless the DEBUG=1 environment variable is set, in which case the
default is 4 (or DEBUG). Using very high levels (eg. ULTRA_DEBUG) can print out
*a lot* of information and make the run time much longer, but may be useful
in some specific cases.
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/INSTALLATION.rst
|
INSTALLATION.rst
|
#!/usr/bin/python
import sys
from datetime import datetime
if __name__ == "__main__":
newversion = sys.argv[1]
with open("CHANGELOG.rst", "r") as fl:
lines = fl.readlines()
for i, line in enumerate(lines):
if line == "dev-version\n":
break
else:
raise IOError("Couldn't Find 'dev-version' tag")
lines.insert(i + 2, "----------------------\n")
lines.insert(i + 2, f'v{newversion} [{datetime.now().strftime("%d %b %Y")}]\n')
lines.insert(i + 2, "\n")
with open("CHANGELOG.rst", "w") as fl:
fl.writelines(lines)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/changethelog.py
|
changethelog.py
|
Changelog
=========
dev-version
-----------
v3.3.1 [24 May 2023]
----------------------
Fixed
~~~~~
* Compilation of C code for some compilers (#330)
v3.3.0 [17 May 2023]
----------------------
Internals
~~~~~~~~~
* Refactored setting up of inputs to high-level functions so that there is less code
repetition.
Fixed
~~~~~
* Running with ``R_BUBBLE_MAX`` too large auto-fixes it to be ``BOX_LEN`` (#112)
* Bug in calling ``clear_cache``.
* Inconsistency in the way that the very highest redshift of an evolution is handled
between low-level code (eg. ``spin_temperature()``) and high-level code (eg. ``run_coeval()``).
Added
~~~~~
* New ``validate_all_inputs`` function that cross-references the four main input structs
and ensures all the parameters make sense together. Mostly for internal use.
* Ability to save/read directly from an open HDF5 File (#170)
* An implementation of cloud-in-cell to more accurately redistribute the perturbed mass
across all neighbouring cells instead of the previous nearest cell approach
* Changed PhotonConsEndCalibz from z = 5 -> z = 3.5 to handle later reionisation
scenarios in line with current observations (#305)
* Add in an initialisation check for the photon conservation to address some issues
arising for early EOR histories (#311)
* Added ``NON_CUBIC_FACTOR`` to ``UserParams`` to allow for non-cubic coeval boxes (#289)
v3.2.1 [13 Sep 2022]
----------------------
Changed
~~~~~~~
* Included log10_mturnovers(_mini) in lightcone class. Only useful when USE_MINI_HALOS
v3.2.0 [11 Jul 2022]
----------------------
Changed
~~~~~~~
* Floats are now represented to a specific number of significant digits in the hash of
an output object. This fixes problems with very close redshifts not being read from
cache (#80). Note that this means that very close astro/cosmo params will now be read
from cache. This could cause issues when creating large databases with many random
parameters. The behaviour can modified in the configuration by setting the
``cache_param_sigfigs`` and ``cache_redshift_sigfigs`` parameters (these are 6 and
4 by default, respectively).
**NOTE**: updating to this version will cause your previous cached files to become
unusable. Remove them before updating.
Fixed
~~~~~
* Added a missing C-based error to the known errors in Python.
v3.1.5 [27 Apr 2022]
----------------------
v3.1.4 [10 Feb 2022]
----------------------
Fixed
~~~~~
* error in FFT normalization in FindHaloes
* docs not compiling on RTD due to missing ``scipy.integrate`` mock module
* Updated matplotlib removed support for setting vmin/vmax and norm. Now passes vmin/vmax
to the norm() constructor.
v3.1.3 [27 Oct 2021]
----------------------
* Fixed ``FAST_FCOLL_TABLES`` so it only affects MCGs and not ACGs. Added tests of this
flag for high and low z separately.
v3.1.2 [14 Jul 2021]
----------------------
Internals
~~~~~~~~~
* ``MINIMIZE_MEMORY`` flag significantly reduces memory without affecting performance much,
by changing the way some arrays are allocated and accessed in C. (#224)
Change
~~~~~~
* Updated ``USE_INTERPOLATION_TABLES`` to be default True. This makes much more sense as
a default value. Until v4, a warning will be raised if it is not set explicitly.
v3.1.1 [13 Jun 2021]
----------------------
Fixed
~~~~~
* Bug in deployment to PyPI.
v3.1.0 [13 Jun 2021]
----------------------
Added
~~~~~
* Ability to access all evolutionary Coeval components, either from the end Coeval
class, or the Lightcone.
* Ability to gather all evolutionary antecedents from a Coeval/Lightcone into the one
file.
* ``FAST_FCOLL_TABLES`` in ``UserParams`` which improves speeds quite significantly for
~<10% accuracy decrease.
* Fast and low-memory generation of relative-velocity (vcb) initial conditions. Eliminated hi-res vcb boxes, as they are never needed.
* Also output the mean free path (i.e. MFP_box in IonizedBox).
* Added the effect of DM-baryon relative velocities on PopIII-forming minihaloes. This now provides the correct background evolution jointly with LW feedback. It gives rise to velocity-induced acoustic oscillations (VAOs) from the relative-velocity fluctuations. We also follow a more flexible parametrization for LW feedback in minihaloes, following new simulation results, and add a new index ALPHA_STAR_MINI for minihaloes, now independent of regular ACGs.
* New ``hooks`` keyword to high-level functions, that are run on the completion of each computational step, and can
be used to more generically write parts of the data to file.
* Ability to pass a function to ``write=`` to write more specific aspects of the data (internally, this will be put into the ``hooks`` dictionary).
* ``run_lightcone`` and ``run_coeval`` use significantly less memory by offloading initial conditions and perturb_field instances to disk if possible.
Fixed
~~~~~
* Bug in 2LPT when ``USE_RELATIVE_VELOCITIES=True`` [Issue #191, PR #192]
* Error raised when redshifts are not in ascending order [Issue #176, PR #177]
* Errors when ``USE_FFTW_WISDOM`` is used on some systems [Issue #174, PR #199]
* Bug in ComputeIonizedBox causing negative recombination rate and ring structure in ``Gamma12_box`` [Issue #194, PR #210]
* Error in determining the wisdom file name [Issue #209, PR#210]
* Bug in which cached C-based memory would be read in and free'd twice.
Internals
~~~~~~~~~
* Added ``dft.c``, which makes doing all the cubic FFTs a lot easier and more consistent. [PR #199]
* More generic way of keeping track of arrays to be passed between C and Python, and their shape in Python, using ``_get_box_structures``.
This also means that the various boxes can be queried before they are initialized and computed.
* More stringent integration tests that test each array, not just the final brightness temperature.
* Ability to plot the integration test data to more easily identify where things have gone wrong (use ``--plots`` in the ``pytest`` invocation).
* Nicer CLI interface for ``produce_integration_test_data.py``. New options to ``clean`` the ``test_data/`` directory,
and also test data is saved by user-defined key rather than massive string of variables.
* Nicer debug statements before calls to C, for easily comparing between versions.
* Much nicer methods of keeping track of array state (in memory, on disk, c-controlled, etc.)
* Ability to free C-based pointers in a more granular way.
v3.0.3
------
Added
~~~~~
* ``coeval_callback`` and ``coeval_callback_redshifts`` flags to the ``run_lightcone``.
Gives the ability to run arbitrary code on ``Coeval`` boxes.
* JOSS paper!
* ``get_fields`` classmethod on all output classes, so that one can easily figure out
what fields are computed (and available) for that class.
Fixed
~~~~~
* Only raise error on non-available ``external_table_path`` when actually going to use it.
v3.0.2
------
Fixed
-----
* Added prototype functions to enable compilation for some standard compilers on MacOS.
v3.0.1
------
Modifications to the internal code structure of 21cmFAST
Added
~~~~~
* Refactor FFTW wisdom creation to be a python callable function
v3.0.0
------
Complete overhaul of 21cmFAST, including a robust python-wrapper and interface,
caching mechanisms, and public repository with continuous integration. Changes
and equations for minihalo features in this version are found in
https://arxiv.org/abs/2003.04442
All functionality of the original 21cmFAST v2 C-code has been implemented in this
version, including ``USE_HALO_FIELD`` and performing full integration instead of using
the interpolation tables (which are faster).
Added
~~~~~
* Updated the radiation source model: (i) all radiation fields including X-rays, UV
ionizing, Lyman Werner and Lyman alpha are considered from two seperated population
namely atomic-cooling (ACGs) and minihalo-hosted molecular-cooling galaxies (MCGs);
(ii) the turn-over masses of ACGs and MCGs are estimated with cooling efficiency and
feedback from reionization and lyman werner suppression (Qin et al. 2020). This can
be switched on using new ``flag_options`` ``USE_MINI_HALOS``.
* Updated kinetic temperature of the IGM with fully ionized cells following equation 6
of McQuinn (2015) and partially ionized cells having the volume-weightied temperature
between the ionized (volume: 1-xHI; temperature T_RE ) and neutral components (volume:
xHI; temperature: temperature of HI). This is stored in IonizedBox as
temp_kinetic_all_gas. Note that Tk in TsBox remains to be the kinetic temperature of HI.
* Tests: many unit tests, and also some regression tests.
* CLI: run 21cmFAST boxes from the command line, query the cache database, and produce
plots for standard comparison runs.
* Documentation: Jupyter notebook demos and tutorials, FAQs, installation instructions.
* Plotting routines: a number of general plotting routines designed to plot coeval
and lightcone slices.
* New power spectrum option (``POWER_SPECTRUM=5``) that uses a CLASS-based transfer
function. WARNING: If POWER_SPECTRUM==5 the cosmo parameters cannot be altered, they
are set to the Planck2018 best-fit values for now (until CLASS is added):
(omegab=0.02237, omegac= 0.120, hubble=0.6736 (the rest are irrelevant for the
transfer functions, but in case: A_s=2.100e-9, n_s=0.9649, z_reio = 11.357)
* New ``user_params`` option ``USE_RELATIVE_VELOCITIES``, which produces initial relative
velocity cubes (option implemented, but not the actual computation yet).
* Configuration management.
* global params now has a context manager for changing parameters temporarily.
* Vastly improved error handling: exceptions can be caught in C code and propagated to
Python to inform the user of what's going wrong.
* Ability to write high-level data (``Coeval`` and ``Lightcone`` objects) directly to
file in a simple portable format.
Changed
~~~~~~~
* ``POWER_SPECTRUM`` option moved from ``global_params`` to ``user_params``.
* Default cosmology updated to Planck18.
v2.0.0
------
All changes and equations for this version are found in https://arxiv.org/abs/1809.08995.
Changed
~~~~~~~
* Updated the ionizing source model: (i) the star formation rates and ionizing escape
fraction are scaled with the masses of dark matter halos and (ii) the abundance of
active star forming galaxies is exponentially suppressed below the turn-over halo
mass, M_{turn}, according to a duty cycle of exp(−M_{turn}/M_{h}), where M_{h} is a
halo mass.
* Removed the mean free path parameter, R_{mfp}. Instead, directly computes
inhomogeneous, sub-grid recombinations in the intergalactic medium following the
approach of Sobacchi & Mesinger (2014)
v1.2.0
------
Added
~~~~~
* Support for a halo mass dependent ionizing efficiency: zeta = zeta_0 (M/Mmin)^alpha,
where zeta_0 corresponds to HII_EFF_FACTOR, Mmin --> ION_M_MIN,
alpha --> EFF_FACTOR_PL_INDEX in ANAL_PARAMS.H
v1.12.0
-------
Added
~~~~~
- Code 'redshift_interpolate_boxes.c' to interpolate between comoving cubes,
creating comoving light cone boxes.
- Enabled openMP threading for SMP machines. You can specify the number of threads
(for best performace, do not exceed the number of processors) in INIT_PARAMS.H. You do
not need to have an SMP machine to run the code. NOTE: YOU SHOULD RE-INSTALL FFTW to
use openMP (see INSTALL file)
- Included a threaded driver file 'drive_zscroll_reion_param.c' set-up to perform
astrophysical parameter studies of reionization
- Included explicit support for WDM cosmologies; see COSMOLOGY.H. The prescription is
similar to that discussed in Barkana+2001; Mesinger+2005, madifying the (i) transfer
function (according to the Bode+2001 formula; and (ii) including the effective
pressure term of WDM using a Jeans mass analogy. (ii) is approximated with a sharp
cuttoff in the EPS barrier, using 60* M_J found in Barkana+2001 (the 60 is an
adjustment factor found by fitting to the WDM collapsed fraction).
- A Gaussian filtering step of the PT fields to perturb_field.c, in addition to the
implicit boxcar smoothing. This avoids having"empty" density cells, i.e. \delta=-1,
with some small loss in resolution. Although for most uses \delta=-1 is ok, some Lya
forest statistics do not like it.
- Added treatment of the risidual electron fraction from X-ray heating when computing
the ionization field. Relatedly, modified Ts.c to output all intermediate evolution
boxes, Tk and x_e.
- Added a missing factor of Omega_b in Ts.c corresponding to eq. 18 in MFC11. Users who
used a previous version should note that their results just effecively correspond to a
higher effective X-ray efficiency, scaled by 1/Omega_baryon.
- Normalization optimization to Ts.c, increasing performace on arge resolution boxes
Fixed
~~~~~
- GSL interpolation error in kappa_elec_pH for GSL versions > 1.15
- Typo in macro definition, which impacted the Lya background calculation in v1.11 (not applicable to earlier releases)
- Outdated filename sytax when calling gen_size_distr in drive_xHIscroll
- Redshift scrolling so that drive_logZscroll_Ts.c and Ts.c are in sync.
Changed
~~~~~~~
- Output format to avoid FFT padding for all boxes
- Filename conventions to be more explicit.
- Small changes to organization and structure
v1.1.0
------
Added
~~~~~
- Wrapper functions mod_fwrite() and mod_fread() in Cosmo_c_progs/misc.c, which
should fix problems with the library fwrite() and fread() for large files (>4GB) on
certain operating systems.
- Included print_power_spectrum_ICs.c program which reads in high resolution initial
conditions and prints out an ASCII file with the associated power spectrum.
- Parameter in Ts.c for the maximum allowed kinetic temperature, which increases
stability of the code when the redshift step size and the X-ray efficiencies are large.
Fixed
~~~~~
- Oversight adding support for a Gaussian filter for the lower resolution field.
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/CHANGELOG.rst
|
CHANGELOG.rst
|
"""Build the C code with CFFI."""
import os
from cffi import FFI
ffi = FFI()
LOCATION = os.path.dirname(os.path.abspath(__file__))
CLOC = os.path.join(LOCATION, "src", "py21cmfast", "src")
include_dirs = [CLOC]
# =================================================================
# Set compilation arguments dependent on environment... a bit buggy
# =================================================================
if "DEBUG" in os.environ:
extra_compile_args = ["-fopenmp", "-w", "-g", "-O0", "--verbose"]
else:
extra_compile_args = ["-fopenmp", "-Ofast", "-w", "--verbose"]
# Set the C-code logging level.
# If DEBUG is set, we default to the highest level, but if not,
# we set it to the level just above no logging at all.
log_level = os.environ.get("LOG_LEVEL", 4 if "DEBUG" in os.environ else 1)
available_levels = [
"NONE",
"ERROR",
"WARNING",
"INFO",
"DEBUG",
"SUPER_DEBUG",
"ULTRA_DEBUG",
]
if isinstance(log_level, str) and log_level.upper() in available_levels:
log_level = available_levels.index(log_level.upper())
try:
log_level = int(log_level)
except ValueError:
# note: for py35 support, can't use f strings.
raise ValueError(
"LOG_LEVEL must be specified as a positive integer, or one "
"of {}".format(available_levels)
)
library_dirs = []
for k, v in os.environ.items():
if "inc" in k.lower():
include_dirs += [v]
elif "lib" in k.lower():
library_dirs += [v]
# =================================================================
# This is the overall C code.
ffi.set_source(
"py21cmfast.c_21cmfast", # Name/Location of shared library module
"""
#define LOG_LEVEL {log_level}
#include "GenerateICs.c"
""".format(
log_level=log_level
),
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=["m", "gsl", "gslcblas", "fftw3f_omp", "fftw3f"],
extra_compile_args=extra_compile_args,
)
# This is the Header file
with open(os.path.join(CLOC, "21cmFAST.h")) as f:
ffi.cdef(f.read())
with open(os.path.join(CLOC, "Globals.h")) as f:
ffi.cdef(f.read())
if __name__ == "__main__":
ffi.compile()
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/build_cffi.py
|
build_cffi.py
|
=======
Authors
=======
* Brad Greig - github.com/BradGreig
* Andrei Mesinger - github.com/andreimesinger
* Steven Murray - github.com/steven-murray
Contributors
============
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/AUTHORS.rst
|
AUTHORS.rst
|
#!/usr/bin/env python
"""Setup the package."""
from setuptools import find_packages, setup
import glob
import io
import os
import re
import shutil
from os.path import dirname, expanduser, join
def _read(*names, **kwargs):
return open(
join(dirname(__file__), *names), encoding=kwargs.get("encoding", "utf8")
).read()
pkgdir = os.path.dirname(os.path.abspath(__file__))
# Enable code coverage for C code: we can't use CFLAGS=-coverage in tox.ini, since that
# may mess with compiling dependencies (e.g. numpy). Therefore we set SETUPPY_
# CFLAGS=-coverage in tox.ini and copy it to CFLAGS here (after deps have been safely installed).
if "TOXENV" in os.environ and "SETUPPY_CFLAGS" in os.environ:
os.environ["CFLAGS"] = os.environ["SETUPPY_CFLAGS"]
test_req = [
"pre-commit",
"pytest>=5.0",
"pytest-cov",
"tox",
"pytest-remotedata>=0.3.2",
"powerbox",
"pytest-plt",
"questionary",
]
doc_req = ["nbsphinx", "numpydoc", "sphinx >= 1.3", "sphinx-rtd-theme"]
setup(
name="21cmFAST",
license="MIT license",
description="A semi-numerical cosmological simulation code for the 21cm signal",
long_description="%s\n%s"
% (
re.compile("^.. start-badges.*^.. end-badges", re.M | re.S).sub(
"", _read("README.rst")
),
re.sub(":[a-z]+:`~?(.*?)`", r"``\1``", _read("CHANGELOG.rst")),
),
author="The 21cmFAST coredev team",
author_email="[email protected]",
url="https://github.com/21cmFAST/21cmFAST",
packages=find_packages("src"),
package_dir={"": "src"},
include_package_data=True,
zip_safe=False,
classifiers=[
# complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: Unix",
"Operating System :: POSIX",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: Implementation :: CPython",
],
keywords=["Epoch of Reionization", "Cosmology"],
install_requires=[
"click",
"numpy",
"pyyaml",
"cffi>=1.0",
"scipy",
"astropy>=2.0",
"h5py>=2.8.0",
"cached_property",
"matplotlib",
"bidict",
],
extras_require={"tests": test_req, "docs": doc_req, "dev": test_req + doc_req},
setup_requires=["cffi>=1.0", "setuptools_scm"],
entry_points={"console_scripts": ["21cmfast = py21cmfast.cli:main"]},
cffi_modules=[f"{pkgdir}/build_cffi.py:ffi"],
use_scm_version={
"write_to": "src/py21cmfast/_version.py",
"parentdir_prefix_version": "21cmFAST-",
"fallback_version": "0.0.0",
},
)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/setup.py
|
setup.py
|
"""Configure logging for py21cmfast.
Significantly, adds a new formatter which prepends the PID of the logging process to
any output. This is helpful when running multiple threads in MPI.
"""
import logging
import sys
from multiprocessing import current_process
class PIDFormatter(logging.Formatter):
"""Logging formatter which prepends the PID of the logging process to any output."""
_mylogger = logging.getLogger("21cmFAST") # really bad hack
def format(self, record): # noqa
"""Set the format of the log."""
fmt = "{asctime} | {levelname} |"
if self._mylogger.level <= logging.DEBUG:
fmt += " {filename}::{funcName}() |"
if current_process().name != "MainProcess":
fmt += " pid={process} |"
self._style = logging.StrFormatStyle(fmt + " {message}")
return logging.Formatter.format(self, record)
def configure_logging():
"""Configure logging for the '21cmFAST' logger."""
hdlr = logging.StreamHandler(sys.stderr)
hdlr.setFormatter(PIDFormatter())
logger = logging.getLogger("21cmFAST")
logger.addHandler(hdlr)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/_logging.py
|
_logging.py
|
"""
The main wrapper for the underlying 21cmFAST C-code.
The module provides both low- and high-level wrappers, using the very low-level machinery
in :mod:`~py21cmfast._utils`, and the convenient input and output structures from
:mod:`~py21cmfast.inputs` and :mod:`~py21cmfast.outputs`.
This module provides a number of:
* Low-level functions which simplify calling the background C functions which populate
these output objects given the input classes.
* High-level functions which provide the most efficient and simplest way to generate the
most commonly desired outputs.
**Low-level functions**
The low-level functions provided here ease the production of the aforementioned output
objects. Functions exist for each low-level C routine, which have been decoupled as far
as possible. So, functions exist to create :func:`initial_conditions`,
:func:`perturb_field`, :class:`ionize_box` and so on. Creating a brightness temperature
box (often the desired final output) would generally require calling each of these in
turn, as each depends on the result of a previous function. Nevertheless, each function
has the capability of generating the required previous outputs on-the-fly, so one can
instantly call :func:`ionize_box` and get a self-consistent result. Doing so, while
convenient, is sometimes not *efficient*, especially when using inhomogeneous
recombinations or the spin temperature field, which intrinsically require consistent
evolution of the ionization field through redshift. In these cases, for best efficiency
it is recommended to either use a customised manual approach to calling these low-level
functions, or to call a higher-level function which optimizes this process.
Finally, note that :mod:`py21cmfast` attempts to optimize the production of the large amount of
data via on-disk caching. By default, if a previous set of data has been computed using
the current input parameters, it will be read-in from a caching repository and returned
directly. This behaviour can be tuned in any of the low-level (or high-level) functions
by setting the `write`, `direc`, `regenerate` and `match_seed` parameters (see docs for
:func:`initial_conditions` for details). The function :func:`~query_cache` can be used
to search the cache, and return empty datasets corresponding to each (and these can then be
filled with the data merely by calling ``.read()`` on any data set). Conversely, a
specific data set can be read and returned as a proper output object by calling the
:func:`~py21cmfast.cache_tools.readbox` function.
**High-level functions**
As previously mentioned, calling the low-level functions in some cases is non-optimal,
especially when full evolution of the field is required, and thus iteration through a
series of redshift. In addition, while :class:`InitialConditions` and
:class:`PerturbedField` are necessary intermediate data, it is *usually* the resulting
brightness temperature which is of most interest, and it is easier to not have to worry
about the intermediate steps explicitly. For these typical use-cases, two high-level
functions are available: :func:`run_coeval` and :func:`run_lightcone`, whose purpose
should be self-explanatory. These will optimally run all necessary intermediate
steps (using cached results by default if possible) and return all datasets of interest.
Examples
--------
A typical example of using this module would be the following.
>>> import py21cmfast as p21
Get coeval cubes at redshift 7,8 and 9, without spin temperature or inhomogeneous
recombinations:
>>> coeval = p21.run_coeval(
>>> redshift=[7,8,9],
>>> cosmo_params=p21.CosmoParams(hlittle=0.7),
>>> user_params=p21.UserParams(HII_DIM=100)
>>> )
Get coeval cubes at the same redshift, with both spin temperature and inhomogeneous
recombinations, pulled from the natural evolution of the fields:
>>> all_boxes = p21.run_coeval(
>>> redshift=[7,8,9],
>>> user_params=p21.UserParams(HII_DIM=100),
>>> flag_options=p21.FlagOptions(INHOMO_RECO=True),
>>> do_spin_temp=True
>>> )
Get a self-consistent lightcone defined between z1 and z2 (`z_step_factor` changes the
logarithmic steps between redshift that are actually evaluated, which are then
interpolated onto the lightcone cells):
>>> lightcone = p21.run_lightcone(redshift=z2, max_redshift=z2, z_step_factor=1.03)
"""
from __future__ import annotations
import logging
import numpy as np
import os
import warnings
from astropy import units
from astropy.cosmology import z_at_value
from copy import deepcopy
from scipy.interpolate import interp1d
from typing import Any, Callable, Sequence
from ._cfg import config
from ._utils import OutputStruct, _check_compatible_inputs, _process_exitcode
from .c_21cmfast import ffi, lib
from .inputs import (
AstroParams,
CosmoParams,
FlagOptions,
UserParams,
global_params,
validate_all_inputs,
)
from .outputs import (
BrightnessTemp,
Coeval,
HaloField,
InitialConditions,
IonizedBox,
LightCone,
PerturbedField,
PerturbHaloField,
TsBox,
_OutputStructZ,
)
logger = logging.getLogger(__name__)
def _configure_inputs(
defaults: list,
*datasets,
ignore: list = ["redshift"],
flag_none: list | None = None,
):
"""Configure a set of input parameter structs.
This is useful for basing parameters on a previous output.
The logic is this: the struct _cannot_ be present and different in both defaults and
a dataset. If it is present in _either_ of them, that will be returned. If it is
present in _neither_, either an error will be raised (if that item is in `flag_none`)
or it will pass.
Parameters
----------
defaults : list of 2-tuples
Each tuple is (key, val). Keys are input struct names, and values are a default
structure for that input.
datasets : list of :class:`~_utils.OutputStruct`
A number of output datasets to cross-check, and draw parameter values from.
ignore : list of str
Attributes to ignore when ensuring that parameter inputs are the same.
flag_none : list
A list of parameter names for which ``None`` is not an acceptable value.
Raises
------
ValueError :
If an input parameter is present in both defaults and the dataset, and is different.
OR if the parameter is present in neither defaults not the datasets, and it is
included in `flag_none`.
"""
# First ensure all inputs are compatible in their parameters
_check_compatible_inputs(*datasets, ignore=ignore)
if flag_none is None:
flag_none = []
output = [0] * len(defaults)
for i, (key, val) in enumerate(defaults):
# Get the value of this input from the datasets
data_val = None
for dataset in datasets:
if dataset is not None and hasattr(dataset, key):
data_val = getattr(dataset, key)
break
# If both data and default have values
if not (val is None or data_val is None or data_val == val):
raise ValueError(
"%s has an inconsistent value with %s"
% (key, dataset.__class__.__name__)
)
else:
if val is not None:
output[i] = val
elif data_val is not None:
output[i] = data_val
elif key in flag_none:
raise ValueError(
"For %s, a value must be provided in some manner" % key
)
else:
output[i] = None
return output
def configure_redshift(redshift, *structs):
"""
Check and obtain a redshift from given default and structs.
Parameters
----------
redshift : float
The default redshift to use
structs : list of :class:`~_utils.OutputStruct`
A number of output datasets from which to find the redshift.
Raises
------
ValueError :
If both `redshift` and *all* structs have a value of `None`, **or** if any of them
are different from each other (and not `None`).
"""
zs = {s.redshift for s in structs if s is not None and hasattr(s, "redshift")}
zs = list(zs)
if len(zs) > 1 or (len(zs) == 1 and redshift is not None and zs[0] != redshift):
raise ValueError("Incompatible redshifts in inputs")
elif len(zs) == 1:
return zs[0]
elif redshift is None:
raise ValueError(
"Either redshift must be provided, or a data set containing it."
)
else:
return redshift
def _verify_types(**kwargs):
"""Ensure each argument has a type of None or that matching its name."""
for k, v in kwargs.items():
for j, kk in enumerate(
["init", "perturb", "ionize", "spin_temp", "halo_field", "pt_halos"]
):
if kk in k:
break
cls = [
InitialConditions,
PerturbedField,
IonizedBox,
TsBox,
HaloField,
PerturbHaloField,
][j]
if v is not None and not isinstance(v, cls):
raise ValueError(f"{k} must be an instance of {cls.__name__}")
def _setup_inputs(
input_params: dict[str, Any],
input_boxes: dict[str, OutputStruct] | None = None,
redshift=-1,
):
"""
Verify and set up input parameters to any function that runs C code.
Parameters
----------
input_boxes
A dictionary of OutputStruct objects that are meant as inputs to the current
calculation. These will be verified against each other, and also used to
determine redshift, if appropriate.
input_params
A dictionary of keys and dicts / input structs. This should have the random
seed, cosmo/user params and optionally the flag and astro params.
redshift
Optional value of the redshift. Can be None. If not provided, no redshift is
returned.
Returns
-------
random_seed
The random seed to use, determined from either explicit input or input boxes.
input_params
The configured input parameter structs, in the order in which they were given.
redshift
If redshift is given, it will also be output.
"""
input_boxes = input_boxes or {}
if "flag_options" in input_params and "user_params" not in input_params:
raise ValueError("To set flag_options requires user_params")
if "astro_params" in input_params and "flag_options" not in input_params:
raise ValueError("To set astro_params requires flag_options")
if input_boxes:
_verify_types(**input_boxes)
params = _configure_inputs(list(input_params.items()), *list(input_boxes.values()))
if redshift != -1:
redshift = configure_redshift(
redshift,
*[
v
for k, v in input_boxes.items()
if hasattr(v, "redshift") and "prev" not in k
],
)
# This turns params into a dict with all the input parameters in it.
params = dict(zip(input_params.keys(), params))
params["user_params"] = UserParams(params["user_params"])
params["cosmo_params"] = CosmoParams(params["cosmo_params"])
if "flag_options" in params:
params["flag_options"] = FlagOptions(
params["flag_options"],
USE_VELS_AUX=params["user_params"].USE_RELATIVE_VELOCITIES,
)
if "astro_params" in params:
params["astro_params"] = AstroParams(
params["astro_params"], INHOMO_RECO=params["flag_options"].INHOMO_RECO
)
# Perform validation between different sets of inputs.
validate_all_inputs(**{k: v for k, v in params.items() if k != "random_seed"})
# Sort the params back into input order.
params = [params[k] for k in input_params]
out = params
if redshift != -1:
out.append(redshift)
return out
def _call_c_simple(fnc, *args):
"""Call a simple C function that just returns an object.
Any such function should be defined such that the last argument is an int pointer generating
the status.
"""
# Parse the function to get the type of the last argument
cdata = str(ffi.addressof(lib, fnc.__name__))
kind = cdata.split("(")[-1].split(")")[0].split(",")[-1]
result = ffi.new(kind)
status = fnc(*args, result)
_process_exitcode(status, fnc, args)
return result[0]
def _get_config_options(
direc, regenerate, write, hooks
) -> tuple[str, bool, dict[Callable, dict[str, Any]]]:
direc = str(os.path.expanduser(config["direc"] if direc is None else direc))
if hooks is None or len(hooks) > 0:
hooks = hooks or {}
if callable(write) and write not in hooks:
hooks[write] = {"direc": direc}
if not hooks:
if write is None:
write = config["write"]
if not callable(write) and write:
hooks["write"] = {"direc": direc}
return (
direc,
bool(config["regenerate"] if regenerate is None else regenerate),
hooks,
)
def get_all_fieldnames(
arrays_only=True, lightcone_only=False, as_dict=False
) -> dict[str, str] | set[str]:
"""Return all possible fieldnames in output structs.
Parameters
----------
arrays_only : bool, optional
Whether to only return fields that are arrays.
lightcone_only : bool, optional
Whether to only return fields from classes that evolve with redshift.
as_dict : bool, optional
Whether to return results as a dictionary of ``quantity: class_name``.
Otherwise returns a set of quantities.
"""
classes = [cls(redshift=0) for cls in _OutputStructZ._implementations()]
if not lightcone_only:
classes.append(InitialConditions())
attr = "pointer_fields" if arrays_only else "fieldnames"
if as_dict:
return {
name: cls.__class__.__name__
for cls in classes
for name in getattr(cls, attr)
}
else:
return {name for cls in classes for name in getattr(cls, attr)}
# ======================================================================================
# WRAPPING FUNCTIONS
# ======================================================================================
def construct_fftw_wisdoms(*, user_params=None, cosmo_params=None):
"""Construct all necessary FFTW wisdoms.
Parameters
----------
user_params : :class:`~inputs.UserParams`
Parameters defining the simulation run.
"""
user_params = UserParams(user_params)
cosmo_params = CosmoParams(cosmo_params)
# Run the C code
if user_params.USE_FFTW_WISDOM:
return lib.CreateFFTWWisdoms(user_params(), cosmo_params())
else:
return 0
def compute_tau(*, redshifts, global_xHI, user_params=None, cosmo_params=None):
"""Compute the optical depth to reionization under the given model.
Parameters
----------
redshifts : array-like
Redshifts defining an evolution of the neutral fraction.
global_xHI : array-like
The mean neutral fraction at `redshifts`.
user_params : :class:`~inputs.UserParams`
Parameters defining the simulation run.
cosmo_params : :class:`~inputs.CosmoParams`
Cosmological parameters.
Returns
-------
tau : float
The optional depth to reionization
Raises
------
ValueError :
If `redshifts` and `global_xHI` have inconsistent length or if redshifts are not
in ascending order.
"""
user_params, cosmo_params = _setup_inputs(
{"user_params": user_params, "cosmo_params": cosmo_params}
)
if len(redshifts) != len(global_xHI):
raise ValueError("redshifts and global_xHI must have same length")
if not np.all(np.diff(redshifts) > 0):
raise ValueError("redshifts and global_xHI must be in ascending order")
# Convert the data to the right type
redshifts = np.array(redshifts, dtype="float32")
global_xHI = np.array(global_xHI, dtype="float32")
z = ffi.cast("float *", ffi.from_buffer(redshifts))
xHI = ffi.cast("float *", ffi.from_buffer(global_xHI))
# Run the C code
return lib.ComputeTau(user_params(), cosmo_params(), len(redshifts), z, xHI)
def compute_luminosity_function(
*,
redshifts,
user_params=None,
cosmo_params=None,
astro_params=None,
flag_options=None,
nbins=100,
mturnovers=None,
mturnovers_mini=None,
component=0,
):
"""Compute a the luminosity function over a given number of bins and redshifts.
Parameters
----------
redshifts : array-like
The redshifts at which to compute the luminosity function.
user_params : :class:`~UserParams`, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
astro_params : :class:`~AstroParams`, optional
The astrophysical parameters defining the course of reionization.
flag_options : :class:`~FlagOptions`, optional
Some options passed to the reionization routine.
nbins : int, optional
The number of luminosity bins to produce for the luminosity function.
mturnovers : array-like, optional
The turnover mass at each redshift for massive halos (ACGs).
Only required when USE_MINI_HALOS is True.
mturnovers_mini : array-like, optional
The turnover mass at each redshift for minihalos (MCGs).
Only required when USE_MINI_HALOS is True.
component : int, optional
The component of the LF to be calculated. 0, 1 an 2 are for the total,
ACG and MCG LFs respectively, requiring inputs of both mturnovers and
mturnovers_MINI (0), only mturnovers (1) or mturnovers_MINI (2).
Returns
-------
Muvfunc : np.ndarray
Magnitude array (i.e. brightness). Shape [nredshifts, nbins]
Mhfunc : np.ndarray
Halo mass array. Shape [nredshifts, nbins]
lfunc : np.ndarray
Number density of haloes corresponding to each bin defined by `Muvfunc`.
Shape [nredshifts, nbins].
"""
user_params, cosmo_params, astro_params, flag_options = _setup_inputs(
{
"user_params": user_params,
"cosmo_params": cosmo_params,
"astro_params": astro_params,
"flag_options": flag_options,
}
)
redshifts = np.array(redshifts, dtype="float32")
if flag_options.USE_MINI_HALOS:
if component in [0, 1]:
if mturnovers is None:
logger.warning(
"calculating ACG LFs with mini-halo feature requires users to "
"specify mturnovers!"
)
return None, None, None
mturnovers = np.array(mturnovers, dtype="float32")
if len(mturnovers) != len(redshifts):
logger.warning(
"mturnovers(%d) does not match the length of redshifts (%d)"
% (len(mturnovers), len(redshifts))
)
return None, None, None
if component in [0, 2]:
if mturnovers_mini is None:
logger.warning(
"calculating MCG LFs with mini-halo feature requires users to "
"specify mturnovers_MINI!"
)
return None, None, None
mturnovers_mini = np.array(mturnovers_mini, dtype="float32")
if len(mturnovers_mini) != len(redshifts):
logger.warning(
"mturnovers_MINI(%d) does not match the length of redshifts (%d)"
% (len(mturnovers), len(redshifts))
)
return None, None, None
else:
mturnovers = (
np.zeros(len(redshifts), dtype="float32") + 10**astro_params.M_TURN
)
component = 1
if component == 0:
lfunc = np.zeros(len(redshifts) * nbins)
Muvfunc = np.zeros(len(redshifts) * nbins)
Mhfunc = np.zeros(len(redshifts) * nbins)
lfunc.shape = (len(redshifts), nbins)
Muvfunc.shape = (len(redshifts), nbins)
Mhfunc.shape = (len(redshifts), nbins)
c_Muvfunc = ffi.cast("double *", ffi.from_buffer(Muvfunc))
c_Mhfunc = ffi.cast("double *", ffi.from_buffer(Mhfunc))
c_lfunc = ffi.cast("double *", ffi.from_buffer(lfunc))
# Run the C code
errcode = lib.ComputeLF(
nbins,
user_params(),
cosmo_params(),
astro_params(),
flag_options(),
1,
len(redshifts),
ffi.cast("float *", ffi.from_buffer(redshifts)),
ffi.cast("float *", ffi.from_buffer(mturnovers)),
c_Muvfunc,
c_Mhfunc,
c_lfunc,
)
_process_exitcode(
errcode,
lib.ComputeLF,
(
nbins,
user_params,
cosmo_params,
astro_params,
flag_options,
1,
len(redshifts),
),
)
lfunc_MINI = np.zeros(len(redshifts) * nbins)
Muvfunc_MINI = np.zeros(len(redshifts) * nbins)
Mhfunc_MINI = np.zeros(len(redshifts) * nbins)
lfunc_MINI.shape = (len(redshifts), nbins)
Muvfunc_MINI.shape = (len(redshifts), nbins)
Mhfunc_MINI.shape = (len(redshifts), nbins)
c_Muvfunc_MINI = ffi.cast("double *", ffi.from_buffer(Muvfunc_MINI))
c_Mhfunc_MINI = ffi.cast("double *", ffi.from_buffer(Mhfunc_MINI))
c_lfunc_MINI = ffi.cast("double *", ffi.from_buffer(lfunc_MINI))
# Run the C code
errcode = lib.ComputeLF(
nbins,
user_params(),
cosmo_params(),
astro_params(),
flag_options(),
2,
len(redshifts),
ffi.cast("float *", ffi.from_buffer(redshifts)),
ffi.cast("float *", ffi.from_buffer(mturnovers_mini)),
c_Muvfunc_MINI,
c_Mhfunc_MINI,
c_lfunc_MINI,
)
_process_exitcode(
errcode,
lib.ComputeLF,
(
nbins,
user_params,
cosmo_params,
astro_params,
flag_options,
2,
len(redshifts),
),
)
# redo the Muv range using the faintest (most likely MINI) and the brightest (most likely massive)
lfunc_all = np.zeros(len(redshifts) * nbins)
Muvfunc_all = np.zeros(len(redshifts) * nbins)
Mhfunc_all = np.zeros(len(redshifts) * nbins * 2)
lfunc_all.shape = (len(redshifts), nbins)
Muvfunc_all.shape = (len(redshifts), nbins)
Mhfunc_all.shape = (len(redshifts), nbins, 2)
for iz in range(len(redshifts)):
Muvfunc_all[iz] = np.linspace(
np.min([Muvfunc.min(), Muvfunc_MINI.min()]),
np.max([Muvfunc.max(), Muvfunc_MINI.max()]),
nbins,
)
lfunc_all[iz] = np.log10(
10
** (
interp1d(Muvfunc[iz], lfunc[iz], fill_value="extrapolate")(
Muvfunc_all[iz]
)
)
+ 10
** (
interp1d(
Muvfunc_MINI[iz], lfunc_MINI[iz], fill_value="extrapolate"
)(Muvfunc_all[iz])
)
)
Mhfunc_all[iz] = np.array(
[
interp1d(Muvfunc[iz], Mhfunc[iz], fill_value="extrapolate")(
Muvfunc_all[iz]
),
interp1d(
Muvfunc_MINI[iz], Mhfunc_MINI[iz], fill_value="extrapolate"
)(Muvfunc_all[iz]),
],
).T
lfunc_all[lfunc_all <= -30] = np.nan
return Muvfunc_all, Mhfunc_all, lfunc_all
elif component == 1:
lfunc = np.zeros(len(redshifts) * nbins)
Muvfunc = np.zeros(len(redshifts) * nbins)
Mhfunc = np.zeros(len(redshifts) * nbins)
lfunc.shape = (len(redshifts), nbins)
Muvfunc.shape = (len(redshifts), nbins)
Mhfunc.shape = (len(redshifts), nbins)
c_Muvfunc = ffi.cast("double *", ffi.from_buffer(Muvfunc))
c_Mhfunc = ffi.cast("double *", ffi.from_buffer(Mhfunc))
c_lfunc = ffi.cast("double *", ffi.from_buffer(lfunc))
# Run the C code
errcode = lib.ComputeLF(
nbins,
user_params(),
cosmo_params(),
astro_params(),
flag_options(),
1,
len(redshifts),
ffi.cast("float *", ffi.from_buffer(redshifts)),
ffi.cast("float *", ffi.from_buffer(mturnovers)),
c_Muvfunc,
c_Mhfunc,
c_lfunc,
)
_process_exitcode(
errcode,
lib.ComputeLF,
(
nbins,
user_params,
cosmo_params,
astro_params,
flag_options,
1,
len(redshifts),
),
)
lfunc[lfunc <= -30] = np.nan
return Muvfunc, Mhfunc, lfunc
elif component == 2:
lfunc_MINI = np.zeros(len(redshifts) * nbins)
Muvfunc_MINI = np.zeros(len(redshifts) * nbins)
Mhfunc_MINI = np.zeros(len(redshifts) * nbins)
lfunc_MINI.shape = (len(redshifts), nbins)
Muvfunc_MINI.shape = (len(redshifts), nbins)
Mhfunc_MINI.shape = (len(redshifts), nbins)
c_Muvfunc_MINI = ffi.cast("double *", ffi.from_buffer(Muvfunc_MINI))
c_Mhfunc_MINI = ffi.cast("double *", ffi.from_buffer(Mhfunc_MINI))
c_lfunc_MINI = ffi.cast("double *", ffi.from_buffer(lfunc_MINI))
# Run the C code
errcode = lib.ComputeLF(
nbins,
user_params(),
cosmo_params(),
astro_params(),
flag_options(),
2,
len(redshifts),
ffi.cast("float *", ffi.from_buffer(redshifts)),
ffi.cast("float *", ffi.from_buffer(mturnovers_mini)),
c_Muvfunc_MINI,
c_Mhfunc_MINI,
c_lfunc_MINI,
)
_process_exitcode(
errcode,
lib.ComputeLF,
(
nbins,
user_params,
cosmo_params,
astro_params,
flag_options,
2,
len(redshifts),
),
)
lfunc_MINI[lfunc_MINI <= -30] = np.nan
return Muvfunc_MINI, Mhfunc_MINI, lfunc_MINI
else:
logger.warning("What is component %d ?" % component)
return None, None, None
def _init_photon_conservation_correction(
*, user_params=None, cosmo_params=None, astro_params=None, flag_options=None
):
user_params = UserParams(user_params)
cosmo_params = CosmoParams(cosmo_params)
astro_params = AstroParams(astro_params)
flag_options = FlagOptions(
flag_options, USE_VELS_AUX=user_params.USE_RELATIVE_VELOCITIES
)
return lib.InitialisePhotonCons(
user_params(), cosmo_params(), astro_params(), flag_options()
)
def _calibrate_photon_conservation_correction(
*, redshifts_estimate, nf_estimate, NSpline
):
# Convert the data to the right type
redshifts_estimate = np.array(redshifts_estimate, dtype="float64")
nf_estimate = np.array(nf_estimate, dtype="float64")
z = ffi.cast("double *", ffi.from_buffer(redshifts_estimate))
xHI = ffi.cast("double *", ffi.from_buffer(nf_estimate))
logger.debug(f"PhotonCons nf estimates: {nf_estimate}")
return lib.PhotonCons_Calibration(z, xHI, NSpline)
def _calc_zstart_photon_cons():
# Run the C code
return _call_c_simple(lib.ComputeZstart_PhotonCons)
def _get_photon_nonconservation_data():
"""
Access C global data representing the photon-nonconservation corrections.
.. note:: if not using ``PHOTON_CONS`` (in :class:`~FlagOptions`), *or* if the
initialisation for photon conservation has not been performed yet, this
will return None.
Returns
-------
dict :
z_analytic: array of redshifts defining the analytic ionized fraction
Q_analytic: array of analytic ionized fractions corresponding to `z_analytic`
z_calibration: array of redshifts defining the ionized fraction from 21cmFAST without
recombinations
nf_calibration: array of calibration ionized fractions corresponding to `z_calibration`
delta_z_photon_cons: the change in redshift required to calibrate 21cmFAST, as a function
of z_calibration
nf_photoncons: the neutral fraction as a function of redshift
"""
# Check if photon conservation has been initialised at all
if not lib.photon_cons_allocated:
return None
arbitrary_large_size = 2000
data = np.zeros((6, arbitrary_large_size))
IntVal1 = np.array(np.zeros(1), dtype="int32")
IntVal2 = np.array(np.zeros(1), dtype="int32")
IntVal3 = np.array(np.zeros(1), dtype="int32")
c_z_at_Q = ffi.cast("double *", ffi.from_buffer(data[0]))
c_Qval = ffi.cast("double *", ffi.from_buffer(data[1]))
c_z_cal = ffi.cast("double *", ffi.from_buffer(data[2]))
c_nf_cal = ffi.cast("double *", ffi.from_buffer(data[3]))
c_PC_nf = ffi.cast("double *", ffi.from_buffer(data[4]))
c_PC_deltaz = ffi.cast("double *", ffi.from_buffer(data[5]))
c_int_NQ = ffi.cast("int *", ffi.from_buffer(IntVal1))
c_int_NC = ffi.cast("int *", ffi.from_buffer(IntVal2))
c_int_NP = ffi.cast("int *", ffi.from_buffer(IntVal3))
# Run the C code
errcode = lib.ObtainPhotonConsData(
c_z_at_Q,
c_Qval,
c_int_NQ,
c_z_cal,
c_nf_cal,
c_int_NC,
c_PC_nf,
c_PC_deltaz,
c_int_NP,
)
_process_exitcode(errcode, lib.ObtainPhotonConsData, ())
ArrayIndices = [
IntVal1[0],
IntVal1[0],
IntVal2[0],
IntVal2[0],
IntVal3[0],
IntVal3[0],
]
data_list = [
"z_analytic",
"Q_analytic",
"z_calibration",
"nf_calibration",
"nf_photoncons",
"delta_z_photon_cons",
]
return {name: d[:index] for name, d, index in zip(data_list, data, ArrayIndices)}
def initial_conditions(
*,
user_params=None,
cosmo_params=None,
random_seed=None,
regenerate=None,
write=None,
direc=None,
hooks: dict[Callable, dict[str, Any]] | None = None,
**global_kwargs,
) -> InitialConditions:
r"""
Compute initial conditions.
Parameters
----------
user_params : :class:`~UserParams` instance, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams` instance, optional
Defines the cosmological parameters used to compute initial conditions.
regenerate : bool, optional
Whether to force regeneration of data, even if matching cached data is found.
This is applied recursively to any potential sub-calculations. It is ignored in
the case of dependent data only if that data is explicitly passed to the function.
write : bool, optional
Whether to write results to file (i.e. cache). This is recursively applied to
any potential sub-calculations.
hooks
Any extra functions to apply to the output object. This should be a dictionary
where the keys are the functions, and the values are themselves dictionaries of
parameters to pass to the function. The function signature should be
``(output, **params)``, where the ``output`` is the output object.
direc : str, optional
The directory in which to search for the boxes and write them. By default, this
is the directory given by ``boxdir`` in the configuration file,
``~/.21cmfast/config.yml``. This is recursively applied to any potential
sub-calculations.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
:class:`~InitialConditions`
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
with global_params.use(**global_kwargs):
user_params, cosmo_params = _setup_inputs(
{"user_params": user_params, "cosmo_params": cosmo_params}
)
# Initialize memory for the boxes that will be returned.
boxes = InitialConditions(
user_params=user_params, cosmo_params=cosmo_params, random_seed=random_seed
)
# Construct FFTW wisdoms. Only if required
construct_fftw_wisdoms(user_params=user_params, cosmo_params=cosmo_params)
# First check whether the boxes already exist.
if not regenerate:
try:
boxes.read(direc)
logger.info(
f"Existing init_boxes found and read in (seed={boxes.random_seed})."
)
return boxes
except OSError:
pass
return boxes.compute(hooks=hooks)
def perturb_field(
*,
redshift,
init_boxes=None,
user_params=None,
cosmo_params=None,
random_seed=None,
regenerate=None,
write=None,
direc=None,
hooks: dict[Callable, dict[str, Any]] | None = None,
**global_kwargs,
) -> PerturbedField:
r"""
Compute a perturbed field at a given redshift.
Parameters
----------
redshift : float
The redshift at which to compute the perturbed field.
init_boxes : :class:`~InitialConditions`, optional
If given, these initial conditions boxes will be used, otherwise initial conditions will
be generated. If given,
the user and cosmo params will be set from this object.
user_params : :class:`~UserParams`, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
:class:`~PerturbedField`
Other Parameters
----------------
regenerate, write, direc, random_seed:
See docs of :func:`initial_conditions` for more information.
Examples
--------
The simplest method is just to give a redshift::
>>> field = perturb_field(7.0)
>>> print(field.density)
Doing so will internally call the :func:`~initial_conditions` function. If initial conditions
have already been
calculated, this can be avoided by passing them:
>>> init_boxes = initial_conditions()
>>> field7 = perturb_field(7.0, init_boxes)
>>> field8 = perturb_field(8.0, init_boxes)
The user and cosmo parameter structures are by default inferred from the ``init_boxes``,
so that the following is
consistent::
>>> init_boxes = initial_conditions(user_params= UserParams(HII_DIM=1000))
>>> field7 = perturb_field(7.0, init_boxes)
If ``init_boxes`` is not passed, then these parameters can be directly passed::
>>> field7 = perturb_field(7.0, user_params=UserParams(HII_DIM=1000))
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
with global_params.use(**global_kwargs):
random_seed, user_params, cosmo_params, redshift = _setup_inputs(
{
"random_seed": random_seed,
"user_params": user_params,
"cosmo_params": cosmo_params,
},
input_boxes={"init_boxes": init_boxes},
redshift=redshift,
)
# Initialize perturbed boxes.
fields = PerturbedField(
redshift=redshift,
user_params=user_params,
cosmo_params=cosmo_params,
random_seed=random_seed,
)
# Check whether the boxes already exist
if not regenerate:
try:
fields.read(direc)
logger.info(
f"Existing z={redshift} perturb_field boxes found and read in "
f"(seed={fields.random_seed})."
)
return fields
except OSError:
pass
# Construct FFTW wisdoms. Only if required
construct_fftw_wisdoms(user_params=user_params, cosmo_params=cosmo_params)
# Make sure we've got computed init boxes.
if init_boxes is None or not init_boxes.is_computed:
init_boxes = initial_conditions(
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regenerate,
hooks=hooks,
direc=direc,
random_seed=random_seed,
)
# Need to update fields to have the same seed as init_boxes
fields._random_seed = init_boxes.random_seed
# Run the C Code
return fields.compute(ics=init_boxes, hooks=hooks)
def determine_halo_list(
*,
redshift,
init_boxes=None,
user_params=None,
cosmo_params=None,
astro_params=None,
flag_options=None,
random_seed=None,
regenerate=None,
write=None,
direc=None,
hooks=None,
**global_kwargs,
):
r"""
Find a halo list, given a redshift.
Parameters
----------
redshift : float
The redshift at which to determine the halo list.
init_boxes : :class:`~InitialConditions`, optional
If given, these initial conditions boxes will be used, otherwise initial conditions will
be generated. If given,
the user and cosmo params will be set from this object.
user_params : :class:`~UserParams`, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
astro_params: :class:`~AstroParams` instance, optional
The astrophysical parameters defining the course of reionization.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
:class:`~HaloField`
Other Parameters
----------------
regenerate, write, direc, random_seed:
See docs of :func:`initial_conditions` for more information.
Examples
--------
Fill this in once finalised
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
with global_params.use(**global_kwargs):
# Configure and check input/output parameters/structs
(
random_seed,
user_params,
cosmo_params,
astro_params,
flag_options,
redshift,
) = _setup_inputs(
{
"random_seed": random_seed,
"user_params": user_params,
"cosmo_params": cosmo_params,
"astro_params": astro_params,
"flag_options": flag_options,
},
{"init_boxes": init_boxes},
redshift=redshift,
)
if user_params.HMF != 1:
raise ValueError("USE_HALO_FIELD is only valid for HMF = 1")
# Initialize halo list boxes.
fields = HaloField(
redshift=redshift,
user_params=user_params,
cosmo_params=cosmo_params,
astro_params=astro_params,
flag_options=flag_options,
random_seed=random_seed,
)
# Check whether the boxes already exist
if not regenerate:
try:
fields.read(direc)
logger.info(
f"Existing z={redshift} determine_halo_list boxes found and read in "
f"(seed={fields.random_seed})."
)
return fields
except OSError:
pass
# Construct FFTW wisdoms. Only if required
construct_fftw_wisdoms(user_params=user_params, cosmo_params=cosmo_params)
# Make sure we've got computed init boxes.
if init_boxes is None or not init_boxes.is_computed:
init_boxes = initial_conditions(
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regenerate,
hooks=hooks,
direc=direc,
random_seed=random_seed,
)
# Need to update fields to have the same seed as init_boxes
fields._random_seed = init_boxes.random_seed
# Run the C Code
return fields.compute(ics=init_boxes, hooks=hooks)
def perturb_halo_list(
*,
redshift,
init_boxes=None,
halo_field=None,
user_params=None,
cosmo_params=None,
astro_params=None,
flag_options=None,
random_seed=None,
regenerate=None,
write=None,
direc=None,
hooks=None,
**global_kwargs,
):
r"""
Given a halo list, perturb the halos for a given redshift.
Parameters
----------
redshift : float
The redshift at which to determine the halo list.
init_boxes : :class:`~InitialConditions`, optional
If given, these initial conditions boxes will be used, otherwise initial conditions will
be generated. If given,
the user and cosmo params will be set from this object.
user_params : :class:`~UserParams`, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
astro_params: :class:`~AstroParams` instance, optional
The astrophysical parameters defining the course of reionization.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
:class:`~PerturbHaloField`
Other Parameters
----------------
regenerate, write, direc, random_seed:
See docs of :func:`initial_conditions` for more information.
Examples
--------
Fill this in once finalised
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
with global_params.use(**global_kwargs):
# Configure and check input/output parameters/structs
(
random_seed,
user_params,
cosmo_params,
astro_params,
flag_options,
redshift,
) = _setup_inputs(
{
"random_seed": random_seed,
"user_params": user_params,
"cosmo_params": cosmo_params,
"astro_params": astro_params,
"flag_options": flag_options,
},
{"init_boxes": init_boxes, "halo_field": halo_field},
redshift=redshift,
)
if user_params.HMF != 1:
raise ValueError("USE_HALO_FIELD is only valid for HMF = 1")
# Initialize halo list boxes.
fields = PerturbHaloField(
redshift=redshift,
user_params=user_params,
cosmo_params=cosmo_params,
astro_params=astro_params,
flag_options=flag_options,
random_seed=random_seed,
)
# Check whether the boxes already exist
if not regenerate:
try:
fields.read(direc)
logger.info(
"Existing z=%s perturb_halo_list boxes found and read in (seed=%s)."
% (redshift, fields.random_seed)
)
return fields
except OSError:
pass
# Make sure we've got computed init boxes.
if init_boxes is None or not init_boxes.is_computed:
init_boxes = initial_conditions(
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regenerate,
hooks=hooks,
direc=direc,
random_seed=random_seed,
)
# Need to update fields to have the same seed as init_boxes
fields._random_seed = init_boxes.random_seed
# Dynamically produce the halo list.
if halo_field is None or not halo_field.is_computed:
halo_field = determine_halo_list(
init_boxes=init_boxes,
# NOTE: this is required, rather than using cosmo_ and user_,
# since init may have a set seed.
redshift=redshift,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
# Run the C Code
return fields.compute(ics=init_boxes, halo_field=halo_field, hooks=hooks)
def ionize_box(
*,
astro_params=None,
flag_options=None,
redshift=None,
perturbed_field=None,
previous_perturbed_field=None,
previous_ionize_box=None,
spin_temp=None,
pt_halos=None,
init_boxes=None,
cosmo_params=None,
user_params=None,
regenerate=None,
write=None,
direc=None,
random_seed=None,
cleanup=True,
hooks=None,
**global_kwargs,
) -> IonizedBox:
r"""
Compute an ionized box at a given redshift.
This function has various options for how the evolution of the ionization is computed (if at
all). See the Notes below for details.
Parameters
----------
astro_params: :class:`~AstroParams` instance, optional
The astrophysical parameters defining the course of reionization.
flag_options: :class:`~FlagOptions` instance, optional
Some options passed to the reionization routine.
redshift : float, optional
The redshift at which to compute the ionized box. If `perturbed_field` is given,
its inherent redshift
will take precedence over this argument. If not, this argument is mandatory.
perturbed_field : :class:`~PerturbField`, optional
If given, this field will be used, otherwise it will be generated. To be generated,
either `init_boxes` and
`redshift` must be given, or `user_params`, `cosmo_params` and `redshift`.
previous_perturbed_field : :class:`~PerturbField`, optional
An perturbed field at higher redshift. This is only used if mini_halo is included.
init_boxes : :class:`~InitialConditions` , optional
If given, and `perturbed_field` *not* given, these initial conditions boxes will be used
to generate the perturbed field, otherwise initial conditions will be generated on the fly.
If given, the user and cosmo params will be set from this object.
previous_ionize_box: :class:`IonizedBox` or None
An ionized box at higher redshift. This is only used if `INHOMO_RECO` and/or `do_spin_temp`
are true. If either of these are true, and this is not given, then it will be assumed that
this is the "first box", i.e. that it can be populated accurately without knowing source
statistics.
spin_temp: :class:`TsBox` or None, optional
A spin-temperature box, only required if `do_spin_temp` is True. If None, will try to read
in a spin temp box at the current redshift, and failing that will try to automatically
create one, using the previous ionized box redshift as the previous spin temperature
redshift.
pt_halos: :class:`~PerturbHaloField` or None, optional
If passed, this contains all the dark matter haloes obtained if using the USE_HALO_FIELD.
This is a list of halo masses and coords for the dark matter haloes.
If not passed, it will try and automatically create them using the available initial conditions.
user_params : :class:`~UserParams`, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
cleanup : bool, optional
A flag to specify whether the C routine cleans up its memory before returning. Typically,
if `spin_temperature` is called directly, you will want this to be true, as if the next box
to be calculate has different shape, errors will occur if memory is not cleaned. However,
it can be useful to set it to False if scrolling through parameters for the same box shape.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
:class:`~IonizedBox` :
An object containing the ionized box data.
Other Parameters
----------------
regenerate, write, direc, random_seed :
See docs of :func:`initial_conditions` for more information.
Notes
-----
Typically, the ionization field at any redshift is dependent on the evolution of xHI up until
that redshift, which necessitates providing a previous ionization field to define the current
one. This function provides several options for doing so. First, if neither the spin
temperature field, nor inhomogeneous recombinations (specified in flag options) are used, no
evolution needs to be done. Otherwise, either (in order of precedence)
1. a specific previous :class`~IonizedBox` object is provided, which will be used directly,
2. a previous redshift is provided, for which a cached field on disk will be sought,
3. a step factor is provided which recursively steps through redshift, calculating previous
fields up until Z_HEAT_MAX, and returning just the final field at the current redshift, or
4. the function is instructed to treat the current field as being an initial "high-redshift"
field such that specific sources need not be found and evolved.
.. note:: If a previous specific redshift is given, but no cached field is found at that
redshift, the previous ionization field will be evaluated based on `z_step_factor`.
Examples
--------
By default, no spin temperature is used, and neither are inhomogeneous recombinations,
so that no evolution is required, thus the following will compute a coeval ionization box:
>>> xHI = ionize_box(redshift=7.0)
However, if either of those options are true, then a full evolution will be required:
>>> xHI = ionize_box(redshift=7.0, flag_options=FlagOptions(INHOMO_RECO=True,USE_TS_FLUCT=True))
This will by default evolve the field from a redshift of *at least* `Z_HEAT_MAX` (a global
parameter), in logarithmic steps of `ZPRIME_STEP_FACTOR`. To change these:
>>> xHI = ionize_box(redshift=7.0, zprime_step_factor=1.2, z_heat_max=15.0,
>>> flag_options={"USE_TS_FLUCT":True})
Alternatively, one can pass an exact previous redshift, which will be sought in the disk
cache, or evaluated:
>>> ts_box = ionize_box(redshift=7.0, previous_ionize_box=8.0, flag_options={
>>> "USE_TS_FLUCT":True})
Beware that doing this, if the previous box is not found on disk, will continue to evaluate
prior boxes based on `ZPRIME_STEP_FACTOR`. Alternatively, one can pass a previous
:class:`~IonizedBox`:
>>> xHI_0 = ionize_box(redshift=8.0, flag_options={"USE_TS_FLUCT":True})
>>> xHI = ionize_box(redshift=7.0, previous_ionize_box=xHI_0)
Again, the first line here will implicitly use ``ZPRIME_STEP_FACTOR`` to evolve the field from
``Z_HEAT_MAX``. Note that in the second line, all of the input parameters are taken directly from
`xHI_0` so that they are consistent, and we need not specify the ``flag_options``.
As the function recursively evaluates previous redshift, the previous spin temperature fields
will also be consistently recursively evaluated. Only the final ionized box will actually be
returned and kept in memory, however intervening results will by default be cached on disk.
One can also pass an explicit spin temperature object:
>>> ts = spin_temperature(redshift=7.0)
>>> xHI = ionize_box(redshift=7.0, spin_temp=ts)
If automatic recursion is used, then it is done in such a way that no large boxes are kept
around in memory for longer than they need to be (only two at a time are required).
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
with global_params.use(**global_kwargs):
_verify_types(
init_boxes=init_boxes,
perturbed_field=perturbed_field,
previous_perturbed_field=previous_perturbed_field,
previous_ionize_box=previous_ionize_box,
spin_temp=spin_temp,
pt_halos=pt_halos,
)
# Configure and check input/output parameters/structs
(
random_seed,
user_params,
cosmo_params,
astro_params,
flag_options,
redshift,
) = _setup_inputs(
{
"random_seed": random_seed,
"user_params": user_params,
"cosmo_params": cosmo_params,
"astro_params": astro_params,
"flag_options": flag_options,
},
{
"init_boxes": init_boxes,
"perturbed_field": perturbed_field,
"previous_perturbed_field": previous_perturbed_field,
"previous_ionize_box": previous_ionize_box,
"spin_temp": spin_temp,
"pt_halos": pt_halos,
},
redshift=redshift,
)
if spin_temp is not None and not flag_options.USE_TS_FLUCT:
logger.warning(
"Changing flag_options.USE_TS_FLUCT to True since spin_temp was passed."
)
flag_options.USE_TS_FLUCT = True
# Get the previous redshift
if previous_ionize_box is not None and previous_ionize_box.is_computed:
prev_z = previous_ionize_box.redshift
# Ensure the previous ionized box has a higher redshift than this one.
if prev_z <= redshift:
raise ValueError(
"Previous ionized box must have a higher redshift than that being evaluated."
)
elif flag_options.INHOMO_RECO or flag_options.USE_TS_FLUCT:
prev_z = (1 + redshift) * global_params.ZPRIME_STEP_FACTOR - 1
# if the previous box is before our starting point, we set it to zero,
# which is what the C-code expects for an "initial" box
if prev_z > global_params.Z_HEAT_MAX:
prev_z = 0
else:
prev_z = 0
box = IonizedBox(
user_params=user_params,
cosmo_params=cosmo_params,
redshift=redshift,
astro_params=astro_params,
flag_options=flag_options,
random_seed=random_seed,
prev_ionize_redshift=prev_z,
)
# Construct FFTW wisdoms. Only if required
construct_fftw_wisdoms(user_params=user_params, cosmo_params=cosmo_params)
# Check whether the boxes already exist
if not regenerate:
try:
box.read(direc)
logger.info(
"Existing z=%s ionized boxes found and read in (seed=%s)."
% (redshift, box.random_seed)
)
return box
except OSError:
pass
# EVERYTHING PAST THIS POINT ONLY HAPPENS IF THE BOX DOESN'T ALREADY EXIST
# ------------------------------------------------------------------------
# Get init_box required.
if init_boxes is None or not init_boxes.is_computed:
init_boxes = initial_conditions(
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regenerate,
hooks=hooks,
direc=direc,
random_seed=random_seed,
)
# Need to update random seed
box._random_seed = init_boxes.random_seed
# Get appropriate previous ionization box
if previous_ionize_box is None or not previous_ionize_box.is_computed:
# If we are beyond Z_HEAT_MAX, just make an empty box
if prev_z == 0:
previous_ionize_box = IonizedBox(
redshift=0, flag_options=flag_options, initial=True
)
# Otherwise recursively create new previous box.
else:
previous_ionize_box = ionize_box(
astro_params=astro_params,
flag_options=flag_options,
redshift=prev_z,
init_boxes=init_boxes,
regenerate=regenerate,
hooks=hooks,
direc=direc,
cleanup=False, # We *know* we're going to need the memory again.
)
# Dynamically produce the perturbed field.
if perturbed_field is None or not perturbed_field.is_computed:
perturbed_field = perturb_field(
init_boxes=init_boxes,
# NOTE: this is required, rather than using cosmo_ and user_,
# since init may have a set seed.
redshift=redshift,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
if previous_perturbed_field is None or not previous_perturbed_field.is_computed:
# If we are beyond Z_HEAT_MAX, just make an empty box
if not prev_z:
previous_perturbed_field = PerturbedField(
redshift=0, user_params=user_params, initial=True
)
else:
previous_perturbed_field = perturb_field(
init_boxes=init_boxes,
redshift=prev_z,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
# Dynamically produce the halo field.
if not flag_options.USE_HALO_FIELD:
# Construct an empty halo field to pass in to the function.
pt_halos = PerturbHaloField(redshift=0, dummy=True)
elif pt_halos is None or not pt_halos.is_computed:
pt_halos = perturb_halo_list(
redshift=redshift,
init_boxes=init_boxes,
halo_field=determine_halo_list(
redshift=redshift,
init_boxes=init_boxes,
astro_params=astro_params,
flag_options=flag_options,
regenerate=regenerate,
hooks=hooks,
direc=direc,
),
astro_params=astro_params,
flag_options=flag_options,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
# Set empty spin temp box if necessary.
if not flag_options.USE_TS_FLUCT:
spin_temp = TsBox(redshift=0, dummy=True)
elif spin_temp is None:
spin_temp = spin_temperature(
perturbed_field=perturbed_field,
flag_options=flag_options,
init_boxes=init_boxes,
direc=direc,
hooks=hooks,
regenerate=regenerate,
cleanup=cleanup,
)
# Run the C Code
return box.compute(
perturbed_field=perturbed_field,
prev_perturbed_field=previous_perturbed_field,
prev_ionize_box=previous_ionize_box,
spin_temp=spin_temp,
pt_halos=pt_halos,
ics=init_boxes,
hooks=hooks,
)
def spin_temperature(
*,
astro_params=None,
flag_options=None,
redshift=None,
perturbed_field=None,
previous_spin_temp=None,
init_boxes=None,
cosmo_params=None,
user_params=None,
regenerate=None,
write=None,
direc=None,
random_seed=None,
cleanup=True,
hooks=None,
**global_kwargs,
) -> TsBox:
r"""
Compute spin temperature boxes at a given redshift.
See the notes below for how the spin temperature field is evolved through redshift.
Parameters
----------
astro_params : :class:`~AstroParams`, optional
The astrophysical parameters defining the course of reionization.
flag_options : :class:`~FlagOptions`, optional
Some options passed to the reionization routine.
redshift : float, optional
The redshift at which to compute the ionized box. If not given, the redshift from
`perturbed_field` will be used. Either `redshift`, `perturbed_field`, or
`previous_spin_temp` must be given. See notes on `perturbed_field` for how it affects the
given redshift if both are given.
perturbed_field : :class:`~PerturbField`, optional
If given, this field will be used, otherwise it will be generated. To be generated,
either `init_boxes` and `redshift` must be given, or `user_params`, `cosmo_params` and
`redshift`. By default, this will be generated at the same redshift as the spin temperature
box. The redshift of perturb field is allowed to be different than `redshift`. If so, it
will be interpolated to the correct redshift, which can provide a speedup compared to
actually computing it at the desired redshift.
previous_spin_temp : :class:`TsBox` or None
The previous spin temperature box.
init_boxes : :class:`~InitialConditions`, optional
If given, and `perturbed_field` *not* given, these initial conditions boxes will be used
to generate the perturbed field, otherwise initial conditions will be generated on the fly.
If given, the user and cosmo params will be set from this object.
user_params : :class:`~UserParams`, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
cleanup : bool, optional
A flag to specify whether the C routine cleans up its memory before returning.
Typically, if `spin_temperature` is called directly, you will want this to be
true, as if the next box to be calculate has different shape, errors will occur
if memory is not cleaned. However, it can be useful to set it to False if
scrolling through parameters for the same box shape.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
:class:`~TsBox`
An object containing the spin temperature box data.
Other Parameters
----------------
regenerate, write, direc, random_seed :
See docs of :func:`initial_conditions` for more information.
Notes
-----
Typically, the spin temperature field at any redshift is dependent on the evolution of spin
temperature up until that redshift, which necessitates providing a previous spin temperature
field to define the current one. This function provides several options for doing so. Either
(in order of precedence):
1. a specific previous spin temperature object is provided, which will be used directly,
2. a previous redshift is provided, for which a cached field on disk will be sought,
3. a step factor is provided which recursively steps through redshift, calculating previous
fields up until Z_HEAT_MAX, and returning just the final field at the current redshift, or
4. the function is instructed to treat the current field as being an initial "high-redshift"
field such that specific sources need not be found and evolved.
.. note:: If a previous specific redshift is given, but no cached field is found at that
redshift, the previous spin temperature field will be evaluated based on
``z_step_factor``.
Examples
--------
To calculate and return a fully evolved spin temperature field at a given redshift (with
default input parameters), simply use:
>>> ts_box = spin_temperature(redshift=7.0)
This will by default evolve the field from a redshift of *at least* `Z_HEAT_MAX` (a global
parameter), in logarithmic steps of `z_step_factor`. Thus to change these:
>>> ts_box = spin_temperature(redshift=7.0, zprime_step_factor=1.2, z_heat_max=15.0)
Alternatively, one can pass an exact previous redshift, which will be sought in the disk
cache, or evaluated:
>>> ts_box = spin_temperature(redshift=7.0, previous_spin_temp=8.0)
Beware that doing this, if the previous box is not found on disk, will continue to evaluate
prior boxes based on the ``z_step_factor``. Alternatively, one can pass a previous spin
temperature box:
>>> ts_box1 = spin_temperature(redshift=8.0)
>>> ts_box = spin_temperature(redshift=7.0, previous_spin_temp=ts_box1)
Again, the first line here will implicitly use ``z_step_factor`` to evolve the field from
around ``Z_HEAT_MAX``. Note that in the second line, all of the input parameters are taken
directly from `ts_box1` so that they are consistent. Finally, one can force the function to
evaluate the current redshift as if it was beyond ``Z_HEAT_MAX`` so that it depends only on
itself:
>>> ts_box = spin_temperature(redshift=7.0, zprime_step_factor=None)
This is usually a bad idea, and will give a warning, but it is possible.
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
with global_params.use(**global_kwargs):
# Configure and check input/output parameters/structs
(
random_seed,
user_params,
cosmo_params,
astro_params,
flag_options,
) = _setup_inputs(
{
"random_seed": random_seed,
"user_params": user_params,
"cosmo_params": cosmo_params,
"astro_params": astro_params,
"flag_options": flag_options,
},
{
"init_boxes": init_boxes,
"perturbed_field": perturbed_field,
"previous_spin_temp": previous_spin_temp,
},
)
# Try to determine redshift from other inputs, if required.
# Note that perturb_field does not need to match redshift here.
if redshift is None:
if perturbed_field is not None:
redshift = perturbed_field.redshift
elif previous_spin_temp is not None:
redshift = (
previous_spin_temp.redshift + 1
) / global_params.ZPRIME_STEP_FACTOR - 1
else:
raise ValueError(
"Either the redshift, perturbed_field or previous_spin_temp must be given."
)
# Explicitly set this flag to True, though it shouldn't be required!
flag_options.update(USE_TS_FLUCT=True)
# Get the previous redshift
if previous_spin_temp is not None:
prev_z = previous_spin_temp.redshift
else:
if redshift < global_params.Z_HEAT_MAX:
# In general runs, we only compute the spin temperature *below* Z_HEAT_MAX.
# Above this, we don't need a prev_z at all, because we can calculate
# directly at whatever redshift it is.
prev_z = min(
global_params.Z_HEAT_MAX,
(1 + redshift) * global_params.ZPRIME_STEP_FACTOR - 1,
)
else:
# Set prev_z to anything, since we don't need it.
prev_z = np.inf
# Ensure the previous spin temperature has a higher redshift than this one.
if prev_z <= redshift:
raise ValueError(
"Previous spin temperature box must have a higher redshift than "
"that being evaluated."
)
# Set up the box without computing anything.
box = TsBox(
user_params=user_params,
cosmo_params=cosmo_params,
redshift=redshift,
astro_params=astro_params,
flag_options=flag_options,
random_seed=random_seed,
prev_spin_redshift=prev_z,
perturbed_field_redshift=perturbed_field.redshift
if (perturbed_field is not None and perturbed_field.is_computed)
else redshift,
)
# Construct FFTW wisdoms. Only if required
construct_fftw_wisdoms(user_params=user_params, cosmo_params=cosmo_params)
# Check whether the boxes already exist on disk.
if not regenerate:
try:
box.read(direc)
logger.info(
f"Existing z={redshift} spin_temp boxes found and read in "
f"(seed={box.random_seed})."
)
return box
except OSError:
pass
# EVERYTHING PAST THIS POINT ONLY HAPPENS IF THE BOX DOESN'T ALREADY EXIST
# ------------------------------------------------------------------------
# Dynamically produce the initial conditions.
if init_boxes is None or not init_boxes.is_computed:
init_boxes = initial_conditions(
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regenerate,
hooks=hooks,
direc=direc,
random_seed=random_seed,
)
# Need to update random seed
box._random_seed = init_boxes.random_seed
# Create appropriate previous_spin_temp
if previous_spin_temp is None:
if redshift >= global_params.Z_HEAT_MAX:
# We end up never even using this box, just need to define it
# unallocated to be able to send into the C code.
previous_spin_temp = TsBox(
redshift=prev_z, # redshift here is ignored
user_params=init_boxes.user_params,
cosmo_params=init_boxes.cosmo_params,
astro_params=astro_params,
flag_options=flag_options,
dummy=True,
)
else:
previous_spin_temp = spin_temperature(
init_boxes=init_boxes,
astro_params=astro_params,
flag_options=flag_options,
redshift=prev_z,
regenerate=regenerate,
hooks=hooks,
direc=direc,
cleanup=False, # we know we'll need the memory again
)
# Dynamically produce the perturbed field.
if perturbed_field is None or not perturbed_field.is_computed:
perturbed_field = perturb_field(
redshift=redshift,
init_boxes=init_boxes,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
# Run the C Code
return box.compute(
cleanup=cleanup,
perturbed_field=perturbed_field,
prev_spin_temp=previous_spin_temp,
ics=init_boxes,
hooks=hooks,
)
def brightness_temperature(
*,
ionized_box,
perturbed_field,
spin_temp=None,
write=None,
regenerate=None,
direc=None,
hooks=None,
**global_kwargs,
) -> BrightnessTemp:
r"""
Compute a coeval brightness temperature box.
Parameters
----------
ionized_box: :class:`IonizedBox`
A pre-computed ionized box.
perturbed_field: :class:`PerturbedField`
A pre-computed perturbed field at the same redshift as `ionized_box`.
spin_temp: :class:`TsBox`, optional
A pre-computed spin temperature, at the same redshift as the other boxes.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
:class:`BrightnessTemp` instance.
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
with global_params.use(**global_kwargs):
_verify_types(
perturbed_field=perturbed_field,
spin_temp=spin_temp,
ionized_box=ionized_box,
)
# don't ignore redshift here
_check_compatible_inputs(ionized_box, perturbed_field, spin_temp, ignore=[])
# ensure ionized_box and perturbed_field aren't None, as we don't do
# any dynamic calculations here.
if ionized_box is None or perturbed_field is None:
raise ValueError("both ionized_box and perturbed_field must be specified.")
if spin_temp is None:
if ionized_box.flag_options.USE_TS_FLUCT:
raise ValueError(
"You have USE_TS_FLUCT=True, but have not provided a spin_temp!"
)
# Make an unused dummy box.
spin_temp = TsBox(redshift=0, dummy=True)
box = BrightnessTemp(
user_params=ionized_box.user_params,
cosmo_params=ionized_box.cosmo_params,
astro_params=ionized_box.astro_params,
flag_options=ionized_box.flag_options,
redshift=ionized_box.redshift,
random_seed=ionized_box.random_seed,
)
# Construct FFTW wisdoms. Only if required
construct_fftw_wisdoms(
user_params=ionized_box.user_params, cosmo_params=ionized_box.cosmo_params
)
# Check whether the boxes already exist on disk.
if not regenerate:
try:
box.read(direc)
logger.info(
f"Existing brightness_temp box found and read in (seed={box.random_seed})."
)
return box
except OSError:
pass
return box.compute(
spin_temp=spin_temp,
ionized_box=ionized_box,
perturbed_field=perturbed_field,
hooks=hooks,
)
def _logscroll_redshifts(min_redshift, z_step_factor, zmax):
redshifts = [min_redshift]
while redshifts[-1] < zmax:
redshifts.append((redshifts[-1] + 1.0) * z_step_factor - 1.0)
return redshifts[::-1]
def run_coeval(
*,
redshift=None,
user_params=None,
cosmo_params=None,
astro_params=None,
flag_options=None,
regenerate=None,
write=None,
direc=None,
init_box=None,
perturb=None,
use_interp_perturb_field=False,
pt_halos=None,
random_seed=None,
cleanup=True,
hooks=None,
always_purge: bool = False,
**global_kwargs,
):
r"""
Evaluate a coeval ionized box at a given redshift, or multiple redshifts.
This is generally the easiest and most efficient way to generate a set of coeval cubes at a
given set of redshift. It self-consistently deals with situations in which the field needs to be
evolved, and does this with the highest memory-efficiency, only returning the desired redshift.
All other calculations are by default stored in the on-disk cache so they can be re-used at a
later time.
.. note:: User-supplied redshift are *not* used as previous redshift in any scrolling,
so that pristine log-sampling can be maintained.
Parameters
----------
redshift: array_like
A single redshift, or multiple redshift, at which to return results. The minimum of these
will define the log-scrolling behaviour (if necessary).
user_params : :class:`~inputs.UserParams`, optional
Defines the overall options and parameters of the run.
cosmo_params : :class:`~inputs.CosmoParams` , optional
Defines the cosmological parameters used to compute initial conditions.
astro_params : :class:`~inputs.AstroParams` , optional
The astrophysical parameters defining the course of reionization.
flag_options : :class:`~inputs.FlagOptions` , optional
Some options passed to the reionization routine.
init_box : :class:`~InitialConditions`, optional
If given, the user and cosmo params will be set from this object, and it will not
be re-calculated.
perturb : list of :class:`~PerturbedField`, optional
If given, must be compatible with init_box. It will merely negate the necessity
of re-calculating the perturb fields.
use_interp_perturb_field : bool, optional
Whether to use a single perturb field, at the lowest redshift of the lightcone,
to determine all spin temperature fields. If so, this field is interpolated in
the underlying C-code to the correct redshift. This is less accurate (and no more
efficient), but provides compatibility with older versions of 21cmFAST.
pt_halos : bool, optional
If given, must be compatible with init_box. It will merely negate the necessity
of re-calculating the perturbed halo lists.
cleanup : bool, optional
A flag to specify whether the C routine cleans up its memory before returning.
Typically, if `spin_temperature` is called directly, you will want this to be
true, as if the next box to be calculate has different shape, errors will occur
if memory is not cleaned. Note that internally, this is set to False until the
last iteration.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
coevals : :class:`~py21cmfast.outputs.Coeval`
The full data for the Coeval class, with init boxes, perturbed fields, ionized boxes,
brightness temperature, and potential data from the conservation of photons. If a
single redshift was specified, it will return such a class. If multiple redshifts
were passed, it will return a list of such classes.
Other Parameters
----------------
regenerate, write, direc, random_seed :
See docs of :func:`initial_conditions` for more information.
"""
with global_params.use(**global_kwargs):
if redshift is None and perturb is None:
raise ValueError("Either redshift or perturb must be given")
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
singleton = False
# Ensure perturb is a list of boxes, not just one.
if perturb is None:
perturb = []
elif not hasattr(perturb, "__len__"):
perturb = [perturb]
singleton = True
# Ensure perturbed halo field is a list of boxes, not just one.
if flag_options is None or pt_halos is None:
pt_halos = []
elif (
flag_options["USE_HALO_FIELD"]
if isinstance(flag_options, dict)
else flag_options.USE_HALO_FIELD
):
pt_halos = [pt_halos] if not hasattr(pt_halos, "__len__") else []
else:
pt_halos = []
(
random_seed,
user_params,
cosmo_params,
astro_params,
flag_options,
) = _setup_inputs(
{
"random_seed": random_seed,
"user_params": user_params,
"cosmo_params": cosmo_params,
"astro_params": astro_params,
"flag_options": flag_options,
},
)
if use_interp_perturb_field and flag_options.USE_MINI_HALOS:
raise ValueError("Cannot use an interpolated perturb field with minihalos!")
if init_box is None:
init_box = initial_conditions(
user_params=user_params,
cosmo_params=cosmo_params,
random_seed=random_seed,
hooks=hooks,
regenerate=regenerate,
direc=direc,
)
# We can go ahead and purge some of the stuff in the init_box, but only if
# it is cached -- otherwise we could be losing information.
try:
init_box.prepare_for_perturb(flag_options=flag_options, force=always_purge)
except OSError:
pass
if perturb:
if redshift is not None and any(
p.redshift != z for p, z in zip(perturb, redshift)
):
raise ValueError("Input redshifts do not match perturb field redshifts")
else:
redshift = [p.redshift for p in perturb]
if (
flag_options.USE_HALO_FIELD
and pt_halos
and any(p.redshift != z for p, z in zip(pt_halos, redshift))
):
raise ValueError(
"Input redshifts do not match the perturbed halo field redshifts"
)
if flag_options.PHOTON_CONS:
calibrate_photon_cons(
user_params,
cosmo_params,
astro_params,
flag_options,
init_box,
regenerate,
write,
direc,
)
if not hasattr(redshift, "__len__"):
singleton = True
redshift = [redshift]
# Get the list of redshift we need to scroll through.
redshifts = _get_required_redshifts_coeval(flag_options, redshift)
# Get all the perturb boxes early. We need to get the perturb at every
# redshift, even if we are interpolating the perturb field, because the
# ionize box needs it.
pz = [p.redshift for p in perturb]
perturb_ = []
for z in redshifts:
p = (
perturb_field(
redshift=z,
init_boxes=init_box,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
if z not in pz
else perturb[pz.index(z)]
)
if user_params.MINIMIZE_MEMORY:
try:
p.purge(force=always_purge)
except OSError:
pass
perturb_.append(p)
perturb = perturb_
# Now we can purge init_box further.
try:
init_box.prepare_for_spin_temp(
flag_options=flag_options, force=always_purge
)
except OSError:
pass
if flag_options.USE_HALO_FIELD and not pt_halos:
for z in redshift:
pt_halos += [
perturb_halo_list(
redshift=z,
init_boxes=init_box,
user_params=user_params,
cosmo_params=cosmo_params,
astro_params=astro_params,
flag_options=flag_options,
halo_field=determine_halo_list(
redshift=z,
init_boxes=init_box,
astro_params=astro_params,
flag_options=flag_options,
regenerate=regenerate,
hooks=hooks,
direc=direc,
),
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
]
if (
flag_options.PHOTON_CONS
and np.amin(redshifts) < global_params.PhotonConsEndCalibz
):
raise ValueError(
f"You have passed a redshift (z = {np.amin(redshifts)}) that is lower than"
"the endpoint of the photon non-conservation correction"
f"(global_params.PhotonConsEndCalibz = {global_params.PhotonConsEndCalibz})."
"If this behaviour is desired then set global_params.PhotonConsEndCalibz"
f"to a value lower than z = {np.amin(redshifts)}."
)
if flag_options.PHOTON_CONS:
calibrate_photon_cons(
user_params,
cosmo_params,
astro_params,
flag_options,
init_box,
regenerate,
write,
direc,
)
ib_tracker = [0] * len(redshift)
bt = [0] * len(redshift)
st, ib, pf = None, None, None # At first we don't have any "previous" st or ib.
perturb_min = perturb[np.argmin(redshift)]
st_tracker = [None] * len(redshift)
spin_temp_files = []
perturb_files = []
ionize_files = []
brightness_files = []
# Iterate through redshift from top to bottom
for iz, z in enumerate(redshifts):
pf2 = perturb[iz]
pf2.load_all()
if flag_options.USE_TS_FLUCT:
logger.debug(f"Doing spin temp for z={z}.")
st2 = spin_temperature(
redshift=z,
previous_spin_temp=st,
perturbed_field=perturb_min if use_interp_perturb_field else pf2,
# remember that perturb field is interpolated, so no need to provide exact one.
astro_params=astro_params,
flag_options=flag_options,
regenerate=regenerate,
init_boxes=init_box,
hooks=hooks,
direc=direc,
cleanup=(
cleanup and z == redshifts[-1]
), # cleanup if its the last time through
)
if z not in redshift:
st = st2
ib2 = ionize_box(
redshift=z,
previous_ionize_box=ib,
init_boxes=init_box,
perturbed_field=pf2,
# perturb field *not* interpolated here.
previous_perturbed_field=pf,
pt_halos=pt_halos[redshift.index(z)]
if z in redshift and flag_options.USE_HALO_FIELD
else None,
astro_params=astro_params,
flag_options=flag_options,
spin_temp=st2 if flag_options.USE_TS_FLUCT else None,
regenerate=regenerate,
z_heat_max=global_params.Z_HEAT_MAX,
hooks=hooks,
direc=direc,
cleanup=(
cleanup and z == redshifts[-1]
), # cleanup if its the last time through
)
if pf is not None:
try:
pf.purge(force=always_purge)
except OSError:
pass
if z in redshift:
logger.debug(f"PID={os.getpid()} doing brightness temp for z={z}")
ib_tracker[redshift.index(z)] = ib2
st_tracker[redshift.index(z)] = (
st2 if flag_options.USE_TS_FLUCT else None
)
_bt = brightness_temperature(
ionized_box=ib2,
perturbed_field=pf2,
spin_temp=st2 if flag_options.USE_TS_FLUCT else None,
hooks=hooks,
direc=direc,
regenerate=regenerate,
)
bt[redshift.index(z)] = _bt
else:
ib = ib2
pf = pf2
_bt = None
perturb_files.append((z, os.path.join(direc, pf2.filename)))
if flag_options.USE_TS_FLUCT:
spin_temp_files.append((z, os.path.join(direc, st2.filename)))
ionize_files.append((z, os.path.join(direc, ib2.filename)))
if _bt is not None:
brightness_files.append((z, os.path.join(direc, _bt.filename)))
if flag_options.PHOTON_CONS:
photon_nonconservation_data = _get_photon_nonconservation_data()
if photon_nonconservation_data:
lib.FreePhotonConsMemory()
else:
photon_nonconservation_data = None
if (
flag_options.USE_TS_FLUCT
and user_params.USE_INTERPOLATION_TABLES
and lib.interpolation_tables_allocated
):
lib.FreeTsInterpolationTables(flag_options())
coevals = [
Coeval(
redshift=z,
initial_conditions=init_box,
perturbed_field=perturb[redshifts.index(z)],
ionized_box=ib,
brightness_temp=_bt,
ts_box=st,
photon_nonconservation_data=photon_nonconservation_data,
cache_files={
"init": [(0, os.path.join(direc, init_box.filename))],
"perturb_field": perturb_files,
"ionized_box": ionize_files,
"brightness_temp": brightness_files,
"spin_temp": spin_temp_files,
},
)
for z, ib, _bt, st in zip(redshift, ib_tracker, bt, st_tracker)
]
# If a single redshift was passed, then pass back singletons.
if singleton:
coevals = coevals[0]
logger.debug("Returning from Coeval")
return coevals
def _get_required_redshifts_coeval(flag_options, redshift) -> list[float]:
if min(redshift) < global_params.Z_HEAT_MAX and (
flag_options.INHOMO_RECO or flag_options.USE_TS_FLUCT
):
redshifts = _logscroll_redshifts(
min(redshift),
global_params.ZPRIME_STEP_FACTOR,
global_params.Z_HEAT_MAX,
)
# Set the highest redshift to exactly Z_HEAT_MAX. This makes the coeval run
# at exactly the same redshift as the spin temperature box. There's literally
# no point going higher for a coeval, since the user is only interested in
# the final "redshift" (if they've specified a z in redshift that is higher
# that Z_HEAT_MAX, we add it back in below, and so they'll still get it).
redshifts = np.clip(redshifts, None, global_params.Z_HEAT_MAX)
else:
redshifts = [min(redshift)]
# Add in the redshift defined by the user, and sort in order
# Turn into a set so that exact matching user-set redshift
# don't double-up with scrolling ones.
redshifts = np.concatenate((redshifts, redshift))
redshifts = np.sort(np.unique(redshifts))[::-1]
return redshifts.tolist()
def run_lightcone(
*,
redshift=None,
max_redshift=None,
user_params=None,
cosmo_params=None,
astro_params=None,
flag_options=None,
regenerate=None,
write=None,
lightcone_quantities=("brightness_temp",),
global_quantities=("brightness_temp", "xH_box"),
direc=None,
init_box=None,
perturb=None,
random_seed=None,
coeval_callback=None,
coeval_callback_redshifts=1,
use_interp_perturb_field=False,
cleanup=True,
hooks=None,
always_purge: bool = False,
**global_kwargs,
):
r"""
Evaluate a full lightcone ending at a given redshift.
This is generally the easiest and most efficient way to generate a lightcone, though it can
be done manually by using the lower-level functions which are called by this function.
Parameters
----------
redshift : float
The minimum redshift of the lightcone.
max_redshift : float, optional
The maximum redshift at which to keep lightcone information. By default, this is equal to
`z_heat_max`. Note that this is not *exact*, but will be typically slightly exceeded.
user_params : `~UserParams`, optional
Defines the overall options and parameters of the run.
astro_params : :class:`~AstroParams`, optional
Defines the astrophysical parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
flag_options : :class:`~FlagOptions`, optional
Options concerning how the reionization process is run, eg. if spin temperature
fluctuations are required.
lightcone_quantities : tuple of str, optional
The quantities to form into a lightcone. By default, just the brightness
temperature. Note that these quantities must exist in one of the output
structures:
* :class:`~InitialConditions`
* :class:`~PerturbField`
* :class:`~TsBox`
* :class:`~IonizedBox`
* :class:`BrightnessTemp`
To get a full list of possible quantities, run :func:`get_all_fieldnames`.
global_quantities : tuple of str, optional
The quantities to save as globally-averaged redshift-dependent functions.
These may be any of the quantities that can be used in ``lightcone_quantities``.
The mean is taken over the full 3D cube at each redshift, rather than a 2D
slice.
init_box : :class:`~InitialConditions`, optional
If given, the user and cosmo params will be set from this object, and it will not be
re-calculated.
perturb : list of :class:`~PerturbedField`, optional
If given, must be compatible with init_box. It will merely negate the necessity of
re-calculating the
perturb fields. It will also be used to set the redshift if given.
coeval_callback : callable, optional
User-defined arbitrary function computed on :class:`~Coeval`, at redshifts defined in
`coeval_callback_redshifts`.
If given, the function returns :class:`~LightCone` and the list of `coeval_callback` outputs.
coeval_callback_redshifts : list or int, optional
Redshifts for `coeval_callback` computation.
If list, computes the function on `node_redshifts` closest to the specified ones.
If positive integer, computes the function on every n-th redshift in `node_redshifts`.
Ignored in the case `coeval_callback is None`.
use_interp_perturb_field : bool, optional
Whether to use a single perturb field, at the lowest redshift of the lightcone,
to determine all spin temperature fields. If so, this field is interpolated in the
underlying C-code to the correct redshift. This is less accurate (and no more efficient),
but provides compatibility with older versions of 21cmFAST.
cleanup : bool, optional
A flag to specify whether the C routine cleans up its memory before returning.
Typically, if `spin_temperature` is called directly, you will want this to be
true, as if the next box to be calculate has different shape, errors will occur
if memory is not cleaned. Note that internally, this is set to False until the
last iteration.
minimize_memory_usage
If switched on, the routine will do all it can to minimize peak memory usage.
This will be at the cost of disk I/O and CPU time. Recommended to only set this
if you are running particularly large boxes, or have low RAM.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Returns
-------
lightcone : :class:`~py21cmfast.LightCone`
The lightcone object.
coeval_callback_output : list
Only if coeval_callback in not None.
Other Parameters
----------------
regenerate, write, direc, random_seed
See docs of :func:`initial_conditions` for more information.
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, hooks)
with global_params.use(**global_kwargs):
(
random_seed,
user_params,
cosmo_params,
flag_options,
astro_params,
redshift,
) = _setup_inputs(
{
"random_seed": random_seed,
"user_params": user_params,
"cosmo_params": cosmo_params,
"flag_options": flag_options,
"astro_params": astro_params,
},
{"init_box": init_box, "perturb": perturb},
redshift=redshift,
)
if user_params.MINIMIZE_MEMORY and not write:
raise ValueError(
"If trying to minimize memory usage, you must be caching. Set write=True!"
)
# Ensure passed quantities are appropriate
_fld_names = _get_interpolation_outputs(
list(lightcone_quantities), list(global_quantities), flag_options
)
max_redshift = (
global_params.Z_HEAT_MAX
if (
flag_options.INHOMO_RECO
or flag_options.USE_TS_FLUCT
or max_redshift is None
)
else max_redshift
)
# Get the redshift through which we scroll and evaluate the ionization field.
scrollz = _logscroll_redshifts(
redshift, global_params.ZPRIME_STEP_FACTOR, max_redshift
)
if (
flag_options.PHOTON_CONS
and np.amin(scrollz) < global_params.PhotonConsEndCalibz
):
raise ValueError(
f"""
You have passed a redshift (z = {np.amin(scrollz)}) that is lower than the endpoint
of the photon non-conservation correction
(global_params.PhotonConsEndCalibz = {global_params.PhotonConsEndCalibz}).
If this behaviour is desired then set global_params.PhotonConsEndCalibz to a value lower than
z = {np.amin(scrollz)}.
"""
)
coeval_callback_output = []
compute_coeval_callback = _get_coeval_callbacks(
scrollz, coeval_callback, coeval_callback_redshifts
)
if init_box is None: # no need to get cosmo, user params out of it.
init_box = initial_conditions(
user_params=user_params,
cosmo_params=cosmo_params,
hooks=hooks,
regenerate=regenerate,
direc=direc,
random_seed=random_seed,
)
# We can go ahead and purge some of the stuff in the init_box, but only if
# it is cached -- otherwise we could be losing information.
try:
# TODO: should really check that the file at path actually contains a fully
# working copy of the init_box.
init_box.prepare_for_perturb(flag_options=flag_options, force=always_purge)
except OSError:
pass
if perturb is None:
zz = scrollz
else:
zz = scrollz[:-1]
perturb_ = []
for z in zz:
p = perturb_field(
redshift=z,
init_boxes=init_box,
regenerate=regenerate,
direc=direc,
hooks=hooks,
)
if user_params.MINIMIZE_MEMORY:
try:
p.purge(force=always_purge)
except OSError:
pass
perturb_.append(p)
if perturb is not None:
perturb_.append(perturb)
perturb = perturb_
perturb_min = perturb[np.argmin(scrollz)]
# Now that we've got all the perturb fields, we can purge init more.
try:
init_box.prepare_for_spin_temp(
flag_options=flag_options, force=always_purge
)
except OSError:
pass
if flag_options.PHOTON_CONS:
calibrate_photon_cons(
user_params,
cosmo_params,
astro_params,
flag_options,
init_box,
regenerate,
write,
direc,
)
d_at_redshift, lc_distances, n_lightcone = _setup_lightcone(
cosmo_params,
max_redshift,
redshift,
scrollz,
user_params,
global_params.ZPRIME_STEP_FACTOR,
)
scroll_distances = (
cosmo_params.cosmo.comoving_distance(scrollz).value - d_at_redshift
)
# Iterate through redshift from top to bottom
st, ib, bt, prev_perturb = None, None, None, None
lc_index = 0
box_index = 0
lc = {
quantity: np.zeros(
(user_params.HII_DIM, user_params.HII_DIM, n_lightcone),
dtype=np.float32,
)
for quantity in lightcone_quantities
}
interp_functions = {
"z_re_box": "mean_max",
}
global_q = {quantity: np.zeros(len(scrollz)) for quantity in global_quantities}
pf = None
perturb_files = []
spin_temp_files = []
ionize_files = []
brightness_files = []
log10_mturnovers = np.zeros(len(scrollz))
log10_mturnovers_mini = np.zeros(len(scrollz))
for iz, z in enumerate(scrollz):
# Best to get a perturb for this redshift, to pass to brightness_temperature
pf2 = perturb[iz]
# This ensures that all the arrays that are required for spin_temp are there,
# in case we dumped them from memory into file.
pf2.load_all()
if flag_options.USE_HALO_FIELD:
halo_field = determine_halo_list(
redshift=z,
init_boxes=init_box,
astro_params=astro_params,
flag_options=flag_options,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
pt_halos = perturb_halo_list(
redshift=z,
init_boxes=init_box,
astro_params=astro_params,
flag_options=flag_options,
halo_field=halo_field,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
if flag_options.USE_TS_FLUCT:
st2 = spin_temperature(
redshift=z,
previous_spin_temp=st,
astro_params=astro_params,
flag_options=flag_options,
perturbed_field=perturb_min if use_interp_perturb_field else pf2,
regenerate=regenerate,
init_boxes=init_box,
hooks=hooks,
direc=direc,
cleanup=(cleanup and iz == (len(scrollz) - 1)),
)
ib2 = ionize_box(
redshift=z,
previous_ionize_box=ib,
init_boxes=init_box,
perturbed_field=pf2,
previous_perturbed_field=prev_perturb,
astro_params=astro_params,
flag_options=flag_options,
spin_temp=st2 if flag_options.USE_TS_FLUCT else None,
pt_halos=pt_halos if flag_options.USE_HALO_FIELD else None,
regenerate=regenerate,
hooks=hooks,
direc=direc,
cleanup=(cleanup and iz == (len(scrollz) - 1)),
)
log10_mturnovers[iz] = ib2.log10_Mturnover_ave
log10_mturnovers_mini[iz] = ib2.log10_Mturnover_MINI_ave
bt2 = brightness_temperature(
ionized_box=ib2,
perturbed_field=pf2,
spin_temp=st2 if flag_options.USE_TS_FLUCT else None,
hooks=hooks,
direc=direc,
regenerate=regenerate,
)
if coeval_callback is not None and compute_coeval_callback[iz]:
coeval = Coeval(
redshift=z,
initial_conditions=init_box,
perturbed_field=pf2,
ionized_box=ib2,
brightness_temp=bt2,
ts_box=st2 if flag_options.USE_TS_FLUCT else None,
photon_nonconservation_data=_get_photon_nonconservation_data()
if flag_options.PHOTON_CONS
else None,
_globals=None,
)
try:
coeval_callback_output.append(coeval_callback(coeval))
except Exception as e:
if sum(compute_coeval_callback[: iz + 1]) == 1:
raise RuntimeError(
f"coeval_callback computation failed on first trial, z={z}."
)
else:
logger.warning(
f"coeval_callback computation failed on z={z}, skipping. {type(e).__name__}: {e}"
)
perturb_files.append((z, os.path.join(direc, pf2.filename)))
if flag_options.USE_TS_FLUCT:
spin_temp_files.append((z, os.path.join(direc, st2.filename)))
ionize_files.append((z, os.path.join(direc, ib2.filename)))
brightness_files.append((z, os.path.join(direc, bt2.filename)))
outs = {
"PerturbedField": (pf, pf2),
"IonizedBox": (ib, ib2),
"BrightnessTemp": (bt, bt2),
}
if flag_options.USE_TS_FLUCT:
outs["TsBox"] = (st, st2)
if flag_options.USE_HALO_FIELD:
outs["PerturbHaloes"] = pt_halos
# Save mean/global quantities
for quantity in global_quantities:
global_q[quantity][iz] = np.mean(
getattr(outs[_fld_names[quantity]][1], quantity)
)
# Interpolate the lightcone
if z < max_redshift:
for quantity in lightcone_quantities:
data1, data2 = outs[_fld_names[quantity]]
fnc = interp_functions.get(quantity, "mean")
n = _interpolate_in_redshift(
iz,
box_index,
lc_index,
n_lightcone,
scroll_distances,
lc_distances,
data1,
data2,
quantity,
lc[quantity],
fnc,
)
lc_index += n
box_index += n
# Save current ones as old ones.
if flag_options.USE_TS_FLUCT:
st = st2
ib = ib2
bt = bt2
if flag_options.USE_MINI_HALOS:
prev_perturb = pf2
if pf is not None:
try:
pf.purge(force=always_purge)
except OSError:
pass
pf = pf2
if flag_options.PHOTON_CONS:
photon_nonconservation_data = _get_photon_nonconservation_data()
if photon_nonconservation_data:
lib.FreePhotonConsMemory()
else:
photon_nonconservation_data = None
if (
flag_options.USE_TS_FLUCT
and user_params.USE_INTERPOLATION_TABLES
and lib.interpolation_tables_allocated
):
lib.FreeTsInterpolationTables(flag_options())
out = (
LightCone(
redshift,
user_params,
cosmo_params,
astro_params,
flag_options,
init_box.random_seed,
lc,
node_redshifts=scrollz,
global_quantities=global_q,
photon_nonconservation_data=photon_nonconservation_data,
_globals=dict(global_params.items()),
cache_files={
"init": [(0, os.path.join(direc, init_box.filename))],
"perturb_field": perturb_files,
"ionized_box": ionize_files,
"brightness_temp": brightness_files,
"spin_temp": spin_temp_files,
},
log10_mturnovers=log10_mturnovers,
log10_mturnovers_mini=log10_mturnovers_mini,
),
coeval_callback_output,
)
if coeval_callback is None:
return out[0]
else:
return out
def _get_coeval_callbacks(
scrollz: list[float], coeval_callback, coeval_callback_redshifts
) -> list[bool]:
compute_coeval_callback = [False for i in range(len(scrollz))]
if coeval_callback is not None:
if isinstance(coeval_callback_redshifts, (list, np.ndarray)):
for coeval_z in coeval_callback_redshifts:
assert isinstance(coeval_z, (int, float, np.number))
compute_coeval_callback[
np.argmin(np.abs(np.array(scrollz) - coeval_z))
] = True
if sum(compute_coeval_callback) != len(coeval_callback_redshifts):
logger.warning(
"some of the coeval_callback_redshifts refer to the same node_redshift"
)
elif (
isinstance(coeval_callback_redshifts, int) and coeval_callback_redshifts > 0
):
compute_coeval_callback = [
not i % coeval_callback_redshifts for i in range(len(scrollz))
]
else:
raise ValueError("coeval_callback_redshifts has to be list or integer > 0.")
return compute_coeval_callback
def _get_interpolation_outputs(
lightcone_quantities: Sequence,
global_quantities: Sequence,
flag_options: FlagOptions,
) -> dict[str, str]:
_fld_names = get_all_fieldnames(arrays_only=True, lightcone_only=True, as_dict=True)
incorrect_lc = [q for q in lightcone_quantities if q not in _fld_names.keys()]
if incorrect_lc:
raise ValueError(
f"The following lightcone_quantities are not available: {incorrect_lc}"
)
incorrect_gl = [q for q in global_quantities if q not in _fld_names.keys()]
if incorrect_gl:
raise ValueError(
f"The following global_quantities are not available: {incorrect_gl}"
)
if not flag_options.USE_TS_FLUCT and any(
_fld_names[q] == "TsBox" for q in lightcone_quantities + global_quantities
):
raise ValueError(
"TsBox quantity found in lightcone_quantities or global_quantities, "
"but not running spin_temp!"
)
return _fld_names
def _interpolate_in_redshift(
z_index,
box_index,
lc_index,
n_lightcone,
scroll_distances,
lc_distances,
output_obj,
output_obj2,
quantity,
lc,
kind="mean",
):
try:
array = getattr(output_obj, quantity)
array2 = getattr(output_obj2, quantity)
except AttributeError:
raise AttributeError(
f"{quantity} is not a valid field of {output_obj.__class__.__name__}"
)
assert array.__class__ == array2.__class__
# Do linear interpolation only.
prev_d = scroll_distances[z_index - 1]
this_d = scroll_distances[z_index]
# Get the cells that need to be filled on this iteration.
these_distances = lc_distances[
np.logical_and(lc_distances < prev_d, lc_distances >= this_d)
]
n = len(these_distances)
ind = np.arange(-(box_index + n), -box_index)
sub_array = array.take(ind + n_lightcone, axis=2, mode="wrap")
sub_array2 = array2.take(ind + n_lightcone, axis=2, mode="wrap")
out = (
np.abs(this_d - these_distances) * sub_array
+ np.abs(prev_d - these_distances) * sub_array2
) / (np.abs(prev_d - this_d))
if kind == "mean_max":
flag = sub_array * sub_array2 < 0
out[flag] = np.maximum(sub_array, sub_array2)[flag]
elif kind != "mean":
raise ValueError("kind must be 'mean' or 'mean_max'")
lc[:, :, -(lc_index + n) : n_lightcone - lc_index] = out
return n
def _setup_lightcone(
cosmo_params, max_redshift, redshift, scrollz, user_params, z_step_factor
):
# Here set up the lightcone box.
# Get a length of the lightcone (bigger than it needs to be at first).
d_at_redshift = cosmo_params.cosmo.comoving_distance(redshift).value
Ltotal = (
cosmo_params.cosmo.comoving_distance(scrollz[0] * z_step_factor).value
- d_at_redshift
)
lc_distances = np.arange(0, Ltotal, user_params.BOX_LEN / user_params.HII_DIM)
# Use max_redshift to get the actual distances we require.
Lmax = cosmo_params.cosmo.comoving_distance(max_redshift).value - d_at_redshift
first_greater = np.argwhere(lc_distances > Lmax)[0][0]
# Get *at least* as far as max_redshift
lc_distances = lc_distances[: (first_greater + 1)]
n_lightcone = len(lc_distances)
return d_at_redshift, lc_distances, n_lightcone
def _get_lightcone_redshifts(
cosmo_params, max_redshift, redshift, user_params, z_step_factor
):
scrollz = _logscroll_redshifts(redshift, z_step_factor, max_redshift)
lc_distances = _setup_lightcone(
cosmo_params, max_redshift, redshift, scrollz, user_params, z_step_factor
)[1]
lc_distances += cosmo_params.cosmo.comoving_distance(redshift).value
return np.array(
[
z_at_value(cosmo_params.cosmo.comoving_distance, d * units.Mpc)
for d in lc_distances
]
)
def calibrate_photon_cons(
user_params,
cosmo_params,
astro_params,
flag_options,
init_box,
regenerate,
write,
direc,
**global_kwargs,
):
r"""
Set up the photon non-conservation correction.
Scrolls through in redshift, turning off all flag_options to construct a 21cmFAST calibration
reionisation history to be matched to the analytic expression from solving the filling factor
ODE.
Parameters
----------
user_params : `~UserParams`, optional
Defines the overall options and parameters of the run.
astro_params : :class:`~AstroParams`, optional
Defines the astrophysical parameters of the run.
cosmo_params : :class:`~CosmoParams`, optional
Defines the cosmological parameters used to compute initial conditions.
flag_options: :class:`~FlagOptions`, optional
Options concerning how the reionization process is run, eg. if spin temperature
fluctuations are required.
init_box : :class:`~InitialConditions`, optional
If given, the user and cosmo params will be set from this object, and it will not be
re-calculated.
\*\*global_kwargs :
Any attributes for :class:`~py21cmfast.inputs.GlobalParams`. This will
*temporarily* set global attributes for the duration of the function. Note that
arguments will be treated as case-insensitive.
Other Parameters
----------------
regenerate, write
See docs of :func:`initial_conditions` for more information.
"""
direc, regenerate, hooks = _get_config_options(direc, regenerate, write, {})
if not flag_options.PHOTON_CONS:
return
with global_params.use(**global_kwargs):
# Create a new astro_params and flag_options just for the photon_cons correction
astro_params_photoncons = deepcopy(astro_params)
astro_params_photoncons._R_BUBBLE_MAX = astro_params.R_BUBBLE_MAX
flag_options_photoncons = FlagOptions(
USE_MASS_DEPENDENT_ZETA=flag_options.USE_MASS_DEPENDENT_ZETA,
M_MIN_in_Mass=flag_options.M_MIN_in_Mass,
USE_VELS_AUX=user_params.USE_RELATIVE_VELOCITIES,
)
ib = None
prev_perturb = None
# Arrays for redshift and neutral fraction for the calibration curve
z_for_photon_cons = []
neutral_fraction_photon_cons = []
# Initialise the analytic expression for the reionisation history
logger.info("About to start photon conservation correction")
_init_photon_conservation_correction(
user_params=user_params,
cosmo_params=cosmo_params,
astro_params=astro_params,
flag_options=flag_options,
)
# Determine the starting redshift to start scrolling through to create the
# calibration reionisation history
logger.info("Calculating photon conservation zstart")
z = _calc_zstart_photon_cons()
while z > global_params.PhotonConsEndCalibz:
# Determine the ionisation box with recombinations, spin temperature etc.
# turned off.
this_perturb = perturb_field(
redshift=z,
init_boxes=init_box,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
ib2 = ionize_box(
redshift=z,
previous_ionize_box=ib,
init_boxes=init_box,
perturbed_field=this_perturb,
previous_perturbed_field=prev_perturb,
astro_params=astro_params_photoncons,
flag_options=flag_options_photoncons,
spin_temp=None,
regenerate=regenerate,
hooks=hooks,
direc=direc,
)
mean_nf = np.mean(ib2.xH_box)
# Save mean/global quantities
neutral_fraction_photon_cons.append(mean_nf)
z_for_photon_cons.append(z)
# Can speed up sampling in regions where the evolution is slower
if 0.3 < mean_nf <= 0.9:
z -= 0.15
elif 0.01 < mean_nf <= 0.3:
z -= 0.05
else:
z -= 0.5
ib = ib2
if flag_options.USE_MINI_HALOS:
prev_perturb = this_perturb
z_for_photon_cons = np.array(z_for_photon_cons[::-1])
neutral_fraction_photon_cons = np.array(neutral_fraction_photon_cons[::-1])
# Construct the spline for the calibration curve
logger.info("Calibrating photon conservation correction")
_calibrate_photon_conservation_correction(
redshifts_estimate=z_for_photon_cons,
nf_estimate=neutral_fraction_photon_cons,
NSpline=len(z_for_photon_cons),
)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/wrapper.py
|
wrapper.py
|
"""A set of tools for reading/writing/querying the in-built cache."""
import glob
import h5py
import logging
import os
import re
from os import path
from . import outputs, wrapper
from ._cfg import config
from .wrapper import global_params
logger = logging.getLogger("21cmFAST")
def readbox(
*,
direc=None,
fname=None,
hsh=None,
kind=None,
seed=None,
redshift=None,
load_data=True,
):
"""
Read in a data set and return an appropriate object for it.
Parameters
----------
direc : str, optional
The directory in which to search for the boxes. By default, this is the
centrally-managed directory, given by the ``config.yml`` in ``~/.21cmfast/``.
fname: str, optional
The filename (without directory) of the data set. If given, this will be
preferentially used, and must exist.
hsh: str, optional
The md5 hsh of the object desired to be read. Required if `fname` not given.
kind: str, optional
The kind of dataset, eg. "InitialConditions". Will be the name of a class
defined in :mod:`~wrapper`. Required if `fname` not given.
seed: str or int, optional
The random seed of the data set to be read. If not given, and filename not
given, then a box will be read if it matches the kind and hsh, with an
arbitrary seed.
load_data: bool, optional
Whether to read in the data in the data set. Otherwise, only its defining
parameters are read.
Returns
-------
dataset :
An output object, whose type depends on the kind of data set being read.
Raises
------
IOError :
If no files exist of the given kind and hsh.
ValueError :
If either ``fname`` is not supplied, or both ``kind`` and ``hsh`` are not supplied.
"""
direc = path.expanduser(direc or config["direc"])
if not (fname or (hsh and kind)):
raise ValueError("Either fname must be supplied, or kind and hsh")
zstr = f"z{redshift:.4f}_" if redshift is not None else ""
if not fname:
if not seed:
fname = kind + "_" + zstr + hsh + "_r*.h5"
files = glob.glob(path.join(direc, fname))
if files:
fname = files[0]
else:
raise OSError("No files exist with that kind and hsh.")
else:
fname = kind + "_" + zstr + hsh + "_r" + str(seed) + ".h5"
kind = _parse_fname(fname)["kind"]
cls = getattr(outputs, kind)
if hasattr(cls, "from_file"):
inst = cls.from_file(fname, direc=direc, load_data=load_data)
else:
inst = cls.read(fname, direc=direc)
return inst
def _parse_fname(fname):
patterns = (
r"(?P<kind>\w+)_(?P<hash>\w{32})_r(?P<seed>\d+).h5$",
r"(?P<kind>\w+)_z(?P<redshift>\d+.\d{1,4})_(?P<hash>\w{32})_r(?P<seed>\d+).h5$",
)
for pattern in patterns:
match = re.match(pattern, os.path.basename(fname))
if match:
break
if not match:
raise ValueError(
"filename {} does not have correct format for a cached output.".format(
fname
)
)
return match.groupdict()
def list_datasets(*, direc=None, kind=None, hsh=None, seed=None, redshift=None):
"""Yield all datasets which match a given set of filters.
Can be used to determine parameters of all cached datasets, in conjunction with :func:`readbox`.
Parameters
----------
direc : str, optional
The directory in which to search for the boxes. By default, this is the centrally-managed
directory, given by the ``config.yml`` in ``.21cmfast``.
kind: str, optional
Filter by this kind (one of {"InitialConditions", "PerturbedField", "IonizedBox",
"TsBox", "BrightnessTemp"}
hsh: str, optional
Filter by this hsh.
seed: str, optional
Filter by this seed.
Yields
------
fname: str
The filename of the dataset (without directory).
parts: tuple of strings
The (kind, hsh, seed) of the data set.
"""
direc = path.expanduser(direc or config["direc"])
fname = "{}{}_{}_r{}.h5".format(
kind or r"(?P<kind>[a-zA-Z]+)",
f"_z{redshift:.4f}" if redshift is not None else "(.*)",
hsh or r"(?P<hash>\w{32})",
seed or r"(?P<seed>\d+)",
)
for fl in os.listdir(direc):
if re.match(fname, fl):
yield fl
def query_cache(
*, direc=None, kind=None, hsh=None, seed=None, redshift=None, show=True
):
"""Get or print datasets in the cache.
Walks through the cache, with given filters, and return all un-initialised dataset
objects, optionally printing their representation to screen.
Useful for querying which kinds of datasets are available within the cache, and
choosing one to read and use.
Parameters
----------
direc : str, optional
The directory in which to search for the boxes. By default, this is the
centrally-managed directory, given by the ``config.yml`` in ``~/.21cmfast``.
kind: str, optional
Filter by this kind. Must be one of "InitialConditions", "PerturbedField",
"IonizedBox", "TsBox" or "BrightnessTemp".
hsh: str, optional
Filter by this hsh.
seed: str, optional
Filter by this seed.
show: bool, optional
Whether to print out a repr of each object that exists.
Yields
------
obj:
Output objects, un-initialized.
"""
for file in list_datasets(
direc=direc, kind=kind, hsh=hsh, seed=seed, redshift=redshift
):
cls = readbox(direc=direc, fname=file, load_data=False)
if show:
print(file + ": " + str(cls)) # noqa: T
yield file, cls
def clear_cache(**kwargs):
"""Delete datasets in the cache.
Walks through the cache, with given filters, and deletes all un-initialised dataset
objects, optionally printing their representation to screen.
Parameters
----------
kwargs :
All options passed through to :func:`query_cache`.
"""
if "show" not in kwargs:
kwargs["show"] = False
direc = kwargs.get("direc", path.expanduser(config["direc"]))
number = 0
for fname, _ in query_cache(**kwargs):
if kwargs.get("show", True):
logger.info(f"Removing {fname}")
os.remove(path.join(direc, fname))
number += 1
logger.info(f"Removed {number} files from cache.")
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/cache_tools.py
|
cache_tools.py
|
# file generated by setuptools_scm
# don't change, don't track in version control
__version__ = version = '3.3.1'
__version_tuple__ = version_tuple = (3, 3, 1)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/_version.py
|
_version.py
|
"""
Output class objects.
The classes provided by this module exist to simplify access to large datasets created within C.
Fundamentally, ownership of the data belongs to these classes, and the C functions merely accesses
this and fills it. The various boxes and lightcones associated with each output are available as
instance attributes. Along with the output data, each output object contains the various input
parameter objects necessary to define it.
.. warning:: These should not be instantiated or filled by the user, but always handled
as output objects from the various functions contained here. Only the data
within the objects should be accessed.
"""
from __future__ import annotations
import h5py
import numpy as np
import os
import warnings
from astropy import units
from astropy.cosmology import z_at_value
from cached_property import cached_property
from hashlib import md5
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Tuple, Union
from . import __version__
from . import _utils as _ut
from ._cfg import config
from ._utils import OutputStruct as _BaseOutputStruct
from ._utils import _check_compatible_inputs
from .c_21cmfast import ffi, lib
from .inputs import AstroParams, CosmoParams, FlagOptions, UserParams, global_params
class _OutputStruct(_BaseOutputStruct):
_global_params = global_params
def __init__(self, *, user_params=None, cosmo_params=None, **kwargs):
self.cosmo_params = cosmo_params or CosmoParams()
self.user_params = user_params or UserParams()
super().__init__(**kwargs)
_ffi = ffi
class _OutputStructZ(_OutputStruct):
_inputs = _OutputStruct._inputs + ("redshift",)
class InitialConditions(_OutputStruct):
"""A class containing all initial conditions boxes."""
_c_compute_function = lib.ComputeInitialConditions
# The filter params indicates parameters to overlook when deciding if a cached box
# matches current parameters.
# It is useful for ignoring certain global parameters which may not apply to this
# step or its dependents.
_meta = False
_filter_params = _OutputStruct._filter_params + [
"ALPHA_UVB", # ionization
"EVOLVE_DENSITY_LINEARLY", # perturb
"SMOOTH_EVOLVED_DENSITY_FIELD", # perturb
"R_smooth_density", # perturb
"HII_ROUND_ERR", # ionization
"FIND_BUBBLE_ALGORITHM", # ib
"N_POISSON", # ib
"T_USE_VELOCITIES", # bt
"MAX_DVDR", # bt
"DELTA_R_HII_FACTOR", # ib
"HII_FILTER", # ib
"INITIAL_REDSHIFT", # pf
"HEAT_FILTER", # st
"CLUMPING_FACTOR", # st
"Z_HEAT_MAX", # st
"R_XLy_MAX", # st
"NUM_FILTER_STEPS_FOR_Ts", # ts
"ZPRIME_STEP_FACTOR", # ts
"TK_at_Z_HEAT_MAX", # ts
"XION_at_Z_HEAT_MAX", # ts
"Pop", # ib
"Pop2_ion", # ib
"Pop3_ion", # ib
"NU_X_BAND_MAX", # st
"NU_X_MAX", # ib
]
def prepare_for_perturb(self, flag_options: FlagOptions, force: bool = False):
"""Ensure the ICs have all the boxes loaded for perturb, but no extra."""
keep = ["hires_density"]
if not self.user_params.PERTURB_ON_HIGH_RES:
keep.append("lowres_density")
keep.append("lowres_vx")
keep.append("lowres_vy")
keep.append("lowres_vz")
if self.user_params.USE_2LPT:
keep.append("lowres_vx_2LPT")
keep.append("lowres_vy_2LPT")
keep.append("lowres_vz_2LPT")
if flag_options.USE_HALO_FIELD:
keep.append("hires_density")
else:
keep.append("hires_vx")
keep.append("hires_vy")
keep.append("hires_vz")
if self.user_params.USE_2LPT:
keep.append("hires_vx_2LPT")
keep.append("hires_vy_2LPT")
keep.append("hires_vz_2LPT")
if self.user_params.USE_RELATIVE_VELOCITIES:
keep.append("lowres_vcb")
self.prepare(keep=keep, force=force)
def prepare_for_spin_temp(self, flag_options: FlagOptions, force: bool = False):
"""Ensure ICs have all boxes required for spin_temp, and no more."""
keep = []
if self.user_params.USE_RELATIVE_VELOCITIES:
keep.append("lowres_vcb")
self.prepare(keep=keep, force=force)
def _get_box_structures(self) -> dict[str, dict | tuple[int]]:
shape = (self.user_params.HII_DIM,) * 2 + (
int(self.user_params.NON_CUBIC_FACTOR * self.user_params.HII_DIM),
)
hires_shape = (self.user_params.DIM,) * 2 + (
int(self.user_params.NON_CUBIC_FACTOR * self.user_params.DIM),
)
out = {
"lowres_density": shape,
"lowres_vx": shape,
"lowres_vy": shape,
"lowres_vz": shape,
"hires_density": hires_shape,
"hires_vx": hires_shape,
"hires_vy": hires_shape,
"hires_vz": hires_shape,
}
if self.user_params.USE_2LPT:
out.update(
{
"lowres_vx_2LPT": shape,
"lowres_vy_2LPT": shape,
"lowres_vz_2LPT": shape,
"hires_vx_2LPT": hires_shape,
"hires_vy_2LPT": hires_shape,
"hires_vz_2LPT": hires_shape,
}
)
if self.user_params.USE_RELATIVE_VELOCITIES:
out.update({"lowres_vcb": shape})
return out
def get_required_input_arrays(self, input_box: _BaseOutputStruct) -> list[str]:
"""Return all input arrays required to compute this object."""
return []
def compute(self, hooks: dict):
"""Compute the function."""
return self._compute(
self.random_seed,
self.user_params,
self.cosmo_params,
hooks=hooks,
)
class PerturbedField(_OutputStructZ):
"""A class containing all perturbed field boxes."""
_c_compute_function = lib.ComputePerturbField
_meta = False
_filter_params = _OutputStruct._filter_params + [
"ALPHA_UVB", # ionization
"HII_ROUND_ERR", # ionization
"FIND_BUBBLE_ALGORITHM", # ib
"N_POISSON", # ib
"T_USE_VELOCITIES", # bt
"MAX_DVDR", # bt
"DELTA_R_HII_FACTOR", # ib
"HII_FILTER", # ib
"HEAT_FILTER", # st
"CLUMPING_FACTOR", # st
"Z_HEAT_MAX", # st
"R_XLy_MAX", # st
"NUM_FILTER_STEPS_FOR_Ts", # ts
"ZPRIME_STEP_FACTOR", # ts
"TK_at_Z_HEAT_MAX", # ts
"XION_at_Z_HEAT_MAX", # ts
"Pop", # ib
"Pop2_ion", # ib
"Pop3_ion", # ib
"NU_X_BAND_MAX", # st
"NU_X_MAX", # ib
]
def _get_box_structures(self) -> dict[str, dict | tuple[int]]:
return {
"density": (self.user_params.HII_DIM,) * 2
+ (int(self.user_params.NON_CUBIC_FACTOR * self.user_params.HII_DIM),),
"velocity": (self.user_params.HII_DIM,) * 2
+ (int(self.user_params.NON_CUBIC_FACTOR * self.user_params.HII_DIM),),
}
def get_required_input_arrays(self, input_box: _BaseOutputStruct) -> list[str]:
"""Return all input arrays required to compute this object."""
required = []
if not isinstance(input_box, InitialConditions):
raise ValueError(
f"{type(input_box)} is not an input required for PerturbedField!"
)
# Always require hires_density
required += ["hires_density"]
if self.user_params.PERTURB_ON_HIGH_RES:
required += ["hires_vx", "hires_vy", "hires_vz"]
if self.user_params.USE_2LPT:
required += ["hires_vx_2LPT", "hires_vy_2LPT", "hires_vz_2LPT"]
else:
required += ["lowres_density", "lowres_vx", "lowres_vy", "lowres_vz"]
if self.user_params.USE_2LPT:
required += [
"lowres_vx_2LPT",
"lowres_vy_2LPT",
"lowres_vz_2LPT",
]
if self.user_params.USE_RELATIVE_VELOCITIES:
required.append("lowres_vcb")
return required
def compute(self, *, ics: InitialConditions, hooks: dict):
"""Compute the function."""
return self._compute(
self.redshift,
self.user_params,
self.cosmo_params,
ics,
hooks=hooks,
)
class _AllParamsBox(_OutputStructZ):
_meta = True
_inputs = _OutputStructZ._inputs + ("flag_options", "astro_params")
_filter_params = _OutputStruct._filter_params + [
"T_USE_VELOCITIES", # bt
"MAX_DVDR", # bt
]
def __init__(
self,
*,
astro_params: AstroParams | None = None,
flag_options: FlagOptions | None = None,
**kwargs,
):
self.flag_options = flag_options or FlagOptions()
self.astro_params = astro_params or AstroParams(
INHOMO_RECO=self.flag_options.INHOMO_RECO
)
self.log10_Mturnover_ave = 0.0
self.log10_Mturnover_MINI_ave = 0.0
super().__init__(**kwargs)
class HaloField(_AllParamsBox):
"""A class containing all fields related to halos."""
_c_based_pointers = (
"halo_masses",
"halo_coords",
"mass_bins",
"fgtrm",
"sqrt_dfgtrm",
"dndlm",
"sqrtdn_dlm",
)
_c_compute_function = lib.ComputeHaloField
def _get_box_structures(self) -> dict[str, dict | tuple[int]]:
return {}
def _c_shape(self, cstruct):
return {
"halo_masses": (cstruct.n_halos,),
"halo_coords": (cstruct.n_halos, 3),
"mass_bins": (cstruct.n_mass_bins,),
"fgtrm": (cstruct.n_mass_bins,),
"sqrt_dfgtrm": (cstruct.n_mass_bins,),
"dndlm": (cstruct.n_mass_bins,),
"sqrtdn_dlm": (cstruct.n_mass_bins,),
}
def get_required_input_arrays(self, input_box: _BaseOutputStruct) -> list[str]:
"""Return all input arrays required to compute this object."""
if isinstance(input_box, InitialConditions):
return ["hires_density"]
else:
raise ValueError(
f"{type(input_box)} is not an input required for HaloField!"
)
def compute(self, *, ics: InitialConditions, hooks: dict):
"""Compute the function."""
return self._compute(
self.redshift,
self.user_params,
self.cosmo_params,
self.astro_params,
self.flag_options,
ics,
hooks=hooks,
)
class PerturbHaloField(_AllParamsBox):
"""A class containing all fields related to halos."""
_c_compute_function = lib.ComputePerturbHaloField
_c_based_pointers = ("halo_masses", "halo_coords")
def _get_box_structures(self) -> dict[str, dict | tuple[int]]:
return {}
def _c_shape(self, cstruct):
return {
"halo_masses": (cstruct.n_halos,),
"halo_coords": (cstruct.n_halos, 3),
}
def get_required_input_arrays(self, input_box: _BaseOutputStruct) -> list[str]:
"""Return all input arrays required to compute this object."""
required = []
if isinstance(input_box, InitialConditions):
if self.user_params.PERTURB_ON_HIGH_RES:
required += ["hires_vx", "hires_vy", "hires_vz"]
else:
required += ["lowres_vx", "lowres_vy", "lowres_vz"]
if self.user_params.USE_2LPT:
required += [k + "_2LPT" for k in required]
elif isinstance(input_box, HaloField):
required += ["halo_coords", "halo_masses"]
else:
raise ValueError(
f"{type(input_box)} is not an input required for PerturbHaloField!"
)
return required
def compute(self, *, ics: InitialConditions, halo_field: HaloField, hooks: dict):
"""Compute the function."""
return self._compute(
self.redshift,
self.user_params,
self.cosmo_params,
self.astro_params,
self.flag_options,
ics,
halo_field,
hooks=hooks,
)
class TsBox(_AllParamsBox):
"""A class containing all spin temperature boxes."""
_c_compute_function = lib.ComputeTsBox
_meta = False
_inputs = _AllParamsBox._inputs + ("prev_spin_redshift", "perturbed_field_redshift")
def __init__(
self,
*,
prev_spin_redshift: float | None = None,
perturbed_field_redshift: float | None = None,
**kwargs,
):
self.prev_spin_redshift = prev_spin_redshift
self.perturbed_field_redshift = perturbed_field_redshift
super().__init__(**kwargs)
def _get_box_structures(self) -> dict[str, dict | tuple[int]]:
shape = (self.user_params.HII_DIM,) * 2 + (
int(self.user_params.NON_CUBIC_FACTOR * self.user_params.HII_DIM),
)
return {
"Ts_box": shape,
"x_e_box": shape,
"Tk_box": shape,
"J_21_LW_box": shape,
}
@cached_property
def global_Ts(self):
"""Global (mean) spin temperature."""
if "Ts_box" not in self._computed_arrays:
raise AttributeError(
"global_Ts is not defined until the ionization calculation has been performed"
)
else:
return np.mean(self.Ts_box)
@cached_property
def global_Tk(self):
"""Global (mean) Tk."""
if "Tk_box" not in self._computed_arrays:
raise AttributeError(
"global_Tk is not defined until the ionization calculation has been performed"
)
else:
return np.mean(self.Tk_box)
@cached_property
def global_x_e(self):
"""Global (mean) x_e."""
if "x_e_box" not in self._computed_arrays:
raise AttributeError(
"global_x_e is not defined until the ionization calculation has been performed"
)
else:
return np.mean(self.x_e_box)
def get_required_input_arrays(self, input_box: _BaseOutputStruct) -> list[str]:
"""Return all input arrays required to compute this object."""
required = []
if isinstance(input_box, InitialConditions):
if (
self.user_params.USE_RELATIVE_VELOCITIES
and self.flag_options.USE_MINI_HALOS
):
required += ["lowres_vcb"]
elif isinstance(input_box, PerturbedField):
required += ["density"]
elif isinstance(input_box, TsBox):
required += [
"Tk_box",
"x_e_box",
]
if self.flag_options.USE_MINI_HALOS:
required += ["J_21_LW_box"]
else:
raise ValueError(
f"{type(input_box)} is not an input required for PerturbHaloField!"
)
return required
def compute(
self,
*,
cleanup: bool,
perturbed_field: PerturbedField,
prev_spin_temp,
ics: InitialConditions,
hooks: dict,
):
"""Compute the function."""
return self._compute(
self.redshift,
self.prev_spin_redshift,
self.user_params,
self.cosmo_params,
self.astro_params,
self.flag_options,
self.perturbed_field_redshift,
cleanup,
perturbed_field,
prev_spin_temp,
ics,
hooks=hooks,
)
class IonizedBox(_AllParamsBox):
"""A class containing all ionized boxes."""
_meta = False
_c_compute_function = lib.ComputeIonizedBox
_inputs = _AllParamsBox._inputs + ("prev_ionize_redshift",)
def __init__(self, *, prev_ionize_redshift: float | None = None, **kwargs):
self.prev_ionize_redshift = prev_ionize_redshift
super().__init__(**kwargs)
def _get_box_structures(self) -> dict[str, dict | tuple[int]]:
if self.flag_options.USE_MINI_HALOS:
n_filtering = (
int(
np.log(
min(
self.astro_params.R_BUBBLE_MAX,
0.620350491 * self.user_params.BOX_LEN,
)
/ max(
global_params.R_BUBBLE_MIN,
0.620350491
* self.user_params.BOX_LEN
/ self.user_params.HII_DIM,
)
)
/ np.log(global_params.DELTA_R_HII_FACTOR)
)
+ 1
)
else:
n_filtering = 1
shape = (self.user_params.HII_DIM,) * 2 + (
int(self.user_params.NON_CUBIC_FACTOR * self.user_params.HII_DIM),
)
filter_shape = (n_filtering,) + shape
out = {
"xH_box": {"init": np.ones, "shape": shape},
"Gamma12_box": shape,
"MFP_box": shape,
"z_re_box": shape,
"dNrec_box": shape,
"temp_kinetic_all_gas": shape,
"Fcoll": filter_shape,
}
if self.flag_options.USE_MINI_HALOS:
out["Fcoll_MINI"] = filter_shape
return out
@cached_property
def global_xH(self):
"""Global (mean) neutral fraction."""
if not self.filled:
raise AttributeError(
"global_xH is not defined until the ionization calculation has been performed"
)
else:
return np.mean(self.xH_box)
def get_required_input_arrays(self, input_box: _BaseOutputStruct) -> list[str]:
"""Return all input arrays required to compute this object."""
required = []
if isinstance(input_box, InitialConditions):
if (
self.user_params.USE_RELATIVE_VELOCITIES
and self.flag_options.USE_MASS_DEPENDENT_ZETA
):
required += ["lowres_vcb"]
elif isinstance(input_box, PerturbedField):
required += ["density"]
elif isinstance(input_box, TsBox):
required += ["J_21_LW_box", "x_e_box", "Tk_box"]
elif isinstance(input_box, IonizedBox):
required += ["z_re_box", "Gamma12_box"]
if self.flag_options.INHOMO_RECO:
required += [
"dNrec_box",
]
if (
self.flag_options.USE_MASS_DEPENDENT_ZETA
and self.flag_options.USE_MINI_HALOS
):
required += ["Fcoll", "Fcoll_MINI"]
elif isinstance(input_box, PerturbHaloField):
required += ["halo_coords", "halo_masses"]
else:
raise ValueError(
f"{type(input_box)} is not an input required for IonizedBox!"
)
return required
def compute(
self,
*,
perturbed_field: PerturbedField,
prev_perturbed_field: PerturbedField,
prev_ionize_box,
spin_temp: TsBox,
pt_halos: PerturbHaloField,
ics: InitialConditions,
hooks: dict,
):
"""Compute the function."""
return self._compute(
self.redshift,
self.prev_ionize_redshift,
self.user_params,
self.cosmo_params,
self.astro_params,
self.flag_options,
perturbed_field,
prev_perturbed_field,
prev_ionize_box,
spin_temp,
pt_halos,
ics,
hooks=hooks,
)
class BrightnessTemp(_AllParamsBox):
"""A class containing the brightness temperature box."""
_c_compute_function = lib.ComputeBrightnessTemp
_meta = False
_filter_params = _OutputStructZ._filter_params
def _get_box_structures(self) -> dict[str, dict | tuple[int]]:
return {
"brightness_temp": (self.user_params.HII_DIM,) * 2
+ (int(self.user_params.NON_CUBIC_FACTOR * self.user_params.HII_DIM),)
}
@cached_property
def global_Tb(self):
"""Global (mean) brightness temperature."""
if not self.is_computed:
raise AttributeError(
"global_Tb is not defined until the ionization calculation has been performed"
)
else:
return np.mean(self.brightness_temp)
def get_required_input_arrays(self, input_box: _BaseOutputStruct) -> list[str]:
"""Return all input arrays required to compute this object."""
required = []
if isinstance(input_box, PerturbedField):
required += ["velocity"]
elif isinstance(input_box, TsBox):
required += ["Ts_box"]
elif isinstance(input_box, IonizedBox):
required += ["xH_box"]
else:
raise ValueError(
f"{type(input_box)} is not an input required for BrightnessTemp!"
)
return required
def compute(
self,
*,
spin_temp: TsBox,
ionized_box: IonizedBox,
perturbed_field: PerturbedField,
hooks: dict,
):
"""Compute the function."""
return self._compute(
self.redshift,
self.user_params,
self.cosmo_params,
self.astro_params,
self.flag_options,
spin_temp,
ionized_box,
perturbed_field,
hooks=hooks,
)
class _HighLevelOutput:
def get_cached_data(
self, kind: str, redshift: float, load_data: bool = False
) -> _OutputStruct:
"""
Return an OutputStruct object which was cached in creating this Coeval box.
Parameters
----------
kind
The kind of object: "init", "perturb", "spin_temp", "ionize" or "brightness"
redshift
The (approximate) redshift of the object to return.
load_data
Whether to actually read the field data of the object in (call ``obj.read()``
after this function to do this manually)
Returns
-------
output
The output struct object.
"""
if self.cache_files is None:
raise AttributeError(
"No cache files were associated with this Coeval object."
)
# TODO: also check this file, because it may have been "gather"d.
if kind not in self.cache_files:
raise ValueError(
f"{kind} is not a valid kind for the cache. Valid options: "
f"{self.cache_files.keys()}"
)
files = self.cache_files.get(kind, {})
# files is a list of tuples of (redshift, filename)
redshifts = np.array([f[0] for f in files])
indx = np.argmin(np.abs(redshifts - redshift))
fname = files[indx][1]
if not os.path.exists(fname):
raise OSError(
"The cached file you requested does not exist (maybe it was removed?)."
)
kinds = {
"init": InitialConditions,
"perturb_field": PerturbedField,
"ionized_box": IonizedBox,
"spin_temp": TsBox,
"brightness_temp": BrightnessTemp,
}
cls = kinds[kind]
return cls.from_file(fname, load_data=load_data)
def gather(
self,
fname: str | None | Path = None,
kinds: Sequence | None = None,
clean: bool | dict = False,
direc: str | Path | None = None,
) -> Path:
"""Gather the cached data associated with this object into its file."""
kinds = kinds or [
"init",
"perturb_field",
"ionized_box",
"spin_temp",
"brightness_temp",
]
clean = kinds if clean and not hasattr(clean, "__len__") else clean or []
if any(c not in kinds for c in clean):
raise ValueError(
"You are trying to clean cached items that you will not be gathering."
)
direc = Path(direc or config["direc"]).expanduser().absolute()
fname = Path(fname or self.get_unique_filename()).expanduser()
if not fname.exists():
fname = direc / fname
for kind in kinds:
redshifts = (f[0] for f in self.cache_files[kind])
for i, z in enumerate(redshifts):
cache_fname = self.cache_files[kind][i][1]
obj = self.get_cached_data(kind, redshift=z, load_data=True)
with h5py.File(fname, "a") as fl:
cache = (
fl.create_group("cache") if "cache" not in fl else fl["cache"]
)
kind_group = (
cache.create_group(kind) if kind not in cache else cache[kind]
)
zstr = f"z{z:.2f}"
if zstr not in kind_group:
z_group = kind_group.create_group(zstr)
else:
z_group = kind_group[zstr]
obj.write_data_to_hdf5_group(z_group)
if kind in clean:
os.remove(cache_fname)
return fname
def _get_prefix(self):
return "{name}_z{redshift:.4}_{{hash}}_r{seed}.h5".format(
name=self.__class__.__name__,
redshift=float(self.redshift),
seed=self.random_seed,
)
def _input_rep(self):
rep = ""
for inp in [
"user_params",
"cosmo_params",
"astro_params",
"flag_options",
"global_params",
]:
rep += repr(getattr(self, inp))
return rep
def get_unique_filename(self):
"""Generate a unique hash filename for this instance."""
return self._get_prefix().format(
hash=md5((self._input_rep() + self._particular_rep()).encode()).hexdigest()
)
def _write(self, direc=None, fname=None, clobber=False):
"""
Write the lightcone to file in standard HDF5 format.
This method is primarily meant for the automatic caching. Its default
filename is a hash generated based on the input data, and the directory is
the configured caching directory.
Parameters
----------
direc : str, optional
The directory into which to write the file. Default is the configuration
directory.
fname : str, optional
The filename to write, default a unique name produced by the inputs.
clobber : bool, optional
Whether to overwrite existing file.
Returns
-------
fname : str
The absolute path to which the file was written.
"""
direc = os.path.expanduser(direc or config["direc"])
if fname is None:
fname = self.get_unique_filename()
if not os.path.isabs(fname):
fname = os.path.abspath(os.path.join(direc, fname))
if not clobber and os.path.exists(fname):
raise FileExistsError(
"The file {} already exists. If you want to overwrite, set clobber=True.".format(
fname
)
)
with h5py.File(fname, "w") as f:
# Save input parameters as attributes
for k in [
"user_params",
"cosmo_params",
"flag_options",
"astro_params",
"global_params",
]:
q = getattr(self, k)
kfile = "_globals" if k == "global_params" else k
grp = f.create_group(kfile)
try:
dct = q.self
except AttributeError:
dct = q
for kk, v in dct.items():
if v is None:
continue
try:
grp.attrs[kk] = v
except TypeError:
# external_table_path is a cdata object and can't be written.
pass
if self.photon_nonconservation_data is not None:
photon_data = f.create_group("photon_nonconservation_data")
for k, val in self.photon_nonconservation_data.items():
photon_data[k] = val
f.attrs["redshift"] = self.redshift
f.attrs["random_seed"] = self.random_seed
f.attrs["version"] = __version__
self._write_particulars(fname)
return fname
def _write_particulars(self, fname):
pass
def save(self, fname=None, direc="."):
"""Save to disk.
This function has defaults that make it easy to save a unique box to
the current directory.
Parameters
----------
fname : str, optional
The filename to write, default a unique name produced by the inputs.
direc : str, optional
The directory into which to write the file. Default is the current directory.
Returns
-------
str :
The filename to which the box was written.
"""
return self._write(direc=direc, fname=fname)
@classmethod
def _read_inputs(cls, fname):
kwargs = {}
with h5py.File(fname, "r") as fl:
glbls = dict(fl["_globals"].attrs)
kwargs["redshift"] = fl.attrs["redshift"]
if "photon_nonconservation_data" in fl.keys():
d = fl["photon_nonconservation_data"]
kwargs["photon_nonconservation_data"] = {k: d[k][...] for k in d.keys()}
return kwargs, glbls
@classmethod
def read(cls, fname, direc="."):
"""Read a lightcone file from disk, creating a LightCone object.
Parameters
----------
fname : str
The filename path. Can be absolute or relative.
direc : str
If fname, is relative, the directory in which to find the file. By default,
both the current directory and default cache and the will be searched, in
that order.
Returns
-------
LightCone :
A :class:`LightCone` instance created from the file's data.
"""
if not os.path.isabs(fname):
fname = os.path.abspath(os.path.join(direc, fname))
if not os.path.exists(fname):
raise FileExistsError(f"The file {fname} does not exist!")
park, glbls = cls._read_inputs(fname)
boxk = cls._read_particular(fname)
with global_params.use(**glbls):
out = cls(**park, **boxk)
return out
class Coeval(_HighLevelOutput):
"""A full coeval box with all associated data."""
def __init__(
self,
redshift: float,
initial_conditions: InitialConditions,
perturbed_field: PerturbedField,
ionized_box: IonizedBox,
brightness_temp: BrightnessTemp,
ts_box: TsBox | None = None,
cache_files: dict | None = None,
photon_nonconservation_data=None,
_globals=None,
):
_check_compatible_inputs(
initial_conditions,
perturbed_field,
ionized_box,
brightness_temp,
ts_box,
ignore=[],
)
self.redshift = redshift
self.init_struct = initial_conditions
self.perturb_struct = perturbed_field
self.ionization_struct = ionized_box
self.brightness_temp_struct = brightness_temp
self.spin_temp_struct = ts_box
self.cache_files = cache_files
self.photon_nonconservation_data = photon_nonconservation_data
# A *copy* of the current global parameters.
self.global_params = _globals or dict(global_params.items())
# Expose all the fields of the structs to the surface of the Coeval object
for box in [
initial_conditions,
perturbed_field,
ionized_box,
brightness_temp,
ts_box,
]:
if box is None:
continue
for field in box._get_box_structures():
setattr(self, field, getattr(box, field))
@classmethod
def get_fields(cls, spin_temp: bool = True) -> list[str]:
"""Obtain a list of name of simulation boxes saved in the Coeval object."""
pointer_fields = []
for cls in [InitialConditions, PerturbedField, IonizedBox, BrightnessTemp]:
pointer_fields += cls.get_pointer_fields()
if spin_temp:
pointer_fields += TsBox.get_pointer_fields()
return pointer_fields
@property
def user_params(self):
"""User params shared by all datasets."""
return self.brightness_temp_struct.user_params
@property
def cosmo_params(self):
"""Cosmo params shared by all datasets."""
return self.brightness_temp_struct.cosmo_params
@property
def flag_options(self):
"""Flag Options shared by all datasets."""
return self.brightness_temp_struct.flag_options
@property
def astro_params(self):
"""Astro params shared by all datasets."""
return self.brightness_temp_struct.astro_params
@property
def random_seed(self):
"""Random seed shared by all datasets."""
return self.brightness_temp_struct.random_seed
def _particular_rep(self):
return ""
def _write_particulars(self, fname):
for name in ["init", "perturb", "ionization", "brightness_temp", "spin_temp"]:
struct = getattr(self, name + "_struct")
if struct is not None:
struct.write(fname=fname, write_inputs=False)
# Also write any other inputs to any of the constituent boxes
# to the overarching attrs.
with h5py.File(fname, "a") as fl:
for inp in struct._inputs:
if inp not in fl.attrs and inp not in [
"user_params",
"cosmo_params",
"flag_options",
"astro_params",
"global_params",
]:
fl.attrs[inp] = getattr(struct, inp)
@classmethod
def _read_particular(cls, fname):
kwargs = {}
with h5py.File(fname, "r") as fl:
for output_class in _ut.OutputStruct._implementations():
if output_class.__name__ in fl:
kwargs[
_ut.camel_to_snake(output_class.__name__)
] = output_class.from_file(fname)
return kwargs
def __eq__(self, other):
"""Determine if this is equal to another object."""
return (
isinstance(other, self.__class__)
and other.redshift == self.redshift
and self.user_params == other.user_params
and self.cosmo_params == other.cosmo_params
and self.flag_options == other.flag_options
and self.astro_params == other.astro_params
)
class LightCone(_HighLevelOutput):
"""A full Lightcone with all associated evolved data."""
def __init__(
self,
redshift,
user_params,
cosmo_params,
astro_params,
flag_options,
random_seed,
lightcones,
node_redshifts=None,
global_quantities=None,
photon_nonconservation_data=None,
cache_files: dict | None = None,
_globals=None,
log10_mturnovers=None,
log10_mturnovers_mini=None,
):
self.redshift = redshift
self.random_seed = random_seed
self.user_params = user_params
self.cosmo_params = cosmo_params
self.astro_params = astro_params
self.flag_options = flag_options
self.node_redshifts = node_redshifts
self.cache_files = cache_files
self.log10_mturnovers = log10_mturnovers
self.log10_mturnovers_mini = log10_mturnovers_mini
# A *copy* of the current global parameters.
self.global_params = _globals or dict(global_params.items())
if global_quantities:
for name, data in global_quantities.items():
if name.endswith("_box"):
# Remove the _box because it looks dumb.
setattr(self, "global_" + name[:-4], data)
else:
setattr(self, "global_" + name, data)
self.photon_nonconservation_data = photon_nonconservation_data
for name, data in lightcones.items():
setattr(self, name, data)
# Hold a reference to the global/lightcones in a dict form for easy reference.
self.global_quantities = global_quantities
self.lightcones = lightcones
@property
def global_xHI(self):
"""Global neutral fraction function."""
warnings.warn(
"global_xHI is deprecated. From now on, use global_xH. Will be removed in v3.1"
)
return self.global_xH
@property
def cell_size(self):
"""Cell size [Mpc] of the lightcone voxels."""
return self.user_params.BOX_LEN / self.user_params.HII_DIM
@property
def lightcone_dimensions(self):
"""Lightcone size over each dimension -- tuple of (x,y,z) in Mpc."""
return (
self.user_params.BOX_LEN,
self.user_params.BOX_LEN,
self.n_slices * self.cell_size,
)
@property
def shape(self):
"""Shape of the lightcone as a 3-tuple."""
return self.brightness_temp.shape
@property
def n_slices(self):
"""Number of redshift slices in the lightcone."""
return self.shape[-1]
@property
def lightcone_coords(self):
"""Co-ordinates [Mpc] of each cell along the redshift axis."""
return np.linspace(0, self.lightcone_dimensions[-1], self.n_slices)
@property
def lightcone_distances(self):
"""Comoving distance to each cell along the redshift axis, from z=0."""
return (
self.cosmo_params.cosmo.comoving_distance(self.redshift).value
+ self.lightcone_coords
)
@property
def lightcone_redshifts(self):
"""Redshift of each cell along the redshift axis."""
return np.array(
[
z_at_value(self.cosmo_params.cosmo.comoving_distance, d * units.Mpc)
for d in self.lightcone_distances
]
)
def _particular_rep(self):
return (
str(np.round(self.node_redshifts, 3))
+ str(self.global_quantities.keys())
+ str(self.lightcones.keys())
)
def _write_particulars(self, fname):
with h5py.File(fname, "a") as f:
# Save the boxes to the file
boxes = f.create_group("lightcones")
# Go through all fields in this struct, and save
for k, val in self.lightcones.items():
boxes[k] = val
global_q = f.create_group("global_quantities")
for k, v in self.global_quantities.items():
global_q[k] = v
f["node_redshifts"] = self.node_redshifts
@classmethod
def _read_inputs(cls, fname):
kwargs = {}
with h5py.File(fname, "r") as fl:
for k, kls in [
("user_params", UserParams),
("cosmo_params", CosmoParams),
("flag_options", FlagOptions),
("astro_params", AstroParams),
]:
grp = fl[k]
kwargs[k] = kls(dict(grp.attrs))
kwargs["random_seed"] = fl.attrs["random_seed"]
# Get the standard inputs.
kw, glbls = _HighLevelOutput._read_inputs(fname)
return {**kw, **kwargs}, glbls
@classmethod
def _read_particular(cls, fname):
kwargs = {}
with h5py.File(fname, "r") as fl:
boxes = fl["lightcones"]
kwargs["lightcones"] = {k: boxes[k][...] for k in boxes.keys()}
glb = fl["global_quantities"]
kwargs["global_quantities"] = {k: glb[k][...] for k in glb.keys()}
kwargs["node_redshifts"] = fl["node_redshifts"][...]
return kwargs
def __eq__(self, other):
"""Determine if this is equal to another object."""
return (
isinstance(other, self.__class__)
and other.redshift == self.redshift
and np.all(np.isclose(other.node_redshifts, self.node_redshifts, atol=1e-3))
and self.user_params == other.user_params
and self.cosmo_params == other.cosmo_params
and self.flag_options == other.flag_options
and self.astro_params == other.astro_params
and self.global_quantities.keys() == other.global_quantities.keys()
and self.lightcones.keys() == other.lightcones.keys()
)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/outputs.py
|
outputs.py
|
"""Simple plotting functions for 21cmFAST objects."""
from __future__ import annotations
import matplotlib.pyplot as plt
import numpy as np
from astropy import units as un
from astropy.cosmology import z_at_value
from matplotlib import colors
from matplotlib.ticker import AutoLocator
from typing import Optional, Union
from . import outputs
from .outputs import Coeval, LightCone
eor_colour = colors.LinearSegmentedColormap.from_list(
"EoR",
[
(0, "white"),
(0.21, "yellow"),
(0.42, "orange"),
(0.63, "red"),
(0.86, "black"),
(0.9, "blue"),
(1, "cyan"),
],
)
plt.register_cmap(cmap=eor_colour)
def _imshow_slice(
cube,
slice_axis=-1,
slice_index=0,
fig=None,
ax=None,
fig_kw=None,
cbar=True,
cbar_horizontal=False,
rotate=False,
cmap="EoR",
log: [bool] = False,
**imshow_kw,
):
"""
Plot a slice of some kind of cube.
Parameters
----------
cube : nd-array
A 3D array of some quantity.
slice_axis : int, optional
The axis over which to take a slice, in order to plot.
slice_index :
The index of the slice.
fig : Figure object
An optional matplotlib figure object on which to plot
ax : Axis object
The matplotlib axis object on which to plot (created by default).
fig_kw :
Optional arguments passed to the figure construction.
cbar : bool
Whether to plot the colorbar
cbar_horizontal : bool
Whether the colorbar should be horizontal underneath the plot.
rotate : bool
Whether to rotate the plot vertically.
imshow_kw :
Optional keywords to pass to :func:`maplotlib.imshow`.
Returns
-------
fig, ax :
The figure and axis objects from matplotlib.
"""
# If no axis is passed, create a new one
# This allows the user to add this plot into an existing grid, or alter it afterwards.
if fig_kw is None:
fig_kw = {}
if ax is None and fig is None:
fig, ax = plt.subplots(1, 1, **fig_kw)
elif ax is None:
ax = plt.gca()
elif fig is None:
fig = plt.gcf()
plt.sca(ax)
if slice_index >= cube.shape[slice_axis]:
raise IndexError(
"slice_index is too large for that axis (slice_index=%s >= %s"
% (slice_index, cube.shape[slice_axis])
)
slc = np.take(cube, slice_index, axis=slice_axis)
if not rotate:
slc = slc.T
if cmap == "EoR":
imshow_kw["vmin"] = -150
imshow_kw["vmax"] = 30
norm_kw = {k: imshow_kw.pop(k) for k in ["vmin", "vmax"] if k in imshow_kw}
norm = imshow_kw.get(
"norm", colors.LogNorm(**norm_kw) if log else colors.Normalize(**norm_kw)
)
plt.imshow(slc, origin="lower", cmap=cmap, norm=norm, **imshow_kw)
if cbar:
cb = plt.colorbar(
orientation="horizontal" if cbar_horizontal else "vertical", aspect=40
)
cb.outline.set_edgecolor(None)
return fig, ax
def coeval_sliceplot(
struct: outputs._OutputStruct | Coeval,
kind: str | None = None,
cbar_label: str | None = None,
**kwargs,
):
"""
Show a slice of a given coeval box.
Parameters
----------
struct : :class:`~outputs._OutputStruct` or :class:`~wrapper.Coeval` instance
The output of a function such as `ionize_box` (a class containing several quantities), or
`run_coeval`.
kind : str
The quantity within the structure to be shown. A full list of available options
can be obtained by running ``Coeval.get_fields()``.
cbar_label : str, optional
A label for the colorbar. Some values of `kind` will have automatically chosen
labels, but these can be turned off by setting ``cbar_label=''``.
Returns
-------
fig, ax :
figure and axis objects from matplotlib
Other Parameters
----------------
All other parameters are passed directly to :func:`_imshow_slice`. These include `slice_axis`
and `slice_index`,
which choose the actual slice to plot, optional `fig` and `ax` keywords which enable
over-plotting previous figures,
and the `imshow_kw` argument, which allows arbitrary styling of the plot.
"""
if kind is None:
if isinstance(struct, outputs._OutputStruct):
kind = struct.fieldnames[0]
elif isinstance(struct, Coeval):
kind = "brightness_temp"
try:
cube = getattr(struct, kind)
except AttributeError:
raise AttributeError(
f"The given OutputStruct does not have the quantity {kind}"
)
if kind != "brightness_temp" and "cmap" not in kwargs:
kwargs["cmap"] = "viridis"
fig, ax = _imshow_slice(cube, extent=(0, struct.user_params.BOX_LEN) * 2, **kwargs)
slice_axis = kwargs.get("slice_axis", -1)
# Determine which axes are being plotted.
if slice_axis in (2, -1):
xax = "x"
yax = "y"
elif slice_axis == 1:
xax = "x"
yax = "z"
elif slice_axis == 0:
xax = "y"
yax = "z"
else:
raise ValueError("slice_axis should be between -1 and 2")
# Now put on the decorations.
ax.set_xlabel(f"{xax}-axis [Mpc]")
ax.set_ylabel(f"{yax}-axis [Mpc]")
cbar = fig._gci().colorbar
if cbar is not None:
if cbar_label is None:
if kind == "brightness_temp":
cbar_label = r"Brightness Temperature, $\delta T_B$ [mK]"
elif kind == "xH_box":
cbar_label = r"Neutral fraction"
cbar.ax.set_ylabel(cbar_label)
return fig, ax
def lightcone_sliceplot(
lightcone: LightCone,
kind: str = "brightness_temp",
lightcone2: LightCone = None,
vertical: bool = False,
xlabel: str | None = None,
ylabel: str | None = None,
cbar_label: str | None = None,
zticks: str = "redshift",
fig: plt.Figure | None = None,
ax: plt.Axes | None = None,
**kwargs,
):
"""Create a 2D plot of a slice through a lightcone.
Parameters
----------
lightcone : :class:`~py21cmfast.wrapper.Lightcone`
The lightcone object to plot
kind : str, optional
The attribute of the lightcone to plot. Must be an array.
lightcone2 : str, optional
If provided, plot the _difference_ of the selected attribute between the two
lightcones.
vertical : bool, optional
Whether to plot the redshift in the vertical direction.
cbar_label : str, optional
A label for the colorbar. Some quantities have automatically chosen labels, but
these can be removed by setting `cbar_label=''`.
zticks : str, optional
Defines the co-ordinates of the ticks along the redshift axis.
Can be "redshift" (default), "frequency", "distance" (which starts at zero
for the lowest redshift) or the name of any function in an astropy cosmology
that is purely a function of redshift.
kwargs :
Passed through to ``imshow()``.
Returns
-------
fig :
The matplotlib Figure object
ax :
The matplotlib Axis object onto which the plot was drawn.
"""
slice_axis = kwargs.pop("slice_axis", 0)
if slice_axis <= -2 or slice_axis >= 3:
raise ValueError(f"slice_axis should be between -1 and 2 (got {slice_axis})")
z_axis = ("y" if vertical else "x") if slice_axis in (0, 1) else None
# Dictionary mapping axis to dimension in lightcone
axis_dct = {
"x": 2 if z_axis == "x" else [1, 0, 0][slice_axis],
"y": 2 if z_axis == "y" else [1, 0, 1][slice_axis],
}
if fig is None and ax is None:
fig, ax = plt.subplots(
1,
1,
figsize=(
lightcone.shape[axis_dct["x"]] * 0.015 + 0.5,
lightcone.shape[axis_dct["y"]] * 0.015
+ (2.5 if kwargs.get("cbar", True) else 0.05),
),
)
elif fig is None:
fig = ax._gci().figure
elif ax is None:
ax = fig.get_axes()
# Get x,y labels if they're not the redshift axis.
if xlabel is None:
xlabel = (
None if axis_dct["x"] == 2 else "{}-axis [Mpc]".format("xy"[axis_dct["x"]])
)
if ylabel is None:
ylabel = (
None if axis_dct["y"] == 2 else "{}-axis [Mpc]".format("xy"[axis_dct["y"]])
)
extent = (
0,
lightcone.lightcone_dimensions[axis_dct["x"]],
0,
lightcone.lightcone_dimensions[axis_dct["y"]],
)
if lightcone2 is None:
fig, ax = _imshow_slice(
getattr(lightcone, kind),
extent=extent,
slice_axis=slice_axis,
rotate=not vertical,
cbar_horizontal=not vertical,
cmap=kwargs.get("cmap", "EoR" if kind == "brightness_temp" else "viridis"),
fig=fig,
ax=ax,
**kwargs,
)
else:
d = getattr(lightcone, kind) - getattr(lightcone2, kind)
fig, ax = _imshow_slice(
d,
extent=extent,
slice_axis=slice_axis,
rotate=not vertical,
cbar_horizontal=not vertical,
cmap=kwargs.pop("cmap", "bwr"),
vmin=-np.abs(d.max()),
vmax=np.abs(d.max()),
fig=fig,
ax=ax,
**kwargs,
)
if z_axis:
zlabel = _set_zaxis_ticks(ax, lightcone, zticks, z_axis)
if ylabel != "":
ax.set_ylabel(ylabel or zlabel)
if xlabel != "":
ax.set_xlabel(xlabel or zlabel)
cbar = fig._gci().colorbar
if cbar_label is None:
if kind == "brightness_temp":
cbar_label = r"Brightness Temperature, $\delta T_B$ [mK]"
elif kind == "xH":
cbar_label = r"Neutral fraction"
if vertical:
cbar.ax.set_ylabel(cbar_label)
else:
cbar.ax.set_xlabel(cbar_label)
return fig, ax
def _set_zaxis_ticks(ax, lightcone, zticks, z_axis):
if zticks != "distance":
loc = AutoLocator()
# Get redshift ticks.
lc_z = lightcone.lightcone_redshifts
if zticks == "redshift":
coords = lc_z
elif zticks == "frequency":
coords = 1420 / (1 + lc_z) * un.MHz
else:
try:
coords = getattr(lightcone.cosmo_params.cosmo, zticks)(lc_z)
except AttributeError:
raise AttributeError(f"zticks '{zticks}' is not a cosmology function.")
zlabel = " ".join(z.capitalize() for z in zticks.split("_"))
units = getattr(coords, "unit", None)
if units:
zlabel += f" [{str(coords.unit)}]"
coords = coords.value
ticks = loc.tick_values(coords.min(), coords.max())
if ticks.min() < coords.min() / 1.00001:
ticks = ticks[1:]
if ticks.max() > coords.max() * 1.00001:
ticks = ticks[:-1]
if coords[1] < coords[0]:
ticks = ticks[::-1]
if zticks == "redshift":
z_ticks = ticks
elif zticks == "frequency":
z_ticks = 1420 / ticks - 1
else:
z_ticks = [
z_at_value(getattr(lightcone.cosmo_params.cosmo, zticks), z * units)
for z in ticks
]
d_ticks = (
lightcone.cosmo_params.cosmo.comoving_distance(z_ticks).value
- lightcone.lightcone_distances[0]
)
getattr(ax, f"set_{z_axis}ticks")(d_ticks)
getattr(ax, f"set_{z_axis}ticklabels")(ticks)
else:
zlabel = "Line-of-Sight Distance [Mpc]"
return zlabel
def plot_global_history(
lightcone: LightCone,
kind: str | None = None,
ylabel: str | None = None,
ylog: bool = False,
ax: plt.Axes | None = None,
):
"""
Plot the global history of a given quantity from a lightcone.
Parameters
----------
lightcone : :class:`~LightCone` instance
The lightcone containing the quantity to plot.
kind : str, optional
The quantity to plot. Must be in the `global_quantities` dict in the lightcone.
By default, will choose the first entry in the dict.
ylabel : str, optional
A y-label for the plot. If None, will use ``kind``.
ax : Axes, optional
The matplotlib Axes object on which to plot. Otherwise, created.
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=(7, 4))
else:
fig = ax._gci().figure
if kind is None:
kind = list(lightcone.global_quantities.keys())[0]
assert (
kind in lightcone.global_quantities
or hasattr(lightcone, "global_" + kind)
or (kind.startswith("global_") and hasattr(lightcone, kind))
)
if kind in lightcone.global_quantities:
value = lightcone.global_quantities[kind]
elif kind.startswith("global)"):
value = getattr(lightcone, kind)
else:
value = getattr(lightcone, "global_" + kind)
ax.plot(lightcone.node_redshifts, value)
ax.set_xlabel("Redshift")
if ylabel is None:
ylabel = kind
if ylabel:
ax.set_ylabel(ylabel)
if ylog:
ax.set_yscale("log")
return fig, ax
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/plotting.py
|
plotting.py
|
"""
Input parameter classes.
There are four input parameter/option classes, not all of which are required for any
given function. They are :class:`UserParams`, :class:`CosmoParams`, :class:`AstroParams`
and :class:`FlagOptions`. Each of them defines a number of variables, and all of these
have default values, to minimize the burden on the user. These defaults are accessed via
the ``_defaults_`` class attribute of each class. The available parameters for each are
listed in the documentation for each class below.
Along with these, the module exposes ``global_params``, a singleton object of type
:class:`GlobalParams`, which is a simple class providing read/write access to a number of parameters
used throughout the computation which are very rarely varied.
"""
from __future__ import annotations
import contextlib
import logging
import warnings
from astropy.cosmology import Planck15
from os import path
from pathlib import Path
from ._cfg import config
from ._data import DATA_PATH
from ._utils import StructInstanceWrapper, StructWithDefaults
from .c_21cmfast import ffi, lib
logger = logging.getLogger("21cmFAST")
# Cosmology is from https://arxiv.org/pdf/1807.06209.pdf
# Table 2, last column. [TT,TE,EE+lowE+lensing+BAO]
Planck18 = Planck15.clone(
Om0=(0.02242 + 0.11933) / 0.6766**2,
Ob0=0.02242 / 0.6766**2,
H0=67.66,
)
class GlobalParams(StructInstanceWrapper):
"""
Global parameters for 21cmFAST.
This is a thin wrapper over an allocated C struct, containing parameter values
which are used throughout various computations within 21cmFAST. It is a singleton;
that is, a single python (and C) object exists, and no others should be created.
This object is not "passed around", rather its values are accessed throughout the
code.
Parameters in this struct are considered to be options that should usually not have
to be modified, and if so, typically once in any given script or session.
Values can be set in the normal way, eg.:
>>> global_params.ALPHA_UVB = 5.5
The class also provides a context manager for setting parameters for a well-defined
portion of the code. For example, if you would like to set ``Z_HEAT_MAX`` for a given
run:
>>> with global_params.use(Z_HEAT_MAX=25):
>>> p21c.run_lightcone(...) # uses Z_HEAT_MAX=25 for the entire run.
>>> print(global_params.Z_HEAT_MAX)
35.0
Attributes
----------
ALPHA_UVB : float
Power law index of the UVB during the EoR. This is only used if `INHOMO_RECO` is
True (in :class:`FlagOptions`), in order to compute the local mean free path
inside the cosmic HII regions.
EVOLVE_DENSITY_LINEARLY : bool
Whether to evolve the density field with linear theory (instead of 1LPT or Zel'Dovich).
If choosing this option, make sure that your cell size is
in the linear regime at the redshift of interest. Otherwise, make sure you resolve
small enough scales, roughly we find BOX_LEN/DIM should be < 1Mpc
SMOOTH_EVOLVED_DENSITY_FIELD : bool
If True, the zeldovich-approximation density field is additionally smoothed
(aside from the implicit boxcar smoothing performed when re-binning the ICs from
DIM to HII_DIM) with a Gaussian filter of width ``R_smooth_density*BOX_LEN/HII_DIM``.
The implicit boxcar smoothing in ``perturb_field()`` bins the density field on
scale DIM/HII_DIM, similar to what Lagrangian codes do when constructing Eulerian
grids. In other words, the density field is quantized into ``(DIM/HII_DIM)^3`` values.
If your usage requires smooth density fields, it is recommended to set this to True.
This also decreases the shot noise present in all grid based codes, though it
overcompensates by an effective loss in resolution. **Added in 1.1.0**.
R_smooth_density : float
Determines the smoothing length to use if `SMOOTH_EVOLVED_DENSITY_FIELD` is True.
HII_ROUND_ERR : float
Rounding error on the ionization fraction. If the mean xHI is greater than
``1 - HII_ROUND_ERR``, then finding HII bubbles is skipped, and a homogeneous
xHI field of ones is returned. Added in v1.1.0.
FIND_BUBBLE_ALGORITHM : int, {1,2}
Choose which algorithm used to find HII bubbles. Options are: (1) Mesinger & Furlanetto 2007
method of overlapping spheres: paint an ionized sphere with radius R, centered on pixel
where R is filter radius. This method, while somewhat more accurate, is slower than (2),
especially in mostly ionized universes, so only use for lower resolution boxes
(HII_DIM<~400). (2) Center pixel only method (Zahn et al. 2007). This is faster.
N_POISSON : int
If not using the halo field to generate HII regions, we provide the option of
including Poisson scatter in the number of sources obtained through the conditional
collapse fraction (which only gives the *mean* collapse fraction on a particular
scale. If the predicted mean collapse fraction is less than `N_POISSON * M_MIN`,
then Poisson scatter is added to mimic discrete halos on the subgrid scale (see
Zahn+2010).Use a negative number to turn it off.
.. note:: If you are interested in snapshots of the same realization at several
redshifts,it is recommended to turn off this feature, as halos can
stochastically "pop in and out of" existence from one redshift to the next.
R_OVERLAP_FACTOR : float
When using USE_HALO_FIELD, it is used as a factor the halo's radius, R, so that the
effective radius is R_eff = R_OVERLAP_FACTOR * R. Halos whose centers are less than
R_eff away from another halo are not allowed. R_OVERLAP_FACTOR = 1 is fully disjoint
R_OVERLAP_FACTOR = 0 means that centers are allowed to lay on the edges of
neighboring halos.
DELTA_CRIT_MODE : int
The delta_crit to be used for determining whether a halo exists in a cell
0: delta_crit is constant (i.e. 1.686)
1: delta_crit is the sheth tormen ellipsoidal collapse correction to delta_crit
HALO_FILTER : int
Filter for the density field used to generate the halo field with EPS
0: real space top hat filter
1: sharp k-space filter
2: gaussian filter
OPTIMIZE : bool
Finding halos can be made more efficient if the filter size is sufficiently large that
we can switch to the collapse fraction at a later stage.
OPTIMIZE_MIN_MASS : float
Minimum mass on which the optimization for the halo finder will be used.
T_USE_VELOCITIES : bool
Whether to use velocity corrections in 21-cm fields
.. note:: The approximation used to include peculiar velocity effects works
only in the linear regime, so be careful using this (see Mesinger+2010)
MAX_DVDR : float
Maximum velocity gradient along the line of sight in units of the hubble parameter at z.
This is only used in computing the 21cm fields.
.. note:: Setting this too high can add spurious 21cm power in the early stages,
due to the 1-e^-tau ~ tau approximation (see Mesinger's 21cm intro paper and mao+2011).
However, this is still a good approximation at the <~10% level.
VELOCITY_COMPONENT : int
Component of the velocity to be used in 21-cm temperature maps (1=x, 2=y, 3=z)
DELTA_R_FACTOR : float
Factor by which to scroll through filter radius for halos
DELTA_R_HII_FACTOR : float
Factor by which to scroll through filter radius for bubbles
HII_FILTER : int, {0, 1, 2}
Filter for the Halo or density field used to generate ionization field:
0. real space top hat filter
1. k-space top hat filter
2. gaussian filter
INITIAL_REDSHIFT : float
Used to perturb field
CRIT_DENS_TRANSITION : float
A transition value for the interpolation tables for calculating the number of ionising
photons produced given the input parameters. Log sampling is desired, however the numerical
accuracy near the critical density for collapse (i.e. 1.69) broke down. Therefore, below the
value for `CRIT_DENS_TRANSITION` log sampling of the density values is used, whereas above
this value linear sampling is used.
MIN_DENSITY_LOW_LIMIT : float
Required for using the interpolation tables for the number of ionising photons. This is a
lower limit for the density values that is slightly larger than -1. Defined as a density
contrast.
RecombPhotonCons : int
Whether or not to use the recombination term when calculating the filling factor for
performing the photon non-conservation correction.
PhotonConsStart : float
A starting value for the neutral fraction where the photon non-conservation correction is
performed exactly. Any value larger than this the photon non-conservation correction is not
performed (i.e. the algorithm is perfectly photon conserving).
PhotonConsEnd : float
An end-point for where the photon non-conservation correction is performed exactly. This is
required to remove undesired numerical artifacts in the resultant neutral fraction histories.
PhotonConsAsymptoteTo : float
Beyond `PhotonConsEnd` the photon non-conservation correction is extrapolated to yield
smooth reionisation histories. This sets the lowest neutral fraction value that the photon
non-conservation correction will be applied to.
HEAT_FILTER : int
Filter used for smoothing the linear density field to obtain the collapsed fraction:
0: real space top hat filter
1: sharp k-space filter
2: gaussian filter
CLUMPING_FACTOR : float
Sub grid scale. If you want to run-down from a very high redshift (>50), you should
set this to one.
Z_HEAT_MAX : float
Maximum redshift used in the Tk and x_e evolution equations.
Temperature and x_e are assumed to be homogeneous at higher redshifts.
Lower values will increase performance.
R_XLy_MAX : float
Maximum radius of influence for computing X-ray and Lya pumping in cMpc. This
should be larger than the mean free path of the relevant photons.
NUM_FILTER_STEPS_FOR_Ts : int
Number of spherical annuli used to compute df_coll/dz' in the simulation box.
The spherical annuli are evenly spaced in logR, ranging from the cell size to the box
size. :func:`~wrapper.spin_temp` will create this many boxes of size `HII_DIM`,
so be wary of memory usage if values are high.
ZPRIME_STEP_FACTOR : float
Logarithmic redshift step-size used in the z' integral. Logarithmic dz.
Decreasing (closer to unity) increases total simulation time for lightcones,
and for Ts calculations.
TK_at_Z_HEAT_MAX : float
If positive, then overwrite default boundary conditions for the evolution
equations with this value. The default is to use the value obtained from RECFAST.
See also `XION_at_Z_HEAT_MAX`.
XION_at_Z_HEAT_MAX : float
If positive, then overwrite default boundary conditions for the evolution
equations with this value. The default is to use the value obtained from RECFAST.
See also `TK_at_Z_HEAT_MAX`.
Pop : int
Stellar Population responsible for early heating (2 or 3)
Pop2_ion : float
Number of ionizing photons per baryon for population 2 stellar species.
Pop3_ion : float
Number of ionizing photons per baryon for population 3 stellar species.
NU_X_BAND_MAX : float
This is the upper limit of the soft X-ray band (0.5 - 2 keV) used for normalising
the X-ray SED to observational limits set by the X-ray luminosity. Used for performing
the heating rate integrals.
NU_X_MAX : float
An upper limit (must be set beyond `NU_X_BAND_MAX`) for performing the rate integrals.
Given the X-ray SED is modelled as a power-law, this removes the potential of divergent
behaviour for the heating rates. Chosen purely for numerical convenience though it is
motivated by the fact that observed X-ray SEDs apprear to turn-over around 10-100 keV
(Lehmer et al. 2013, 2015)
NBINS_LF : int
Number of bins for the luminosity function calculation.
P_CUTOFF : bool
Turn on Warm-Dark-matter power suppression.
M_WDM : float
Mass of WDM particle in keV. Ignored if `P_CUTOFF` is False.
g_x : float
Degrees of freedom of WDM particles; 1.5 for fermions.
OMn : float
Relative density of neutrinos in the universe.
OMk : float
Relative density of curvature.
OMr : float
Relative density of radiation.
OMtot : float
Fractional density of the universe with respect to critical density. Set to
unity for a flat universe.
Y_He : float
Helium fraction.
wl : float
Dark energy equation of state parameter (wl = -1 for vacuum )
SHETH_b : float
Sheth-Tormen parameter for ellipsoidal collapse (for HMF).
.. note:: The best fit b and c ST params for these 3D realisations have a redshift,
and a ``DELTA_R_FACTOR`` dependence, as shown
in Mesinger+. For converged mass functions at z~5-10, set `DELTA_R_FACTOR=1.1`
and `SHETH_b=0.15` and `SHETH_c~0.05`.
For most purposes, a larger step size is quite sufficient and provides an
excellent match to N-body and smoother mass functions, though the b and c
parameters should be changed to make up for some "stepping-over" massive
collapsed halos (see Mesinger, Perna, Haiman (2005) and Mesinger et al.,
in preparation).
For example, at z~7-10, one can set `DELTA_R_FACTOR=1.3` and `SHETH_b=0.15`
and `SHETH_c=0.25`, to increase the speed of the halo finder.
SHETH_c : float
Sheth-Tormen parameter for ellipsoidal collapse (for HMF). See notes for `SHETH_b`.
Zreion_HeII : float
Redshift of helium reionization, currently only used for tau_e
FILTER : int, {0, 1}
Filter to use for smoothing.
0. tophat
1. gaussian
external_table_path : str
The system path to find external tables for calculation speedups. DO NOT MODIFY.
R_BUBBLE_MIN : float
Minimum radius of bubbles to be searched in cMpc. One can set this to 0, but should
be careful with shot noise if running on a fine, non-linear density grid. Default
is set to L_FACTOR which is (4PI/3)^(-1/3) = 0.620350491.
M_MIN_INTEGRAL:
Minimum mass when performing integral on halo mass function.
M_MAX_INTEGRAL:
Maximum mass when performing integral on halo mass function.
T_RE:
The peak gas temperatures behind the supersonic ionization fronts during reionization.
VAVG:
Avg value of the DM-b relative velocity [im km/s], ~0.9*SIGMAVCB (=25.86 km/s) normally.
"""
def __init__(self, wrapped, ffi):
super().__init__(wrapped, ffi)
self.external_table_path = ffi.new("char[]", str(DATA_PATH).encode())
self._wisdoms_path = Path(config["direc"]) / "wisdoms"
self.wisdoms_path = ffi.new("char[]", str(self._wisdoms_path).encode())
@property
def external_table_path(self):
"""An ffi char pointer to the path to which external tables are kept."""
return self._external_table_path
@external_table_path.setter
def external_table_path(self, val):
self._external_table_path = val
@property
def wisdoms_path(self):
"""An ffi char pointer to the path to which external tables are kept."""
if not self._wisdoms_path.exists():
self._wisdoms_path.mkdir(parents=True)
return self._wisdom_path
@wisdoms_path.setter
def wisdoms_path(self, val):
self._wisdom_path = val
@contextlib.contextmanager
def use(self, **kwargs):
"""Set given parameters for a certain context.
.. note:: Keywords are *not* case-sensitive.
Examples
--------
>>> from py21cmfast import global_params, run_lightcone
>>> with global_params.use(zprime_step_factor=1.1, Sheth_c=0.06):
>>> run_lightcone(redshift=7)
"""
prev = {}
this_attr_upper = {k.upper(): k for k in self.keys()}
for k, val in kwargs.items():
if k.upper() not in this_attr_upper:
raise ValueError(f"{k} is not a valid parameter of global_params")
key = this_attr_upper[k.upper()]
prev[key] = getattr(self, key)
setattr(self, key, val)
yield
# Restore everything back to the way it was.
for k, v in prev.items():
setattr(self, k, v)
global_params = GlobalParams(lib.global_params, ffi)
class CosmoParams(StructWithDefaults):
"""
Cosmological parameters (with defaults) which translates to a C struct.
To see default values for each parameter, use ``CosmoParams._defaults_``.
All parameters passed in the constructor are also saved as instance attributes which should
be considered read-only. This is true of all input-parameter classes.
Default parameters are based on Plank18, https://arxiv.org/pdf/1807.06209.pdf,
Table 2, last column. [TT,TE,EE+lowE+lensing+BAO]
Parameters
----------
SIGMA_8 : float, optional
RMS mass variance (power spectrum normalisation).
hlittle : float, optional
The hubble parameter, H_0/100.
OMm : float, optional
Omega matter.
OMb : float, optional
Omega baryon, the baryon component.
POWER_INDEX : float, optional
Spectral index of the power spectrum.
"""
_ffi = ffi
_defaults_ = {
"SIGMA_8": 0.8102,
"hlittle": Planck18.h,
"OMm": Planck18.Om0,
"OMb": Planck18.Ob0,
"POWER_INDEX": 0.9665,
}
@property
def OMl(self):
"""Omega lambda, dark energy density."""
return 1 - self.OMm
@property
def cosmo(self):
"""Return an astropy cosmology object for this cosmology."""
return Planck15.clone(H0=self.hlittle * 100, Om0=self.OMm, Ob0=self.OMb)
class UserParams(StructWithDefaults):
"""
Structure containing user parameters (with defaults).
To see default values for each parameter, use ``UserParams._defaults_``.
All parameters passed in the constructor are also saved as instance attributes which should
be considered read-only. This is true of all input-parameter classes.
Parameters
----------
HII_DIM : int, optional
Number of cells for the low-res box. Default 200.
DIM : int,optional
Number of cells for the high-res box (sampling ICs) along a principal axis. To avoid
sampling issues, DIM should be at least 3 or 4 times HII_DIM, and an integer multiple.
By default, it is set to 3*HII_DIM.
NON_CUBIC_FACTOR : float, optional
Factor which allows the creation of non-cubic boxes. It will shorten/lengthen the line
of sight dimension of all boxes. NON_CUBIC_FACTOR * DIM/HII_DIM must result in an integer
BOX_LEN : float, optional
Length of the box, in Mpc. Default 300 Mpc.
HMF: int or str, optional
Determines which halo mass function to be used for the normalisation of the
collapsed fraction (default Sheth-Tormen). If string should be one of the
following codes:
0: PS (Press-Schechter)
1: ST (Sheth-Tormen)
2: Watson (Watson FOF)
3: Watson-z (Watson FOF-z)
USE_RELATIVE_VELOCITIES: int, optional
Flag to decide whether to use relative velocities.
If True, POWER_SPECTRUM is automatically set to 5. Default False.
POWER_SPECTRUM: int or str, optional
Determines which power spectrum to use, default EH (unless `USE_RELATIVE_VELOCITIES`
is True). If string, use the following codes:
0: EH
1: BBKS
2: EFSTATHIOU
3: PEEBLES
4: WHITE
5: CLASS (single cosmology)
N_THREADS : int, optional
Sets the number of processors (threads) to be used for performing 21cmFAST.
Default 1.
PERTURB_ON_HIGH_RES : bool, optional
Whether to perform the Zel'Dovich or 2LPT perturbation on the low or high
resolution grid.
NO_RNG : bool, optional
Ability to turn off random number generation for initial conditions. Can be
useful for debugging and adding in new features
USE_FFTW_WISDOM : bool, optional
Whether or not to use stored FFTW_WISDOMs for improving performance of FFTs
USE_INTERPOLATION_TABLES: bool, optional
If True, calculates and evaluates quantites using interpolation tables, which
is considerably faster than when performing integrals explicitly.
FAST_FCOLL_TABLES: bool, optional
Whether to use fast Fcoll tables, as described in Appendix of Muñoz+21 (2110.13919). Significant speedup for minihaloes.
USE_2LPT: bool, optional
Whether to use second-order Lagrangian perturbation theory (2LPT).
Set this to True if the density field or the halo positions are extrapolated to
low redshifts. The current implementation is very naive and adds a factor ~6 to
the memory requirements. Reference: Scoccimarro R., 1998, MNRAS, 299, 1097-1118
Appendix D.
MINIMIZE_MEMORY: bool, optional
If set, the code will run in a mode that minimizes memory usage, at the expense
of some CPU/disk-IO. Good for large boxes / small computers.
"""
_ffi = ffi
_defaults_ = {
"BOX_LEN": 300.0,
"DIM": None,
"HII_DIM": 200,
"NON_CUBIC_FACTOR": 1.0,
"USE_FFTW_WISDOM": False,
"HMF": 1,
"USE_RELATIVE_VELOCITIES": False,
"POWER_SPECTRUM": 0,
"N_THREADS": 1,
"PERTURB_ON_HIGH_RES": False,
"NO_RNG": False,
"USE_INTERPOLATION_TABLES": None,
"FAST_FCOLL_TABLES": False,
"USE_2LPT": True,
"MINIMIZE_MEMORY": False,
}
_hmf_models = ["PS", "ST", "WATSON", "WATSON-Z"]
_power_models = ["EH", "BBKS", "EFSTATHIOU", "PEEBLES", "WHITE", "CLASS"]
@property
def USE_INTERPOLATION_TABLES(self):
"""Whether to use interpolation tables for integrals, speeding things up."""
if self._USE_INTERPOLATION_TABLES is None:
warnings.warn(
"The USE_INTERPOLATION_TABLES setting has changed in v3.1.2 to be "
"default True. You can likely ignore this warning, but if you relied on"
"having USE_INTERPOLATION_TABLES=False by *default*, please set it "
"explicitly. To silence this warning, set it explicitly to True. This"
"warning will be removed in v4."
)
self._USE_INTERPOLATION_TABLES = True
return self._USE_INTERPOLATION_TABLES
@property
def DIM(self):
"""Number of cells for the high-res box (sampling ICs) along a principal axis."""
return self._DIM or 3 * self.HII_DIM
@property
def NON_CUBIC_FACTOR(self):
"""Factor to shorten/lengthen the line-of-sight dimension (non-cubic boxes)."""
dcf = self.DIM * self._NON_CUBIC_FACTOR
hdcf = self.HII_DIM * self._NON_CUBIC_FACTOR
if dcf % int(dcf) or hdcf % int(hdcf):
raise ValueError(
"NON_CUBIC_FACTOR * DIM and NON_CUBIC_FACTOR * HII_DIM must be integers"
)
else:
return self._NON_CUBIC_FACTOR
@property
def tot_fft_num_pixels(self):
"""Total number of pixels in the high-res box."""
return self.NON_CUBIC_FACTOR * self.DIM**3
@property
def HII_tot_num_pixels(self):
"""Total number of pixels in the low-res box."""
return self.NON_CUBIC_FACTOR * self.HII_DIM**3
@property
def POWER_SPECTRUM(self):
"""
The power spectrum generator to use, as an integer.
See :func:`power_spectrum_model` for a string representation.
"""
if self.USE_RELATIVE_VELOCITIES:
if self._POWER_SPECTRUM != 5 or (
isinstance(self._POWER_SPECTRUM, str)
and self._POWER_SPECTRUM.upper() != "CLASS"
):
logger.warning(
"Automatically setting POWER_SPECTRUM to 5 (CLASS) as you are using "
"relative velocities"
)
return 5
else:
if isinstance(self._POWER_SPECTRUM, str):
val = self._power_models.index(self._POWER_SPECTRUM.upper())
else:
val = self._POWER_SPECTRUM
if not 0 <= val < len(self._power_models):
raise ValueError(
f"Power spectrum must be between 0 and {len(self._power_models) - 1}"
)
return val
@property
def HMF(self):
"""The HMF to use (an int, mapping to a given form).
See hmf_model for a string representation.
"""
if isinstance(self._HMF, str):
val = self._hmf_models.index(self._HMF.upper())
else:
val = self._HMF
try:
val = int(val)
except (ValueError, TypeError) as e:
raise ValueError("Invalid value for HMF") from e
if not 0 <= val < len(self._hmf_models):
raise ValueError(
f"HMF must be an int between 0 and {len(self._hmf_models) - 1}"
)
return val
@property
def hmf_model(self):
"""String representation of the HMF model used."""
return self._hmf_models[self.HMF]
@property
def power_spectrum_model(self):
"""String representation of the power spectrum model used."""
return self._power_models[self.POWER_SPECTRUM]
@property
def FAST_FCOLL_TABLES(self):
"""Check that USE_INTERPOLATION_TABLES is True."""
if not self._FAST_FCOLL_TABLES or self.USE_INTERPOLATION_TABLES:
return self._FAST_FCOLL_TABLES
logger.warning(
"You cannot turn on FAST_FCOLL_TABLES without USE_INTERPOLATION_TABLES."
)
return False
class FlagOptions(StructWithDefaults):
"""
Flag-style options for the ionization routines.
To see default values for each parameter, use ``FlagOptions._defaults_``.
All parameters passed in the constructor are also saved as instance attributes
which should be considered read-only. This is true of all input-parameter classes.
Note that all flags are set to False by default, giving the simplest "vanilla"
version of 21cmFAST.
Parameters
----------
USE_HALO_FIELD : bool, optional
Set to True if intending to find and use the halo field. If False, uses
the mean collapse fraction (which is considerably faster).
USE_MINI_HALOS : bool, optional
Set to True if using mini-halos parameterization.
If True, USE_MASS_DEPENDENT_ZETA and INHOMO_RECO must be True.
USE_CMB_HEATING : bool, optional
Whether to include CMB Heating. (cf Eq.4 of Meiksin 2021, arxiv.org/abs/2105.14516)
USE_LYA_HEATING : bool, optional
Whether to use Lyman-alpha heating. (cf Sec. 3 of Reis+2021, doi.org/10.1093/mnras/stab2089)
USE_MASS_DEPENDENT_ZETA : bool, optional
Set to True if using new parameterization. Setting to True will automatically
set `M_MIN_in_Mass` to True.
SUBCELL_RSDS : bool, optional
Add sub-cell redshift-space-distortions (cf Sec 2.2 of Greig+2018).
Will only be effective if `USE_TS_FLUCT` is True.
INHOMO_RECO : bool, optional
Whether to perform inhomogeneous recombinations. Increases the computation
time.
USE_TS_FLUCT : bool, optional
Whether to perform IGM spin temperature fluctuations (i.e. X-ray heating).
Dramatically increases the computation time.
M_MIN_in_Mass : bool, optional
Whether the minimum halo mass (for ionization) is defined by
mass or virial temperature. Automatically True if `USE_MASS_DEPENDENT_ZETA`
is True.
PHOTON_CONS : bool, optional
Whether to perform a small correction to account for the inherent
photon non-conservation.
FIX_VCB_AVG: bool, optional
Determines whether to use a fixed vcb=VAVG (*regardless* of USE_RELATIVE_VELOCITIES). It includes the average effect of velocities but not its fluctuations. See Muñoz+21 (2110.13919).
USE_VELS_AUX: bool, optional
Auxiliary variable (not input) to check if minihaloes are being used without relative velocities and complain
"""
_ffi = ffi
_defaults_ = {
"USE_HALO_FIELD": False,
"USE_MINI_HALOS": False,
"USE_CMB_HEATING": True,
"USE_LYA_HEATING": True,
"USE_MASS_DEPENDENT_ZETA": False,
"SUBCELL_RSD": False,
"INHOMO_RECO": False,
"USE_TS_FLUCT": False,
"M_MIN_in_Mass": False,
"PHOTON_CONS": False,
"FIX_VCB_AVG": False,
}
@property
def USE_HALO_FIELD(self):
"""Automatically setting USE_MASS_DEPENDENT_ZETA to False if USE_MINI_HALOS."""
if not self.USE_MINI_HALOS or not self._USE_HALO_FIELD:
return self._USE_HALO_FIELD
logger.warning(
"You have set USE_MINI_HALOS to True but USE_HALO_FIELD is also True! "
"Automatically setting USE_HALO_FIELD to False."
)
return False
@property
def M_MIN_in_Mass(self):
"""Whether minimum halo mass is defined in mass or virial temperature."""
return True if self.USE_MASS_DEPENDENT_ZETA else self._M_MIN_in_Mass
@property
def USE_MASS_DEPENDENT_ZETA(self):
"""Automatically setting USE_MASS_DEPENDENT_ZETA to True if USE_MINI_HALOS."""
if not self.USE_MINI_HALOS or self._USE_MASS_DEPENDENT_ZETA:
return self._USE_MASS_DEPENDENT_ZETA
logger.warning(
"You have set USE_MINI_HALOS to True but USE_MASS_DEPENDENT_ZETA to False! "
"Automatically setting USE_MASS_DEPENDENT_ZETA to True."
)
return True
@property
def INHOMO_RECO(self):
"""Automatically setting INHOMO_RECO to True if USE_MINI_HALOS."""
if not self.USE_MINI_HALOS or self._INHOMO_RECO:
return self._INHOMO_RECO
logger.warning(
"You have set USE_MINI_HALOS to True but INHOMO_RECO to False! "
"Automatically setting INHOMO_RECO to True."
)
return True
@property
def USE_TS_FLUCT(self):
"""Automatically setting USE_TS_FLUCT to True if USE_MINI_HALOS."""
if not self.USE_MINI_HALOS or self._USE_TS_FLUCT:
return self._USE_TS_FLUCT
logger.warning(
"You have set USE_MINI_HALOS to True but USE_TS_FLUCT to False! "
"Automatically setting USE_TS_FLUCT to True."
)
return True
@property
def PHOTON_CONS(self):
"""Automatically setting PHOTON_CONS to False if USE_MINI_HALOS."""
if not self.USE_MINI_HALOS or not self._PHOTON_CONS:
return self._PHOTON_CONS
logger.warning(
"USE_MINI_HALOS is not compatible with PHOTON_CONS! "
"Automatically setting PHOTON_CONS to False."
)
return False
class AstroParams(StructWithDefaults):
"""
Astrophysical parameters.
To see default values for each parameter, use ``AstroParams._defaults_``.
All parameters passed in the constructor are also saved as instance attributes which should
be considered read-only. This is true of all input-parameter classes.
Parameters
----------
INHOMO_RECO : bool, optional
Whether inhomogeneous recombinations are being calculated. This is not a part of the
astro parameters structure, but is required by this class to set some default behaviour.
HII_EFF_FACTOR : float, optional
The ionizing efficiency of high-z galaxies (zeta, from Eq. 2 of Greig+2015).
Higher values tend to speed up reionization.
F_STAR10 : float, optional
The fraction of galactic gas in stars for 10^10 solar mass haloes.
Only used in the "new" parameterization,
i.e. when `USE_MASS_DEPENDENT_ZETA` is set to True (in :class:`FlagOptions`).
If so, this is used along with `F_ESC10` to determine `HII_EFF_FACTOR` (which
is then unused). See Eq. 11 of Greig+2018 and Sec 2.1 of Park+2018.
Given in log10 units.
F_STAR7_MINI : float, optional
The fraction of galactic gas in stars for 10^7 solar mass minihaloes.
Only used in the "minihalo" parameterization,
i.e. when `USE_MINI_HALOS` is set to True (in :class:`FlagOptions`).
If so, this is used along with `F_ESC7_MINI` to determine `HII_EFF_FACTOR_MINI` (which
is then unused). See Eq. 8 of Qin+2020.
Given in log10 units.
ALPHA_STAR : float, optional
Power-law index of fraction of galactic gas in stars as a function of halo mass.
See Sec 2.1 of Park+2018.
ALPHA_STAR_MINI : float, optional
Power-law index of fraction of galactic gas in stars as a function of halo mass, for MCGs.
See Sec 2 of Muñoz+21 (2110.13919).
F_ESC10 : float, optional
The "escape fraction", i.e. the fraction of ionizing photons escaping into the
IGM, for 10^10 solar mass haloes. Only used in the "new" parameterization,
i.e. when `USE_MASS_DEPENDENT_ZETA` is set to True (in :class:`FlagOptions`).
If so, this is used along with `F_STAR10` to determine `HII_EFF_FACTOR` (which
is then unused). See Eq. 11 of Greig+2018 and Sec 2.1 of Park+2018.
F_ESC7_MINI: float, optional
The "escape fraction for minihalos", i.e. the fraction of ionizing photons escaping
into the IGM, for 10^7 solar mass minihaloes. Only used in the "minihalo" parameterization,
i.e. when `USE_MINI_HALOS` is set to True (in :class:`FlagOptions`).
If so, this is used along with `F_ESC7_MINI` to determine `HII_EFF_FACTOR_MINI` (which
is then unused). See Eq. 17 of Qin+2020.
Given in log10 units.
ALPHA_ESC : float, optional
Power-law index of escape fraction as a function of halo mass. See Sec 2.1 of
Park+2018.
M_TURN : float, optional
Turnover mass (in log10 solar mass units) for quenching of star formation in
halos, due to SNe or photo-heating feedback, or inefficient gas accretion. Only
used if `USE_MASS_DEPENDENT_ZETA` is set to True in :class:`FlagOptions`.
See Sec 2.1 of Park+2018.
R_BUBBLE_MAX : float, optional
Mean free path in Mpc of ionizing photons within ionizing regions (Sec. 2.1.2 of
Greig+2015). Default is 50 if `INHOMO_RECO` is True, or 15.0 if not.
ION_Tvir_MIN : float, optional
Minimum virial temperature of star-forming haloes (Sec 2.1.3 of Greig+2015).
Given in log10 units.
L_X : float, optional
The specific X-ray luminosity per unit star formation escaping host galaxies.
Cf. Eq. 6 of Greig+2018. Given in log10 units.
L_X_MINI: float, optional
The specific X-ray luminosity per unit star formation escaping host galaxies for
minihalos. Cf. Eq. 23 of Qin+2020. Given in log10 units.
NU_X_THRESH : float, optional
X-ray energy threshold for self-absorption by host galaxies (in eV). Also called
E_0 (cf. Sec 4.1 of Greig+2018). Typical range is (100, 1500).
X_RAY_SPEC_INDEX : float, optional
X-ray spectral energy index (cf. Sec 4.1 of Greig+2018). Typical range is
(-1, 3).
X_RAY_Tvir_MIN : float, optional
Minimum halo virial temperature in which X-rays are produced. Given in log10
units. Default is `ION_Tvir_MIN`.
F_H2_SHIELD: float, optional
Self-shielding factor of molecular hydrogen when experiencing LW suppression.
Cf. Eq. 12 of Qin+2020. Consistently included in A_LW fit from sims.
If used we recommend going back to Macachek+01 A_LW=22.86.
t_STAR : float, optional
Fractional characteristic time-scale (fraction of hubble time) defining the
star-formation rate of galaxies. Only used if `USE_MASS_DEPENDENT_ZETA` is set
to True in :class:`FlagOptions`. See Sec 2.1, Eq. 3 of Park+2018.
N_RSD_STEPS : int, optional
Number of steps used in redshift-space-distortion algorithm. NOT A PHYSICAL
PARAMETER.
A_LW, BETA_LW: float, optional
Impact of the LW feedback on Mturn for minihaloes. Default is 22.8685 and 0.47 following Machacek+01, respectively. Latest simulations suggest 2.0 and 0.6. See Sec 2 of Muñoz+21 (2110.13919).
A_VCB, BETA_VCB: float, optional
Impact of the DM-baryon relative velocities on Mturn for minihaloes. Default is 1.0 and 1.8, and agrees between different sims. See Sec 2 of Muñoz+21 (2110.13919).
"""
_ffi = ffi
_defaults_ = {
"HII_EFF_FACTOR": 30.0,
"F_STAR10": -1.3,
"F_STAR7_MINI": -2.0,
"ALPHA_STAR": 0.5,
"ALPHA_STAR_MINI": 0.5,
"F_ESC10": -1.0,
"F_ESC7_MINI": -2.0,
"ALPHA_ESC": -0.5,
"M_TURN": 8.7,
"R_BUBBLE_MAX": None,
"ION_Tvir_MIN": 4.69897,
"L_X": 40.0,
"L_X_MINI": 40.0,
"NU_X_THRESH": 500.0,
"X_RAY_SPEC_INDEX": 1.0,
"X_RAY_Tvir_MIN": None,
"F_H2_SHIELD": 0.0,
"t_STAR": 0.5,
"N_RSD_STEPS": 20,
"A_LW": 2.00,
"BETA_LW": 0.6,
"A_VCB": 1.0,
"BETA_VCB": 1.8,
}
def __init__(
self, *args, INHOMO_RECO=FlagOptions._defaults_["INHOMO_RECO"], **kwargs
):
# TODO: should try to get inhomo_reco out of here... just needed for default of
# R_BUBBLE_MAX.
self.INHOMO_RECO = INHOMO_RECO
super().__init__(*args, **kwargs)
def convert(self, key, val):
"""Convert a given attribute before saving it the instance."""
if key in [
"F_STAR10",
"F_ESC10",
"F_STAR7_MINI",
"F_ESC7_MINI",
"M_TURN",
"ION_Tvir_MIN",
"L_X",
"L_X_MINI",
"X_RAY_Tvir_MIN",
]:
return 10**val
else:
return val
@property
def R_BUBBLE_MAX(self):
"""Maximum radius of bubbles to be searched. Set dynamically."""
if not self._R_BUBBLE_MAX:
return 50.0 if self.INHOMO_RECO else 15.0
if self.INHOMO_RECO and self._R_BUBBLE_MAX != 50:
logger.warning(
"You are setting R_BUBBLE_MAX != 50 when INHOMO_RECO=True. "
"This is non-standard (but allowed), and usually occurs upon manual "
"update of INHOMO_RECO"
)
return self._R_BUBBLE_MAX
@property
def X_RAY_Tvir_MIN(self):
"""Minimum virial temperature of X-ray emitting sources (unlogged and set dynamically)."""
return self._X_RAY_Tvir_MIN or self.ION_Tvir_MIN
@property
def NU_X_THRESH(self):
"""Check if the choice of NU_X_THRESH is sensible."""
if self._NU_X_THRESH < 100.0:
raise ValueError(
"Chosen NU_X_THRESH is < 100 eV. NU_X_THRESH must be above 100 eV as it describes X-ray photons"
)
elif self._NU_X_THRESH >= global_params.NU_X_BAND_MAX:
raise ValueError(
"""
Chosen NU_X_THRESH > {}, which is the upper limit of the adopted X-ray band
(fiducially the soft band 0.5 - 2.0 keV). If you know what you are doing with this
choice, please modify the global parameter: NU_X_BAND_MAX""".format(
global_params.NU_X_BAND_MAX
)
)
else:
if global_params.NU_X_BAND_MAX > global_params.NU_X_MAX:
raise ValueError(
"""
Chosen NU_X_BAND_MAX > {}, which is the upper limit of X-ray integrals (fiducially 10 keV)
If you know what you are doing, please modify the global parameter:
NU_X_MAX""".format(
global_params.NU_X_MAX
)
)
else:
return self._NU_X_THRESH
@property
def t_STAR(self):
"""Check if the choice of NU_X_THRESH is sensible."""
if self._t_STAR <= 0.0 or self._t_STAR > 1.0:
raise ValueError("t_STAR must be above zero and less than or equal to one")
else:
return self._t_STAR
class InputCrossValidationError(ValueError):
"""Error when two parameters from different structs aren't consistent."""
pass
def validate_all_inputs(
user_params: UserParams,
cosmo_params: CosmoParams,
astro_params: AstroParams | None = None,
flag_options: FlagOptions | None = None,
):
"""Cross-validate input parameters from different structs.
The input params may be modified in-place in this function, but if so, a warning
should be emitted.
"""
if astro_params is not None:
if astro_params.R_BUBBLE_MAX > user_params.BOX_LEN:
astro_params.update(R_BUBBLE_MAX=user_params.BOX_LEN)
warnings.warn(
f"Setting R_BUBBLE_MAX to BOX_LEN (={user_params.BOX_LEN} as it doesn't make sense for it to be larger."
)
if (
global_params.HII_FILTER == 1
and astro_params.R_BUBBLE_MAX > user_params.BOX_LEN / 3
):
msg = (
"Your R_BUBBLE_MAX is > BOX_LEN/3 "
f"({astro_params.R_BUBBLE_MAX} > {user_params.BOX_LEN/3})."
)
if config["ignore_R_BUBBLE_MAX_error"]:
warnings.warn(msg)
else:
raise ValueError(msg)
if flag_options is not None and (
flag_options.USE_MINI_HALOS
and not user_params.USE_RELATIVE_VELOCITIES
and not flag_options.FIX_VCB_AVG
):
logger.warning(
"USE_MINI_HALOS needs USE_RELATIVE_VELOCITIES to get the right evolution!"
)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/inputs.py
|
inputs.py
|
"""Modified YAML that can load/dump `astropy` quantities.
A modification of the basic YAML and astropy.io.misc.yaml to be able to load/dump
objects with astropy quantities in them.
"""
import yaml
from astropy.io.misc import yaml as ayaml
class _NewDumper(yaml.Dumper, ayaml.AstropyDumper):
pass
class _NewLoader(yaml.Loader, ayaml.AstropyLoader):
pass
for k, v in yaml.Dumper.yaml_representers.items():
_NewDumper.add_representer(k, v)
for k, v in yaml.Dumper.yaml_multi_representers.items():
_NewDumper.add_multi_representer(k, v)
for k, v in ayaml.AstropyDumper.yaml_representers.items():
_NewDumper.add_representer(k, v)
for k, v in ayaml.AstropyDumper.yaml_multi_representers.items():
_NewDumper.add_multi_representer(k, v)
for k, v in yaml.Loader.yaml_constructors.items():
_NewLoader.add_constructor(k, v)
for k, v in ayaml.AstropyLoader.yaml_constructors.items():
_NewLoader.add_constructor(k, v)
for k, v in yaml.Loader.yaml_multi_constructors.items():
_NewLoader.add_multi_constructor(k, v)
for k, v in ayaml.AstropyLoader.yaml_multi_constructors.items():
_NewLoader.add_multi_constructor(k, v)
def load(stream):
"""Load an object from a YAML stream."""
return yaml.load(stream, Loader=_NewLoader)
def dump(data, stream=None, **kwargs):
"""Dump an object into a YAML stream."""
kwargs["Dumper"] = _NewDumper
return yaml.dump(data, stream=stream, **kwargs)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/yaml.py
|
yaml.py
|
"""The py21cmfast package."""
try:
from importlib.metadata import PackageNotFoundError, version
except ImportError:
from importlib_metadata import PackageNotFoundError, version
try:
from ._version import version as __version__
except ModuleNotFoundError: # pragma: no cover
try:
__version__ = version("21cmFAST")
except PackageNotFoundError:
# package is not installed
__version__ = "unknown"
# This just ensures that the default directory for boxes is created.
from os import mkdir as _mkdir
from os import path
from . import cache_tools, inputs, outputs, plotting, wrapper
from ._cfg import config
from ._logging import configure_logging
from .cache_tools import query_cache
from .outputs import (
Coeval,
InitialConditions,
IonizedBox,
LightCone,
PerturbedField,
TsBox,
)
from .wrapper import (
AstroParams,
BrightnessTemp,
CosmoParams,
FlagOptions,
HaloField,
PerturbHaloField,
UserParams,
brightness_temperature,
compute_luminosity_function,
compute_tau,
construct_fftw_wisdoms,
determine_halo_list,
get_all_fieldnames,
global_params,
initial_conditions,
ionize_box,
perturb_field,
perturb_halo_list,
run_coeval,
run_lightcone,
spin_temperature,
)
configure_logging()
try:
_mkdir(path.expanduser(config["direc"]))
except FileExistsError:
pass
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/__init__.py
|
__init__.py
|
"""Open and read the configuration file."""
from __future__ import annotations
import contextlib
import copy
import warnings
from pathlib import Path
from . import yaml
class ConfigurationError(Exception):
"""An error with the config file."""
pass
class Config(dict):
"""Simple over-ride of dict that adds a context manager."""
_defaults = {
"direc": "~/21cmFAST-cache",
"regenerate": False,
"write": True,
"cache_param_sigfigs": 6,
"cache_redshift_sigfigs": 4,
"ignore_R_BUBBLE_MAX_error": False,
}
_aliases = {"direc": ("boxdir",)}
def __init__(self, *args, write=True, file_name=None, **kwargs):
super().__init__(*args, **kwargs)
self.file_name = file_name
# Ensure the keys that got read in are the right keys for the current version
do_write = False
for k, v in self._defaults.items():
if k not in self:
if k not in self._aliases:
warnings.warn("Your configuration file is out of date. Updating...")
do_write = True
self[k] = v
else:
for alias in self._aliases[k]:
if alias in self:
do_write = True
warnings.warn(
f"Your configuration file has old key '{alias}' which "
f"has been re-named '{k}'. Updating..."
)
self[k] = self[alias]
del self[alias]
break
else:
warnings.warn(
"Your configuration file is out of date. Updating..."
)
do_write = True
self[k] = v
for k, v in self.items():
if k not in self._defaults:
raise ConfigurationError(
f"The configuration file has key '{k}' which is not known to 21cmFAST."
)
self["direc"] = Path(self["direc"]).expanduser().absolute()
if do_write and write and self.file_name:
self.write()
@contextlib.contextmanager
def use(self, **kwargs):
"""Context manager for using certain configuration options for a set time."""
backup = self.copy()
for k, v in kwargs.items():
self[k] = Path(v).expanduser().absolute() if k == "direc" else v
yield self
for k in kwargs:
self[k] = backup[k]
def write(self, fname: str | Path | None = None):
"""Write current configuration to file to make it permanent."""
fname = Path(fname or self.file_name)
if fname:
if not fname.parent.exists():
fname.parent.mkdir(parents=True)
with open(fname, "w") as fl:
yaml.dump(self._as_dict(), fl)
def _as_dict(self):
"""The plain dict defining the instance."""
return {k: str(Path) if isinstance(v, Path) else v for k, v in self.items()}
@classmethod
def load(cls, file_name: str | Path):
"""Create a Config object from a config file."""
file_name = Path(file_name).expanduser().absolute()
if file_name.exists():
with open(file_name) as fl:
cfg = yaml.load(fl)
return cls(cfg, file_name=file_name)
else:
return cls(write=False)
config = Config.load(Path("~/.21cmfast/config.yml"))
# Keep an original copy around
default_config = copy.deepcopy(config)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/_cfg.py
|
_cfg.py
|
"""Utilities that help with wrapping various C structures."""
import glob
import h5py
import logging
import numpy as np
import warnings
from abc import ABCMeta, abstractmethod
from bidict import bidict
from cffi import FFI
from enum import IntEnum
from hashlib import md5
from os import makedirs, path
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
from . import __version__
from ._cfg import config
from .c_21cmfast import lib
_ffi = FFI()
logger = logging.getLogger(__name__)
class ArrayStateError(ValueError):
"""Errors arising from incorrectly modifying array state."""
pass
class ArrayState:
"""Define the memory state of a struct array."""
def __init__(
self, initialized=False, c_memory=False, computed_in_mem=False, on_disk=False
):
self._initialized = initialized
self._c_memory = c_memory
self._computed_in_mem = computed_in_mem
self._on_disk = on_disk
@property
def initialized(self):
"""Whether the array is initialized (i.e. allocated memory)."""
return self._initialized
@initialized.setter
def initialized(self, val):
if not val:
# if its not initialized, can't be computed in memory
self.computed_in_mem = False
self._initialized = bool(val)
@property
def c_memory(self):
"""Whether the array's memory (if any) is controlled by C."""
return self._c_memory
@c_memory.setter
def c_memory(self, val):
self._c_memory = bool(val)
@property
def computed_in_mem(self):
"""Whether the array is computed and stored in memory."""
return self._computed_in_mem
@computed_in_mem.setter
def computed_in_mem(self, val):
if val:
# any time we pull something into memory, it must be initialized.
self.initialized = True
self._computed_in_mem = bool(val)
@property
def on_disk(self):
"""Whether the array is computed and store on disk."""
return self._on_disk
@on_disk.setter
def on_disk(self, val):
self._on_disk = bool(val)
@property
def computed(self):
"""Whether the array is computed anywhere."""
return self.computed_in_mem or self.on_disk
@property
def c_has_active_memory(self):
"""Whether C currently has initialized memory for this array."""
return self.c_memory and self.initialized
class ParameterError(RuntimeError):
"""An exception representing a bad choice of parameters."""
default_message = "21cmFAST does not support this combination of parameters."
def __init__(self, msg=None):
super().__init__(msg or self.default_message)
class FatalCError(Exception):
"""An exception representing something going wrong in C."""
default_message = "21cmFAST is exiting."
def __init__(self, msg=None):
super().__init__(msg or self.default_message)
class FileIOError(FatalCError):
"""An exception when an error occurs with file I/O."""
default_message = "Expected file could not be found! (check the LOG for more info)"
class GSLError(ParameterError):
"""An exception when a GSL routine encounters an error."""
default_message = "A GSL routine has errored! (check the LOG for more info)"
class ArgumentValueError(FatalCError):
"""An exception when a function takes an unexpected input."""
default_message = "An incorrect argument has been defined or passed! (check the LOG for more info)"
class PhotonConsError(ParameterError):
"""An exception when the photon non-conservation correction routine errors."""
default_message = "An error has occured with the Photon non-conservation correction! (check the LOG for more info)"
class TableGenerationError(ParameterError):
"""An exception when an issue arises populating one of the interpolation tables."""
default_message = """An error has occured when generating an interpolation table!
This has likely occured due to the choice of input AstroParams (check the LOG for more info)"""
class TableEvaluationError(ParameterError):
"""An exception when an issue arises populating one of the interpolation tables."""
default_message = """An error has occured when evaluating an interpolation table!
This can sometimes occur due to small boxes (either small DIM/HII_DIM or BOX_LEN) (check the LOG for more info)"""
class InfinityorNaNError(ParameterError):
"""An exception when an infinity or NaN is encountered in a calculated quantity."""
default_message = """Something has returned an infinity or a NaN! This could be due to an issue with an
input parameter choice (check the LOG for more info)"""
class MassDepZetaError(ParameterError):
"""An exception when determining the bisection for stellar mass/escape fraction."""
default_message = """There is an issue with the choice of parameters under MASS_DEPENDENT_ZETA. Could be an issue with
any of the chosen F_STAR10, ALPHA_STAR, F_ESC10 or ALPHA_ESC."""
class MemoryAllocError(FatalCError):
"""An exception when unable to allocated memory."""
default_message = """An error has occured while attempting to allocate memory! (check the LOG for more info)"""
SUCCESS = 0
IOERROR = 1
GSLERROR = 2
VALUEERROR = 3
PHOTONCONSERROR = 4
TABLEGENERATIONERROR = 5
TABLEEVALUATIONERROR = 6
INFINITYORNANERROR = 7
MASSDEPZETAERROR = 8
MEMORYALLOCERROR = 9
def _process_exitcode(exitcode, fnc, args):
"""Determine what happens for different values of the (integer) exit code from a C function."""
if exitcode != SUCCESS:
logger.error(f"In function: {fnc.__name__}. Arguments: {args}")
if exitcode:
try:
raise {
IOERROR: FileIOError,
GSLERROR: GSLError,
VALUEERROR: ArgumentValueError,
PHOTONCONSERROR: PhotonConsError,
TABLEGENERATIONERROR: TableGenerationError,
TABLEEVALUATIONERROR: TableEvaluationError,
INFINITYORNANERROR: InfinityorNaNError,
MASSDEPZETAERROR: MassDepZetaError,
MEMORYALLOCERROR: MemoryAllocError,
}[exitcode]
except KeyError: # pragma: no cover
raise FatalCError(
"Unknown error in C. Please report this error!"
) # Unknown C code
ctype2dtype = {}
# Integer types
for prefix in ("int", "uint"):
for log_bytes in range(4):
ctype = "%s%d_t" % (prefix, 8 * (2**log_bytes))
dtype = "%s%d" % (prefix[0], 2**log_bytes)
ctype2dtype[ctype] = np.dtype(dtype)
# Floating point types
ctype2dtype["float"] = np.dtype("f4")
ctype2dtype["double"] = np.dtype("f8")
ctype2dtype["int"] = np.dtype("i4")
def asarray(ptr, shape):
"""Get the canonical C type of the elements of ptr as a string."""
ctype = _ffi.getctype(_ffi.typeof(ptr).item).split("*")[0].strip()
if ctype not in ctype2dtype:
raise RuntimeError(
f"Cannot create an array for element type: {ctype}. Can do {list(ctype2dtype.values())}."
)
array = np.frombuffer(
_ffi.buffer(ptr, _ffi.sizeof(ctype) * np.prod(shape)), ctype2dtype[ctype]
)
array.shape = shape
return array
class StructWrapper:
"""
A base-class python wrapper for C structures (not instances of them).
Provides simple methods for creating new instances and accessing field names and values.
To implement wrappers of specific structures, make a subclass with the same name as the
appropriate C struct (which must be defined in the C code that has been compiled to the ``ffi``
object), *or* use an arbitrary name, but set the ``_name`` attribute to the C struct name.
"""
_name = None
_ffi = None
def __init__(self):
# Set the name of this struct in the C code
self._name = self._get_name()
@classmethod
def _get_name(cls):
return cls._name or cls.__name__
@property
def _cstruct(self):
"""
The actual structure which needs to be passed around to C functions.
.. note:: This is best accessed by calling the instance (see __call__).
The reason it is defined as this (manual) cached property is so that it can be created
dynamically, but not lost. It must not be lost, or else C functions which use it will lose
access to its memory. But it also must be created dynamically so that it can be recreated
after pickling (pickle can't handle CData).
"""
try:
return self.__cstruct
except AttributeError:
self.__cstruct = self._new()
return self.__cstruct
def _new(self):
"""Return a new empty C structure corresponding to this class."""
return self._ffi.new("struct " + self._name + "*")
@classmethod
def get_fields(cls, cstruct=None) -> Dict[str, Any]:
"""Obtain the C-side fields of this struct."""
if cstruct is None:
cstruct = cls._ffi.new("struct " + cls._get_name() + "*")
return dict(cls._ffi.typeof(cstruct[0]).fields)
@classmethod
def get_fieldnames(cls, cstruct=None) -> List[str]:
"""Obtain the C-side field names of this struct."""
fields = cls.get_fields(cstruct)
return [f for f, t in fields]
@classmethod
def get_pointer_fields(cls, cstruct=None) -> List[str]:
"""Obtain all pointer fields of the struct (typically simulation boxes)."""
return [f for f, t in cls.get_fields(cstruct) if t.type.kind == "pointer"]
@property
def fields(self) -> Dict[str, Any]:
"""List of fields of the underlying C struct (a list of tuples of "name, type")."""
return self.get_fields(self._cstruct)
@property
def fieldnames(self) -> List[str]:
"""List names of fields of the underlying C struct."""
return [f for f, t in self.fields.items()]
@property
def pointer_fields(self) -> List[str]:
"""List of names of fields which have pointer type in the C struct."""
return [f for f, t in self.fields.items() if t.type.kind == "pointer"]
@property
def primitive_fields(self) -> List[str]:
"""List of names of fields which have primitive type in the C struct."""
return [f for f, t in self.fields.items() if t.type.kind == "primitive"]
def __getstate__(self):
"""Return the current state of the class without pointers."""
return {
k: v
for k, v in self.__dict__.items()
if k not in ["_strings", "_StructWrapper__cstruct"]
}
def refresh_cstruct(self):
"""Delete the underlying C object, forcing it to be rebuilt."""
try:
del self.__cstruct
except AttributeError:
pass
def __call__(self):
"""Return an instance of the C struct."""
pass
class StructWithDefaults(StructWrapper):
"""
A convenient interface to create a C structure with defaults specified.
It is provided for the purpose of *creating* C structures in Python to be passed to C functions,
where sensible defaults are available. Structures which are created within C and passed back do
not need to be wrapped.
This provides a *fully initialised* structure, and will fail if not all fields are specified
with defaults.
.. note:: The actual C structure is gotten by calling an instance. This is auto-generated when
called, based on the parameters in the class.
.. warning:: This class will *not* deal well with parameters of the struct which are pointers.
All parameters should be primitive types, except for strings, which are dealt with
specially.
Parameters
----------
ffi : cffi object
The ffi object from any cffi-wrapped library.
"""
_defaults_ = {}
def __init__(self, *args, **kwargs):
super().__init__()
if args:
if len(args) > 1:
raise TypeError(
"%s takes up to one position argument, %s were given"
% (self.__class__.__name__, len(args))
)
elif args[0] is None:
pass
elif isinstance(args[0], self.__class__):
kwargs.update(args[0].self)
elif isinstance(args[0], dict):
kwargs.update(args[0])
else:
raise TypeError(
f"optional positional argument for {self.__class__.__name__} must be"
f" None, dict, or an instance of itself"
)
for k, v in self._defaults_.items():
# Prefer arguments given to the constructor.
_v = kwargs.pop(k, None)
if _v is not None:
v = _v
try:
setattr(self, k, v)
except AttributeError:
# The attribute has been defined as a property, save it as a hidden variable
setattr(self, "_" + k, v)
if kwargs:
warnings.warn(
"The following parameters to {thisclass} are not supported: {lst}".format(
thisclass=self.__class__.__name__, lst=list(kwargs.keys())
)
)
def convert(self, key, val):
"""Make any conversions of values before saving to the instance."""
return val
def update(self, **kwargs):
"""
Update the parameters of an existing class structure.
This should always be used instead of attempting to *assign* values to instance attributes.
It consistently re-generates the underlying C memory space and sets some book-keeping
variables.
Parameters
----------
kwargs:
Any argument that may be passed to the class constructor.
"""
# Start a fresh cstruct.
if kwargs:
self.refresh_cstruct()
for k in self._defaults_:
# Prefer arguments given to the constructor.
if k in kwargs:
v = kwargs.pop(k)
try:
setattr(self, k, v)
except AttributeError:
# The attribute has been defined as a property, save it as a hidden variable
setattr(self, "_" + k, v)
# Also ensure that parameters that are part of the class, but not the defaults, are set
# this will fail if these parameters cannot be set for some reason, hence doing it
# last.
for k in list(kwargs.keys()):
if hasattr(self, k):
setattr(self, k, kwargs.pop(k))
if kwargs:
warnings.warn(
"The following arguments to be updated are not compatible with this class: %s"
% kwargs
)
def clone(self, **kwargs):
"""Make a fresh copy of the instance with arbitrary parameters updated."""
new = self.__class__(self.self)
new.update(**kwargs)
return new
def __call__(self):
"""Return a filled C Structure corresponding to this instance."""
for key, val in self.pystruct.items():
# Find the value of this key in the current class
if isinstance(val, str):
# If it is a string, need to convert it to C string ourselves.
val = self.ffi.new("char[]", getattr(self, key).encode())
try:
setattr(self._cstruct, key, val)
except TypeError:
logger.info(f"For key {key}, value {val}:")
raise
return self._cstruct
@property
def pystruct(self):
"""A pure-python dictionary representation of the corresponding C structure."""
return {fld: self.convert(fld, getattr(self, fld)) for fld in self.fieldnames}
@property
def defining_dict(self):
"""
Pure python dictionary representation of this class, as it would appear in C.
.. note:: This is not the same as :attr:`pystruct`, as it omits all variables that don't
need to be passed to the constructor, but appear in the C struct (some can be
calculated dynamically based on the inputs). It is also not the same as
:attr:`self`, as it includes the 'converted' values for each variable, which are
those actually passed to the C code.
"""
return {k: self.convert(k, getattr(self, k)) for k in self._defaults_}
@property
def self(self):
"""
Dictionary which if passed to its own constructor will yield an identical copy.
.. note:: This differs from :attr:`pystruct` and :attr:`defining_dict` in that it uses the
hidden variable value, if it exists, instead of the exposed one. This prevents
from, for example, passing a value which is 10**10**val (and recurring!).
"""
# Try to first use the hidden variable before using the non-hidden variety.
dct = {}
for k in self._defaults_:
if hasattr(self, "_" + k):
dct[k] = getattr(self, "_" + k)
else:
dct[k] = getattr(self, k)
return dct
def __repr__(self):
"""Full unique representation of the instance."""
return (
self.__class__.__name__
+ "("
+ ", ".join(
sorted(
k
+ ":"
+ (
float_to_string_precision(v, config["cache_redshift_sigfigs"])
if isinstance(v, (float, np.float32))
else str(v)
)
for k, v in self.defining_dict.items()
)
)
+ ")"
)
def __eq__(self, other):
"""Check whether this instance is equal to another object (by checking the __repr__)."""
return self.__repr__() == repr(other)
def __hash__(self):
"""Generate a unique hsh for the instance."""
return hash(self.__repr__())
def __str__(self):
"""Human-readable string representation of the object."""
biggest_k = max(len(k) for k in self.defining_dict)
params = "\n ".join(
sorted(f"{k:<{biggest_k}}: {v}" for k, v in self.defining_dict.items())
)
return f"""{self.__class__.__name__}:
{params}
"""
def snake_to_camel(word: str, publicize: bool = True):
"""Convert snake case to camel case."""
if publicize:
word = word.lstrip("_")
return "".join(x.capitalize() or "_" for x in word.split("_"))
def camel_to_snake(word: str, depublicize: bool = False):
"""Convert came case to snake case."""
word = "".join("_" + i.lower() if i.isupper() else i for i in word)
if not depublicize:
word = word.lstrip("_")
return word
def float_to_string_precision(x, n):
"""Prints out a standard float number at a given number of significant digits.
Code here: https://stackoverflow.com/a/48812729
"""
return f'{float(f"{x:.{int(n)}g}"):g}'
def get_all_subclasses(cls):
"""Get a list of all subclasses of a given class, recursively."""
all_subclasses = []
for subclass in cls.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(get_all_subclasses(subclass))
return all_subclasses
class OutputStruct(StructWrapper, metaclass=ABCMeta):
"""Base class for any class that wraps a C struct meant to be output from a C function."""
_meta = True
_fields_ = []
_global_params = None
_inputs = ("user_params", "cosmo_params", "_random_seed")
_filter_params = ["external_table_path", "wisdoms_path"]
_c_based_pointers = ()
_c_compute_function = None
_TYPEMAP = bidict({"float32": "float *", "float64": "double *", "int32": "int *"})
def __init__(self, *, random_seed=None, dummy=False, initial=False, **kwargs):
"""
Base type for output structures from C functions.
Parameters
----------
random_seed
Seed associated with the output.
dummy
Specify this as a dummy struct, in which no arrays are to be
initialized or computed.
initial
Specify this as an initial struct, where arrays are to be
initialized, but do not need to be computed to pass into another
struct's compute().
"""
super().__init__()
self.version = ".".join(__version__.split(".")[:2])
self.patch_version = ".".join(__version__.split(".")[2:])
self._paths = []
self._random_seed = random_seed
for k in self._inputs:
if k not in self.__dict__:
try:
setattr(self, k, kwargs.pop(k))
except KeyError:
raise KeyError(
f"{self.__class__.__name__} requires the keyword argument {k}"
)
if kwargs:
warnings.warn(
f"{self.__class__.__name__} received the following unexpected "
f"arguments: {list(kwargs.keys())}"
)
self.dummy = dummy
self.initial = initial
self._array_structure = self._get_box_structures()
self._array_state = {k: ArrayState() for k in self._array_structure}
self._array_state.update({k: ArrayState() for k in self._c_based_pointers})
for k in self._array_structure:
if k not in self.pointer_fields:
raise TypeError(f"Key {k} in {self} not a defined pointer field in C.")
@property
def path(self) -> Tuple[None, Path]:
"""The path to an on-disk version of this object."""
if not self._paths:
return None
for pth in self._paths:
if pth.exists():
return pth
logger.info("All paths that defined {self} have been deleted on disk.")
return None
@abstractmethod
def _get_box_structures(self) -> Dict[str, Union[Dict, Tuple[int]]]:
"""Return a dictionary of names mapping to shapes for each array in the struct.
The reason this is a function, not a simple attribute, is that we may need to
decide on what arrays need to be initialized based on the inputs (eg. if USE_2LPT
is True or False).
Each actual OutputStruct subclass needs to implement this. Note that the arrays
are not actually initialized here -- that's done automatically by :func:`_init_arrays`
using this information. This function means that the names of the actually required
arrays can be accessed without doing any actual initialization.
Note also that this only contains arrays allocated *by Python* not C. Arrays
allocated by C are specified in :func:`_c_shape`.
"""
pass
def _c_shape(self, cstruct) -> Dict[str, Tuple[int]]:
"""Return a dictionary of field: shape for arrays allocated within C."""
return {}
@classmethod
def _implementations(cls):
all_classes = get_all_subclasses(cls)
return [c for c in all_classes if not c._meta]
def _init_arrays(self):
for k, state in self._array_state.items():
if k == "lowres_density":
logger.debug("THINKING ABOUT INITING LOWRES_DENSITY")
logger.debug(state.initialized, state.computed_in_mem, state.on_disk)
# Don't initialize C-based pointers or already-inited stuff, or stuff
# that's computed on disk (if it's on disk, accessing the array should
# just give the computed version, which is what we would want, not a
# zero-inited array).
if k in self._c_based_pointers or state.initialized or state.on_disk:
continue
params = self._array_structure[k]
tp = self._TYPEMAP.inverse[self.fields[k].type.cname]
if isinstance(params, tuple):
shape = params
fnc = np.zeros
elif isinstance(params, dict):
fnc = params.get("init", np.zeros)
shape = params.get("shape")
else:
raise ValueError("params is not a tuple or dict")
setattr(self, k, fnc(shape, dtype=tp))
# Add it to initialized arrays.
state.initialized = True
@property
def random_seed(self):
"""The random seed for this particular instance."""
if self._random_seed is None:
self._random_seed = int(np.random.randint(1, int(1e12)))
return self._random_seed
def _init_cstruct(self):
# Initialize all uninitialized arrays.
self._init_arrays()
for k, state in self._array_state.items():
# We do *not* set COMPUTED_ON_DISK items to the C-struct here, because we have no
# way of knowing (in this function) what is required to load in, and we don't want
# to unnecessarily load things in. We leave it to the user to ensure that all
# required arrays are loaded into memory before calling this function.
if state.initialized:
setattr(self._cstruct, k, self._ary2buf(getattr(self, k)))
for k in self.primitive_fields:
try:
setattr(self._cstruct, k, getattr(self, k))
except AttributeError:
pass
def _ary2buf(self, ary):
if not isinstance(ary, np.ndarray):
raise ValueError("ary must be a numpy array")
return self._ffi.cast(
OutputStruct._TYPEMAP[ary.dtype.name], self._ffi.from_buffer(ary)
)
def __call__(self):
"""Initialize/allocate a fresh C struct in memory and return it."""
if not self.dummy:
self._init_cstruct()
return self._cstruct
def __expose(self):
"""Expose the non-array primitives of the ctype to the top-level object."""
for k in self.primitive_fields:
setattr(self, k, getattr(self._cstruct, k))
@property
def _fname_skeleton(self):
"""The filename without specifying the random seed."""
return self._name + "_" + self._md5 + "_r{seed}.h5"
def prepare(
self,
flush: Optional[Sequence[str]] = None,
keep: Optional[Sequence[str]] = None,
force: bool = False,
):
"""Prepare the instance for being passed to another function.
This will flush all arrays in "flush" from memory, and ensure all arrays
in "keep" are in memory. At least one of these must be provided. By default,
the complement of the given parameter is all flushed/kept.
Parameters
----------
flush
Arrays to flush out of memory. Note that if no file is associated with this
instance, these arrays will be lost forever.
keep
Arrays to keep or load into memory. Note that if these do not already
exist, they will be loaded from file (if the file exists). Only one of
``flush`` and ``keep`` should be specified.
force
Whether to force flushing arrays even if no disk storage exists.
"""
if flush is None and keep is None:
raise ValueError("Must provide either flush or keep")
if flush is not None and keep is None:
keep = [k for k in self._array_state if k not in flush]
elif keep is not None and flush is None:
flush = [k for k in self._array_state if k not in keep]
flush = flush or []
keep = keep or []
for k in flush:
self._remove_array(k, force)
# Accessing the array loads it into memory.
for k in keep:
getattr(self, k)
def _remove_array(self, k, force=False):
state = self._array_state[k]
if not state.initialized:
warnings.warn(f"Trying to remove array that isn't yet created: {k}")
return
if state.computed_in_mem and not state.on_disk and not force:
raise OSError(
f"Trying to purge array '{k}' from memory that hasn't been stored! Use force=True if you meant to do this."
)
if state.c_has_active_memory:
lib.free(getattr(self._cstruct, k))
delattr(self, k)
state.initialized = False
def __getattr__(self, item):
"""Gets arrays that aren't already in memory."""
# Have to use __dict__ here to test membership, otherwise we get recursion error.
if "_array_state" not in self.__dict__ or item not in self._array_state:
raise self.__getattribute__(item)
if not self._array_state[item].on_disk:
raise OSError(
f"Cannot get {item} as it is not in memory, and this object is not cached to disk."
)
self.read(fname=self.path, keys=[item])
return getattr(self, item)
def purge(self, force=False):
"""Flush all the boxes out of memory.
Parameters
----------
force
Whether to force the purge even if no disk storage exists.
"""
self.prepare(keep=[], force=force)
def load_all(self):
"""Load all possible arrays into memory."""
self.prepare(flush=[])
@property
def filename(self):
"""The base filename of this object."""
if self._random_seed is None:
raise AttributeError("filename not defined until random_seed has been set")
return self._fname_skeleton.format(seed=self.random_seed)
def _get_fname(self, direc=None):
direc = path.abspath(path.expanduser(direc or config["direc"]))
return path.join(direc, self.filename)
def _find_file_without_seed(self, direc):
allfiles = glob.glob(path.join(direc, self._fname_skeleton.format(seed="*")))
if allfiles:
return allfiles[0]
else:
return None
def find_existing(self, direc=None):
"""
Try to find existing boxes which match the parameters of this instance.
Parameters
----------
direc : str, optional
The directory in which to search for the boxes. By default, this is the
centrally-managed directory, given by the ``config.yml`` in ``~/.21cmfast/``.
Returns
-------
str
The filename of an existing set of boxes, or None.
"""
# First, if appropriate, find a file without specifying seed.
# Need to do this first, otherwise the seed will be chosen randomly upon
# choosing a filename!
direc = path.expanduser(direc or config["direc"])
if not self._random_seed:
f = self._find_file_without_seed(direc)
if f and self._check_parameters(f):
return f
else:
f = self._get_fname(direc)
if path.exists(f) and self._check_parameters(f):
return f
return None
def _check_parameters(self, fname):
with h5py.File(fname, "r") as f:
for k in self._inputs + ("_global_params",):
q = getattr(self, k)
# The key name as it should appear in file.
kfile = k.lstrip("_")
# If this particular variable is set to None, this is interpreted
# as meaning that we don't care about matching it to file.
if q is None:
continue
if (
not isinstance(q, StructWithDefaults)
and not isinstance(q, StructInstanceWrapper)
and f.attrs[kfile] != q
):
return False
elif isinstance(q, (StructWithDefaults, StructInstanceWrapper)):
grp = f[kfile]
dct = q.self if isinstance(q, StructWithDefaults) else q
for kk, v in dct.items():
if kk not in self._filter_params:
file_v = grp.attrs[kk]
if file_v == "none":
file_v = None
if file_v != v:
logger.debug("For file %s:" % fname)
logger.debug(
f"\tThough md5 and seed matched, the parameter {kk} did not match,"
f" with values {file_v} and {v} in file and user respectively"
)
return False
return True
def exists(self, direc=None):
"""
Return a bool indicating whether a box matching the parameters of this instance is in cache.
Parameters
----------
direc : str, optional
The directory in which to search for the boxes. By default, this is the
centrally-managed directory, given by the ``config.yml`` in ``~/.21cmfast/``.
"""
return self.find_existing(direc) is not None
def write(
self,
direc=None,
fname: Union[str, Path, None, h5py.File, h5py.Group] = None,
write_inputs=True,
mode="w",
):
"""
Write the struct in standard HDF5 format.
Parameters
----------
direc : str, optional
The directory in which to write the boxes. By default, this is the
centrally-managed directory, given by the ``config.yml`` in ``~/.21cmfast/``.
fname : str, optional
The filename to write to. By default creates a unique filename from the hash.
write_inputs : bool, optional
Whether to write the inputs to the file. Can be useful to set to False if
the input file already exists and has parts already written.
"""
if not all(v.computed for v in self._array_state.values()):
raise OSError(
"Not all boxes have been computed (or maybe some have been purged). Cannot write."
f"Non-computed boxes: {[k for k, v in self._array_state.items() if not v.computed]}"
)
if not self._random_seed:
raise ValueError(
"Attempting to write when no random seed has been set. "
"Struct has been 'computed' inconsistently."
)
if not write_inputs:
mode = "a"
try:
if not isinstance(fname, (h5py.File, h5py.Group)):
direc = path.expanduser(direc or config["direc"])
if not path.exists(direc):
makedirs(direc)
fname = fname or self._get_fname(direc)
if not path.isabs(fname):
fname = path.abspath(path.join(direc, fname))
fl = h5py.File(fname, mode)
else:
fl = fname
try:
# Save input parameters to the file
if write_inputs:
for k in self._inputs + ("_global_params",):
q = getattr(self, k)
kfile = k.lstrip("_")
if isinstance(q, (StructWithDefaults, StructInstanceWrapper)):
grp = fl.create_group(kfile)
dct = q.self if isinstance(q, StructWithDefaults) else q
for kk, v in dct.items():
if kk not in self._filter_params:
try:
grp.attrs[kk] = "none" if v is None else v
except TypeError:
raise TypeError(
f"key {kk} with value {v} is not able to be written to HDF5 attrs!"
)
else:
fl.attrs[kfile] = q
# Write 21cmFAST version to the file
fl.attrs["version"] = __version__
# Save the boxes to the file
boxes = fl.create_group(self._name)
self.write_data_to_hdf5_group(boxes)
finally:
if not isinstance(fname, (h5py.File, h5py.Group)):
fl.close()
self._paths.insert(0, Path(fname))
except OSError as e:
logger.warning(
f"When attempting to write {self.__class__.__name__} to file, write failed with the following error. Continuing without caching."
)
logger.warning(e)
def write_data_to_hdf5_group(self, group: h5py.Group):
"""
Write out this object to a particular HDF5 subgroup.
Parameters
----------
group
The HDF5 group into which to write the object.
"""
# Go through all fields in this struct, and save
for k, state in self._array_state.items():
group.create_dataset(k, data=getattr(self, k))
state.on_disk = True
for k in self.primitive_fields:
group.attrs[k] = getattr(self, k)
def save(self, fname=None, direc=".", h5_group=None):
"""Save the box to disk.
In detail, this just calls write, but changes the default directory to the
local directory. This is more user-friendly, while :meth:`write` is for
automatic use under-the-hood.
Parameters
----------
fname : str, optional
The filename to write. Can be an absolute or relative path. If relative,
by default it is relative to the current directory (otherwise relative
to ``direc``). By default, the filename is auto-generated as unique to
the set of parameters that go into producing the data.
direc : str, optional
The directory into which to write the data. By default the current directory.
Ignored if ``fname`` is an absolute path.
"""
# If fname is absolute path, then get direc from it, otherwise assume current dir.
if path.isabs(fname):
direc = path.dirname(fname)
fname = path.basename(fname)
if h5_group is not None:
if not path.isabs(fname):
fname = path.abspath(path.join(direc, fname))
fl = h5py.File(fname, "a")
try:
grp = fl.create_group(h5_group)
self.write(direc, grp)
finally:
fl.close()
else:
self.write(direc, fname)
def _get_path(
self, direc: Union[str, Path, None] = None, fname: Union[str, Path, None] = None
) -> Path:
if direc is None and fname is None and self.path:
return self.path
if fname is None:
pth = self.find_existing(direc)
if pth is None:
raise OSError("No boxes exist for these parameters.")
else:
direc = Path(direc or config["direc"]).expanduser()
fname = Path(fname)
pth = fname if fname.exists() else direc / fname
return pth
def read(
self,
direc: Union[str, Path, None] = None,
fname: Union[str, Path, None, h5py.File, h5py.Group] = None,
keys: Optional[Sequence[str]] = None,
):
"""
Try find and read existing boxes from cache, which match the parameters of this instance.
Parameters
----------
direc
The directory in which to search for the boxes. By default, this is the
centrally-managed directory, given by the ``config.yml`` in ``~/.21cmfast/``.
fname
The filename to read. By default, use the filename associated with this
object. Can be an open h5py File or Group, which will be directly written to.
keys
The names of boxes to read in (can be a subset). By default, read everything.
"""
if not isinstance(fname, (h5py.File, h5py.Group)):
pth = self._get_path(direc, fname)
fl = h5py.File(pth, "r")
else:
fl = fname
try:
try:
boxes = fl[self._name]
except KeyError:
raise OSError(
f"While trying to read in {self._name}, the file exists, but does not have the "
"correct structure."
)
# Set our arrays.
for k in boxes.keys():
if keys is None or k in keys:
setattr(self, k, boxes[k][...])
self._array_state[k].on_disk = True
self._array_state[k].computed_in_mem = True
setattr(self._cstruct, k, self._ary2buf(getattr(self, k)))
for k in boxes.attrs.keys():
if k == "version":
version = ".".join(boxes.attrs[k].split(".")[:2])
patch = ".".join(boxes.attrs[k].split(".")[2:])
if version != ".".join(__version__.split(".")[:2]):
# Ensure that the major and minor versions are the same.
warnings.warn(
f"The file {pth} is out of date (version = {version}.{patch}). "
f"Consider using another box and removing it!"
)
self.version = version
self.patch_version = patch
setattr(self, k, boxes.attrs[k])
try:
setattr(self._cstruct, k, getattr(self, k))
except AttributeError:
pass
# Need to make sure that the seed is set to the one that's read in.
seed = fl.attrs["random_seed"]
self._random_seed = seed
finally:
self.__expose()
if isinstance(fl, h5py.File):
self._paths.insert(0, Path(fl.filename))
else:
self._paths.insert(0, Path(fl.file.filename))
if not isinstance(fname, (h5py.File, h5py.Group)):
fl.close()
@classmethod
def from_file(
cls, fname, direc=None, load_data=True, h5_group: Union[str, None] = None
):
"""Create an instance from a file on disk.
Parameters
----------
fname : str, optional
Path to the file on disk. May be relative or absolute.
direc : str, optional
The directory from which fname is relative to (if it is relative). By
default, will be the cache directory in config.
load_data : bool, optional
Whether to read in the data when creating the instance. If False, a bare
instance is created with input parameters -- the instance can read data
with the :func:`read` method.
h5_group
The path to the group within the file in which the object is stored.
"""
direc = path.expanduser(direc or config["direc"])
if not path.exists(fname):
fname = path.join(direc, fname)
with h5py.File(fname, "r") as fl:
if h5_group is not None:
self = cls(**cls._read_inputs(fl[h5_group]))
else:
self = cls(**cls._read_inputs(fl))
if load_data:
if h5_group is not None:
with h5py.File(fname, "r") as fl:
self.read(fname=fl[h5_group])
else:
self.read(fname=fname)
return self
@classmethod
def _read_inputs(cls, grp: Union[h5py.File, h5py.Group]):
input_classes = [c.__name__ for c in StructWithDefaults.__subclasses__()]
# Read the input parameter dictionaries from file.
kwargs = {}
for k in cls._inputs:
kfile = k.lstrip("_")
input_class_name = snake_to_camel(kfile)
if input_class_name in input_classes:
input_class = StructWithDefaults.__subclasses__()[
input_classes.index(input_class_name)
]
subgrp = grp[kfile]
kwargs[k] = input_class(
{k: v for k, v in dict(subgrp.attrs).items() if v != "none"}
)
else:
kwargs[kfile] = grp.attrs[kfile]
return kwargs
def __repr__(self):
"""Return a fully unique representation of the instance."""
# This is the class name and all parameters which belong to C-based input structs,
# eg. InitialConditions(HII_DIM:100,SIGMA_8:0.8,...)
# eg. InitialConditions(HII_DIM:100,SIGMA_8:0.8,...)
return f"{self._seedless_repr()}_random_seed={self._random_seed}"
def _seedless_repr(self):
# The same as __repr__ except without the seed.
return (
(
self._name
+ "("
+ "; ".join(
repr(v)
if isinstance(v, StructWithDefaults)
else (
v.filtered_repr(self._filter_params)
if isinstance(v, StructInstanceWrapper)
else k.lstrip("_")
+ ":"
+ (
float_to_string_precision(v, config["cache_param_sigfigs"])
if isinstance(v, (float, np.float32))
else repr(v)
)
)
for k, v in [
(k, getattr(self, k))
for k in self._inputs + ("_global_params",)
if k != "_random_seed"
]
)
)
+ f"; v{self.version}"
+ ")"
)
def __str__(self):
"""Return a human-readable representation of the instance."""
# this is *not* a unique representation, and doesn't include global params.
return (
self._name
+ "("
+ ";\n\t".join(
repr(v)
if isinstance(v, StructWithDefaults)
else k.lstrip("_") + ":" + repr(v)
for k, v in [(k, getattr(self, k)) for k in self._inputs]
)
) + ")"
def __hash__(self):
"""Return a unique hsh for this instance, even global params and random seed."""
return hash(repr(self))
@property
def _md5(self):
"""Return a unique hsh of the object, *not* taking into account the random seed."""
return md5(self._seedless_repr().encode()).hexdigest()
def __eq__(self, other):
"""Check equality with another object via its __repr__."""
return repr(self) == repr(other)
@property
def is_computed(self) -> bool:
"""Whether this instance has been computed at all.
This is true either if the current instance has called :meth:`compute`,
or if it has a current existing :attr:`path` pointing to stored data,
or if such a path exists.
Just because the instance has been computed does *not* mean that all
relevant quantities are available -- some may have been purged from
memory without writing. Use :meth:`has` to check whether certain arrays
are available.
"""
return any(v.computed for v in self._array_state.values())
def ensure_arrays_computed(self, *arrays, load=False) -> bool:
"""Check if the given arrays are computed (not just initialized)."""
if not self.is_computed:
return False
computed = all(self._array_state[k].computed for k in arrays)
if computed and load:
self.prepare(keep=arrays, flush=[])
return computed
def ensure_arrays_inited(self, *arrays, init=False) -> bool:
"""Check if the given arrays are initialized (or computed)."""
inited = all(self._array_state[k].initialized for k in arrays)
if init and not inited:
self._init_arrays()
return True
@abstractmethod
def get_required_input_arrays(self, input_box) -> List[str]:
"""Return all input arrays required to compute this object."""
pass
def ensure_input_computed(self, input_box, load=False) -> bool:
"""Ensure all the inputs have been computed."""
if input_box.dummy:
return True
arrays = self.get_required_input_arrays(input_box)
if input_box.initial:
return input_box.ensure_arrays_inited(*arrays, init=load)
return input_box.ensure_arrays_computed(*arrays, load=load)
def summarize(self, indent=0) -> str:
"""Generate a string summary of the struct."""
indent = indent * " "
out = f"\n{indent}{self.__class__.__name__}\n"
out += "".join(
f"{indent} {fieldname:>15}: {getattr(self, fieldname, 'non-existent')}\n"
for fieldname in self.primitive_fields
)
for fieldname, state in self._array_state.items():
if not state.initialized:
out += f"{indent} {fieldname:>15}: uninitialized\n"
elif not state.computed:
out += f"{indent} {fieldname:>15}: initialized\n"
elif not state.computed_in_mem:
out += f"{indent} {fieldname:>15}: computed on disk\n"
else:
x = getattr(self, fieldname).flatten()
if len(x) > 0:
out += f"{indent} {fieldname:>15}: {x[0]:1.4e}, {x[-1]:1.4e}, {x.min():1.4e}, {x.max():1.4e}, {np.mean(x):1.4e}\n"
else:
out += f"{indent} {fieldname:>15}: size zero\n"
return out
@classmethod
def _log_call_arguments(cls, *args):
logger.debug(f"Calling {cls._c_compute_function.__name__} with following args:")
for arg in args:
if isinstance(arg, OutputStruct):
for line in arg.summarize(indent=1).split("\n"):
logger.debug(line)
elif isinstance(arg, StructWithDefaults):
for line in str(arg).split("\n"):
logger.debug(f" {line}")
else:
logger.debug(f" {arg}")
def _ensure_arguments_exist(self, *args):
for arg in args:
if (
isinstance(arg, OutputStruct)
and not arg.dummy
and not self.ensure_input_computed(arg, load=True)
):
raise ValueError(
f"Trying to use {arg} to compute {self}, but some required arrays "
f"are not computed!"
)
def _compute(
self, *args, hooks: Optional[Dict[Union[str, Callable], Dict[str, Any]]] = None
):
"""Compute the actual function that fills this struct."""
# Write a detailed message about call arguments if debug turned on.
if logger.getEffectiveLevel() <= logging.DEBUG:
self._log_call_arguments(*args)
# Check that all required inputs are really computed, and load them into memory
# if they're not already.
self._ensure_arguments_exist(*args)
# Construct the args. All StructWrapper objects need to actually pass their
# underlying cstruct, rather than themselves. OutputStructs also pass the
# class in that's calling this.
inputs = [arg() if isinstance(arg, StructWrapper) else arg for arg in args]
# Ensure we haven't already tried to compute this instance.
if self.is_computed:
raise ValueError(
f"You are trying to compute {self.__class__.__name__}, but it has already been computed."
)
# Perform the C computation
try:
exitcode = self._c_compute_function(*inputs, self())
except TypeError as e:
logger.error(
f"Arguments to {self._c_compute_function.__name__}: "
f"{[arg() if isinstance(arg, StructWrapper) else arg for arg in args]}"
)
raise e
_process_exitcode(exitcode, self._c_compute_function, args)
# Ensure memory created in C gets mapped to numpy arrays in this struct.
for k, state in self._array_state.items():
if state.initialized:
state.computed_in_mem = True
self.__memory_map()
self.__expose()
# Optionally do stuff with the result (like writing it)
self._call_hooks(hooks)
return self
def _call_hooks(self, hooks):
if hooks is None:
hooks = {"write": {"direc": config["direc"]}}
for hook, params in hooks.items():
if callable(hook):
hook(self, **params)
else:
getattr(self, hook)(**params)
def __memory_map(self):
shapes = self._c_shape(self._cstruct)
for item in self._c_based_pointers:
setattr(self, item, asarray(getattr(self._cstruct, item), shapes[item]))
self._array_state[item].c_memory = True
self._array_state[item].computed_in_mem = True
def __del__(self):
"""Safely delete the object and its C-allocated memory."""
for k in self._c_based_pointers:
if self._array_state[k].c_has_active_memory:
lib.free(getattr(self._cstruct, k))
class StructInstanceWrapper:
"""A wrapper for *instances* of C structs.
This is as opposed to :class:`StructWrapper`, which is for the un-instantiated structs.
Parameters
----------
wrapped :
The reference to the C object to wrap (contained in the ``cffi.lib`` object).
ffi :
The ``cffi.ffi`` object.
"""
def __init__(self, wrapped, ffi):
self._cobj = wrapped
self._ffi = ffi
for nm, tp in self._ffi.typeof(self._cobj).fields:
setattr(self, nm, getattr(self._cobj, nm))
# Get the name of the structure
self._ctype = self._ffi.typeof(self._cobj).cname.split()[-1]
def __setattr__(self, name, value):
"""Set an attribute of the instance, attempting to change it in the C struct as well."""
try:
setattr(self._cobj, name, value)
except AttributeError:
pass
object.__setattr__(self, name, value)
def items(self):
"""Yield (name, value) pairs for each element of the struct."""
for nm, tp in self._ffi.typeof(self._cobj).fields:
yield nm, getattr(self, nm)
def keys(self):
"""Return a list of names of elements in the struct."""
return [nm for nm, tp in self.items()]
def __repr__(self):
"""Return a unique representation of the instance."""
return (
self._ctype
+ "("
+ ";".join(k + "=" + str(v) for k, v in sorted(self.items()))
) + ")"
def filtered_repr(self, filter_params):
"""Get a fully unique representation of the instance that filters out some parameters.
Parameters
----------
filter_params : list of str
The parameter names which should not appear in the representation.
"""
return (
self._ctype
+ "("
+ ";".join(
k + "=" + str(v)
for k, v in sorted(self.items())
if k not in filter_params
)
) + ")"
def _check_compatible_inputs(*datasets, ignore=["redshift"]):
"""Ensure that all defined input parameters for the provided datasets are equal.
Parameters
----------
datasets : list of :class:`~_utils.OutputStruct`
A number of output datasets to cross-check.
ignore : list of str
Attributes to ignore when ensuring that parameter inputs are the same.
Raises
------
ValueError :
If datasets are not compatible.
"""
done = [] # keeps track of inputs we've checked so we don't double check.
for i, d in enumerate(datasets):
# If a dataset is None, just ignore and move on.
if d is None:
continue
# noinspection PyProtectedMember
for inp in d._inputs:
# Skip inputs that we want to ignore
if inp in ignore:
continue
if inp not in done:
for j, d2 in enumerate(datasets[(i + 1) :]):
if d2 is None:
continue
# noinspection PyProtectedMember
if inp in d2._inputs and getattr(d, inp) != getattr(d2, inp):
raise ValueError(
f"""
{d.__class__.__name__} and {d2.__class__.__name__} are incompatible.
{inp}: {getattr(d, inp)}
vs.
{inp}: {getattr(d2, inp)}
"""
)
done += [inp]
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/_utils.py
|
_utils.py
|
"""Module that contains the command line app."""
import builtins
import click
import inspect
import logging
import matplotlib.pyplot as plt
import numpy as np
import warnings
import yaml
from os import path, remove
from pathlib import Path
from . import _cfg, cache_tools, global_params, plotting
from . import wrapper as lib
def _get_config(config=None):
if config is None:
config = path.expanduser(path.join("~", ".21cmfast", "runconfig_example.yml"))
with open(config) as f:
cfg = yaml.load(f, Loader=yaml.FullLoader)
return cfg
def _ctx_to_dct(args):
dct = {}
j = 0
while j < len(args):
arg = args[j]
if "=" in arg:
a = arg.split("=")
dct[a[0].replace("--", "")] = a[-1]
j += 1
else:
dct[arg.replace("--", "")] = args[j + 1]
j += 2
return dct
def _update(obj, ctx):
# Try to use the extra arguments as an override of config.
kk = list(ctx.keys())
for k in kk:
# noinspection PyProtectedMember
if hasattr(obj, k):
try:
val = getattr(obj, "_" + k)
setattr(obj, "_" + k, type(val)(ctx[k]))
ctx.pop(k)
except (AttributeError, TypeError):
try:
val = getattr(obj, k)
setattr(obj, k, type(val)(ctx[k]))
ctx.pop(k)
except AttributeError:
pass
def _override(ctx, *param_dicts):
# Try to use the extra arguments as an override of config.
if ctx.args:
ctx = _ctx_to_dct(ctx.args)
for p in param_dicts:
_update(p, ctx)
# Also update globals, always.
_update(global_params, ctx)
if ctx:
warnings.warn("The following arguments were not able to be set: %s" % ctx)
main = click.Group()
@main.command(
context_settings={ # Doing this allows arbitrary options to override config
"ignore_unknown_options": True,
"allow_extra_args": True,
}
)
@click.option(
"--config",
type=click.Path(exists=True, dir_okay=False),
default=None,
help="Path to the configuration file (default ~/.21cmfast/runconfig_single.yml)",
)
@click.option(
"--regen/--no-regen",
default=False,
help="Whether to force regeneration of init/perturb files if they already exist.",
)
@click.option(
"--direc",
type=click.Path(exists=True, dir_okay=True),
default=None,
help="directory to write data and plots to -- must exist.",
)
@click.option(
"--seed",
type=int,
default=None,
help="specify a random seed for the initial conditions",
)
@click.pass_context
def init(ctx, config, regen, direc, seed):
"""Run a single iteration of 21cmFAST init, saving results to file.
Parameters
----------
ctx :
A parameter from the parent CLI function to be able to override config.
config : str
Path to the configuration file.
regen : bool
Whether to regenerate all data, even if found in cache.
direc : str
Where to search for cached items.
seed : int
Random seed used to generate data.
"""
cfg = _get_config(config)
# Set user/cosmo params from config.
user_params = lib.UserParams(**cfg.get("user_params", {}))
cosmo_params = lib.CosmoParams(**cfg.get("cosmo_params", {}))
_override(ctx, user_params, cosmo_params)
lib.initial_conditions(
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regen,
write=True,
direc=direc,
random_seed=seed,
)
@main.command(
context_settings={ # Doing this allows arbitrary options to override config
"ignore_unknown_options": True,
"allow_extra_args": True,
}
)
@click.argument("redshift", type=float)
@click.option(
"--config",
type=click.Path(exists=True, dir_okay=False),
default=None,
help="Path to the configuration file (default ~/.21cmfast/runconfig_single.yml)",
)
@click.option(
"--regen/--no-regen",
default=False,
help="Whether to force regeneration of init/perturb files if they already exist.",
)
@click.option(
"--direc",
type=click.Path(exists=True, dir_okay=True),
default=None,
help="directory to write data and plots to -- must exist.",
)
@click.option(
"--seed",
type=int,
default=None,
help="specify a random seed for the initial conditions",
)
@click.pass_context
def perturb(ctx, redshift, config, regen, direc, seed):
"""Run 21cmFAST perturb_field at the specified redshift, saving results to file.
Parameters
----------
ctx :
A parameter from the parent CLI function to be able to override config.
redshift : float
Redshift at which to generate perturbed field.
config : str
Path to the configuration file.
regen : bool
Whether to regenerate all data, even if found in cache.
direc : str
Where to search for cached items.
seed : int
Random seed used to generate data.
"""
cfg = _get_config(config)
# Set user/cosmo params from config.
user_params = lib.UserParams(**cfg.get("user_params", {}))
cosmo_params = lib.CosmoParams(**cfg.get("cosmo_params", {}))
_override(ctx, user_params, cosmo_params)
lib.perturb_field(
redshift=redshift,
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regen,
write=True,
direc=direc,
random_seed=seed,
)
@main.command(
context_settings={ # Doing this allows arbitrary options to override config
"ignore_unknown_options": True,
"allow_extra_args": True,
}
)
@click.argument("redshift", type=float)
@click.option(
"-p",
"--prev_z",
type=float,
default=None,
help="Previous redshift (the spin temperature data must already exist for this redshift)",
)
@click.option(
"--config",
type=click.Path(exists=True, dir_okay=False),
default=None,
help="Path to the configuration file (default ~/.21cmfast/runconfig_single.yml)",
)
@click.option(
"--regen/--no-regen",
default=False,
help="Whether to force regeneration of init/perturb files if they already exist.",
)
@click.option(
"--direc",
type=click.Path(exists=True, dir_okay=True),
default=None,
help="directory to write data and plots to -- must exist.",
)
@click.option(
"--seed",
type=int,
default=None,
help="specify a random seed for the initial conditions",
)
@click.pass_context
def spin(ctx, redshift, prev_z, config, regen, direc, seed):
"""Run spin_temperature at the specified redshift, saving results to file.
Parameters
----------
ctx :
A parameter from the parent CLI function to be able to override config.
redshift : float
The redshift to generate the field at.
prev_z : float
The redshift of a previous box from which to evolve to the current one.
config : str
Path to the configuration file.
regen : bool
Whether to regenerate all data, even if found in cache.
direc : str
Where to search for cached items.
seed : int
Random seed used to generate data.
"""
cfg = _get_config(config)
# Set user/cosmo params from config.
user_params = lib.UserParams(**cfg.get("user_params", {}))
cosmo_params = lib.CosmoParams(**cfg.get("cosmo_params", {}))
flag_options = lib.FlagOptions(
**cfg.get("flag_options", {}), USE_VELS_AUX=user_params.USE_RELATIVE_VELOCITIES
)
astro_params = lib.AstroParams(
**cfg.get("astro_params", {}), INHOMO_RECO=flag_options.INHOMO_RECO
)
_override(ctx, user_params, cosmo_params, astro_params, flag_options)
lib.spin_temperature(
redshift=redshift,
astro_params=astro_params,
flag_options=flag_options,
previous_spin_temp=prev_z,
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regen,
write=True,
direc=direc,
random_seed=seed,
)
@main.command(
context_settings={ # Doing this allows arbitrary options to override config
"ignore_unknown_options": True,
"allow_extra_args": True,
}
)
@click.argument("redshift", type=float)
@click.option(
"-p",
"--prev_z",
type=float,
default=None,
help="Previous redshift (the ionized box data must already exist for this redshift)",
)
@click.option(
"--config",
type=click.Path(exists=True, dir_okay=False),
default=None,
help="Path to the configuration file (default ~/.21cmfast/runconfig_single.yml)",
)
@click.option(
"--regen/--no-regen",
default=False,
help="Whether to force regeneration of init/perturb files if they already exist.",
)
@click.option(
"--direc",
type=click.Path(exists=True, dir_okay=True),
default=None,
help="directory to write data and plots to -- must exist.",
)
@click.option(
"--seed",
type=int,
default=None,
help="specify a random seed for the initial conditions",
)
@click.pass_context
def ionize(ctx, redshift, prev_z, config, regen, direc, seed):
"""Run 21cmFAST ionize_box at the specified redshift, saving results to file.
Parameters
----------
ctx :
A parameter from the parent CLI function to be able to override config.
redshift : float
The redshift to generate the field at.
prev_z : float
The redshift of a previous box from which to evolve to the current one.
config : str
Path to the configuration file.
regen : bool
Whether to regenerate all data, even if found in cache.
direc : str
Where to search for cached items.
seed : int
Random seed used to generate data.
"""
cfg = _get_config(config)
# Set user/cosmo params from config.
user_params = lib.UserParams(**cfg.get("user_params", {}))
cosmo_params = lib.CosmoParams(**cfg.get("cosmo_params", {}))
flag_options = lib.FlagOptions(
**cfg.get("flag_options", {}), USE_VELS_AUX=user_params.USE_RELATIVE_VELOCITIES
)
astro_params = lib.AstroParams(
**cfg.get("astro_params", {}), INHOMO_RECO=flag_options.INHOMO_RECO
)
_override(ctx, user_params, cosmo_params, astro_params, flag_options)
lib.ionize_box(
redshift=redshift,
astro_params=astro_params,
flag_options=flag_options,
previous_ionize_box=prev_z,
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regen,
write=True,
direc=direc,
random_seed=seed,
)
@main.command(
context_settings={ # Doing this allows arbitrary options to override config
"ignore_unknown_options": True,
"allow_extra_args": True,
}
)
@click.argument("redshift", type=str)
@click.option(
"--config",
type=click.Path(exists=True, dir_okay=False),
default=None,
help="Path to the configuration file (default ~/.21cmfast/runconfig_single.yml)",
)
@click.option(
"--out",
type=click.Path(dir_okay=True, file_okay=True),
default=None,
help="Path to output full Coeval simulation to (directory OK).",
)
@click.option(
"--regen/--no-regen",
default=False,
help="Whether to force regeneration of init/perturb files if they already exist.",
)
@click.option(
"--direc",
type=click.Path(exists=True, dir_okay=True),
default=None,
help="cache directory",
)
@click.option(
"--seed",
type=int,
default=None,
help="specify a random seed for the initial conditions",
)
@click.pass_context
def coeval(ctx, redshift, config, out, regen, direc, seed):
"""Efficiently generate coeval cubes at a given redshift.
Parameters
----------
ctx :
A parameter from the parent CLI function to be able to override config.
redshift : float
The redshift to generate the field at.
config : str
Path to the configuration file.
regen : bool
Whether to regenerate all data, even if found in cache.
direc : str
Where to search for cached items.
seed : int
Random seed used to generate data.
"""
if out is not None:
out = Path(out).absolute()
if len(out.suffix) not in (2, 3) and not out.exists():
out.mkdir()
elif not out.parent.exists():
out.parent.mkdir()
try:
redshift = [float(z.strip()) for z in redshift.split(",")]
except TypeError:
raise TypeError("redshift argument must be comma-separated list of values.")
cfg = _get_config(config)
# Set user/cosmo params from config.
user_params = lib.UserParams(**cfg.get("user_params", {}))
cosmo_params = lib.CosmoParams(**cfg.get("cosmo_params", {}))
flag_options = lib.FlagOptions(
**cfg.get("flag_options", {}), USE_VELS_AUX=user_params.USE_RELATIVE_VELOCITIES
)
astro_params = lib.AstroParams(
**cfg.get("astro_params", {}), INHOMO_RECO=flag_options.INHOMO_RECO
)
_override(ctx, user_params, cosmo_params, astro_params, flag_options)
coeval = lib.run_coeval(
redshift=redshift,
astro_params=astro_params,
flag_options=flag_options,
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regen,
write=True,
direc=direc,
random_seed=seed,
)
if out:
for i, (z, c) in enumerate(zip(redshift, coeval)):
if out.is_dir():
fname = out / c.get_unique_filename()
elif len(redshift) == 1:
fname = out
else:
out = out.parent / f"{out.name}_z{z}{out.suffix}"
c.save(fname)
print(f"Saved Coeval box to {fname}.")
@main.command(
context_settings={ # Doing this allows arbitrary options to override config
"ignore_unknown_options": True,
"allow_extra_args": True,
}
)
@click.argument("redshift", type=float)
@click.option(
"--config",
type=click.Path(exists=True, dir_okay=False),
default=None,
help="Path to the configuration file (default ~/.21cmfast/runconfig_single.yml)",
)
@click.option(
"--out",
type=click.Path(dir_okay=True, file_okay=True),
default=None,
help="Path to output full Lightcone to (directory OK).",
)
@click.option(
"--regen/--no-regen",
default=False,
help="Whether to force regeneration of init/perturb files if they already exist.",
)
@click.option(
"--direc",
type=click.Path(exists=True, dir_okay=True),
default=None,
help="directory to write data and plots to -- must exist.",
)
@click.option(
"-X",
"--max-z",
type=float,
default=None,
help="maximum redshift of the stored lightcone data",
)
@click.option(
"--seed",
type=int,
default=None,
help="specify a random seed for the initial conditions",
)
@click.pass_context
def lightcone(ctx, redshift, config, out, regen, direc, max_z, seed):
"""Efficiently generate coeval cubes at a given redshift.
Parameters
----------
ctx :
A parameter from the parent CLI function to be able to override config.
redshift : float
The redshift to generate the field at.
config : str
Path to the configuration file.
regen : bool
Whether to regenerate all data, even if found in cache.
direc : str
Where to search for cached items.
max_z : float
Maximum redshift to include in the produced lightcone.
seed : int
Random seed used to generate data.
"""
cfg = _get_config(config)
if out is not None:
out = Path(out).absolute()
if len(out.suffix) not in (2, 3) and not out.exists():
out.mkdir()
elif not out.parent.exists():
out.parent.mkdir()
# Set user/cosmo params from config.
user_params = lib.UserParams(**cfg.get("user_params", {}))
cosmo_params = lib.CosmoParams(**cfg.get("cosmo_params", {}))
flag_options = lib.FlagOptions(
**cfg.get("flag_options", {}), USE_VELS_AUX=user_params.USE_RELATIVE_VELOCITIES
)
astro_params = lib.AstroParams(
**cfg.get("astro_params", {}), INHOMO_RECO=flag_options.INHOMO_RECO
)
_override(ctx, user_params, cosmo_params, astro_params, flag_options)
lc = lib.run_lightcone(
redshift=redshift,
max_redshift=max_z,
astro_params=astro_params,
flag_options=flag_options,
user_params=user_params,
cosmo_params=cosmo_params,
regenerate=regen,
write=True,
direc=direc,
random_seed=seed,
)
if out:
fname = out / lc.get_unique_filename() if out.is_dir() else out
lc.save(fname)
print(f"Saved Lightcone to {fname}.")
def _query(direc=None, kind=None, md5=None, seed=None, clear=False):
cls = list(
cache_tools.query_cache(direc=direc, kind=kind, hsh=md5, seed=seed, show=False)
)
if not clear:
print("%s Data Sets Found:" % len(cls))
print("------------------")
else:
print("Removing %s data sets..." % len(cls))
for file, c in cls:
if not clear:
print(" @ {%s}:" % file)
print(" %s" % str(c))
print()
else:
direc = direc or path.expanduser(_cfg.config["direc"])
remove(path.join(direc, file))
@main.command()
@click.option(
"-d",
"--direc",
type=click.Path(exists=True, dir_okay=True),
default=None,
help="directory to write data and plots to -- must exist.",
)
@click.option("-k", "--kind", type=str, default=None, help="filter by kind of data.")
@click.option("-m", "--md5", type=str, default=None, help="filter by md5 hsh")
@click.option("-s", "--seed", type=str, default=None, help="filter by random seed")
@click.option(
"--clear/--no-clear",
default=False,
help="remove all data sets returned by this query.",
)
def query(direc, kind, md5, seed, clear):
"""Query the cache database.
Parameters
----------
direc : str
Directory in which to search for cache items
kind : str
Filter output by kind of box (eg. InitialConditions)
md5 : str
Filter output by hsh
seed : float
Filter output by random seed.
clear : bool
Remove all data sets returned by the query.
"""
_query(direc, kind, md5, seed, clear)
@main.command()
@click.argument("param", type=str)
@click.argument("value", type=str)
@click.option(
"-s",
"--struct",
type=click.Choice(["flag_options", "cosmo_params", "user_params", "astro_params"]),
default="flag_options",
help="struct in which the new feature exists",
)
@click.option(
"-t",
"--vtype",
type=click.Choice(["bool", "float", "int"]),
default="bool",
help="type of the new parameter",
)
@click.option(
"-l/-c",
"--lightcone/--coeval",
default=True,
help="whether to use a lightcone for comparison",
)
@click.option(
"-z", "--redshift", type=float, default=6.0, help="redshift of the comparison boxes"
)
@click.option(
"-Z",
"--max-redshift",
type=float,
default=30,
help="maximum redshift of the comparison lightcone",
)
@click.option("-r", "--random-seed", type=int, default=12345, help="random seed to use")
@click.option("-v", "--verbose", count=True)
@click.option(
"-g/-G",
"--regenerate/--cache",
default=True,
help="whether to regenerate the boxes",
)
def pr_feature(
param,
value,
struct,
vtype,
lightcone,
redshift,
max_redshift,
random_seed,
verbose,
regenerate,
):
"""
Create standard plots comparing a default simulation against a simulation with a new feature.
The new feature is switched on by setting PARAM to VALUE.
Plots are saved in the current directory, with the prefix "pr_feature".
Parameters
----------
param : str
Name of the parameter to modify to "switch on" the feature.
value : float
Value to which to set it.
struct : str
The input parameter struct to which `param` belongs.
vtype : str
Type of the new parameter.
lightcone : bool
Whether the comparison should be done on a lightcone.
redshift : float
Redshift of comparison.
max_redshift : float
If using a lightcone, the maximum redshift in the lightcone to compare.
random_seed : int
Random seed at which to compare.
verbose : int
How verbose the output should be.
regenerate : bool
Whether to regenerate all data, even if it is in cache.
"""
import powerbox
lvl = [logging.WARNING, logging.INFO, logging.DEBUG][verbose]
logger = logging.getLogger("21cmFAST")
logger.setLevel(lvl)
value = getattr(builtins, vtype)(value)
structs = {
"user_params": {"HII_DIM": 128, "BOX_LEN": 250},
"flag_options": {"USE_TS_FLUCT": True},
"cosmo_params": {},
"astro_params": {},
}
if lightcone:
print("Running default lightcone...")
lc_default = lib.run_lightcone(
redshift=redshift,
max_redshift=max_redshift,
random_seed=random_seed,
regenerate=regenerate,
**structs,
)
structs[struct][param] = value
print("Running lightcone with new feature...")
lc_new = lib.run_lightcone(
redshift=redshift,
max_redshift=max_redshift,
random_seed=random_seed,
regenerate=regenerate,
**structs,
)
print("Plotting lightcone slices...")
for field in ["brightness_temp"]:
fig, ax = plt.subplots(3, 1, sharex=True, sharey=True)
vmin = -150
vmax = 30
plotting.lightcone_sliceplot(
lc_default, ax=ax[0], fig=fig, vmin=vmin, vmax=vmax
)
ax[0].set_title("Default")
plotting.lightcone_sliceplot(
lc_new, ax=ax[1], fig=fig, cbar=False, vmin=vmin, vmax=vmax
)
ax[1].set_title("New")
plotting.lightcone_sliceplot(
lc_default, lightcone2=lc_new, cmap="bwr", ax=ax[2], fig=fig
)
ax[2].set_title("Difference")
plt.savefig(f"pr_feature_lighcone_2d_{field}.pdf")
def rms(x, axis=None):
return np.sqrt(np.mean(x**2, axis=axis))
print("Plotting lightcone history...")
fig, ax = plt.subplots(4, 1, sharex=True, gridspec_kw={"hspace": 0.05})
ax[0].plot(lc_default.node_redshifts, lc_default.global_xHI, label="Default")
ax[0].plot(lc_new.node_redshifts, lc_new.global_xHI, label="New")
ax[0].set_ylabel(r"$x_{\rm HI}$")
ax[0].legend()
ax[1].plot(
lc_default.node_redshifts,
lc_default.global_brightness_temp,
label="Default",
)
ax[1].plot(lc_new.node_redshifts, lc_new.global_brightness_temp, label="New")
ax[1].set_ylabel("$T_b$ [K]")
ax[3].set_xlabel("z")
rms_diff = rms(lc_default.brightness_temp, axis=(0, 1)) - rms(
lc_new.brightness_temp, axis=(0, 1)
)
ax[2].plot(lc_default.lightcone_redshifts, rms_diff, label="RMS")
ax[2].plot(
lc_new.node_redshifts,
lc_default.global_xHI - lc_new.global_xHI,
label="$x_{HI}$",
)
ax[2].plot(
lc_new.node_redshifts,
lc_default.global_brightness_temp - lc_new.global_brightness_temp,
label="$T_b$",
)
ax[2].legend()
ax[2].set_ylabel("Differences")
diff_rms = rms(lc_default.brightness_temp - lc_new.brightness_temp, axis=(0, 1))
ax[3].plot(lc_default.lightcone_redshifts, diff_rms)
ax[3].set_ylabel("RMS of Diff.")
plt.savefig("pr_feature_history.pdf")
print("Plotting power spectra history...")
p_default = []
p_new = []
z = []
thickness = 200 # Mpc
ncells = int(thickness / lc_new.cell_size)
chunk_size = lc_new.cell_size * ncells
start = 0
print(ncells)
while start + ncells <= lc_new.shape[-1]:
pd, k = powerbox.get_power(
lc_default.brightness_temp[:, :, start : start + ncells],
lc_default.lightcone_dimensions[:2] + (chunk_size,),
)
p_default.append(pd)
pn, k = powerbox.get_power(
lc_new.brightness_temp[:, :, start : start + ncells],
lc_new.lightcone_dimensions[:2] + (chunk_size,),
)
p_new.append(pn)
z.append(lc_new.lightcone_redshifts[start])
start += ncells
p_default = np.array(p_default).T
p_new = np.array(p_new).T
fig, ax = plt.subplots(2, 1, sharex=True)
ax[0].set_yscale("log")
inds = [
np.where(np.abs(k - 0.1) == np.abs(k - 0.1).min())[0][0],
np.where(np.abs(k - 0.2) == np.abs(k - 0.2).min())[0][0],
np.where(np.abs(k - 0.5) == np.abs(k - 0.5).min())[0][0],
np.where(np.abs(k - 1) == np.abs(k - 1).min())[0][0],
]
for i, (pdef, pnew, kk) in enumerate(
zip(p_default[inds], p_new[inds], k[inds])
):
ax[0].plot(z, pdef, ls="--", label=f"k={kk:.2f}", color=f"C{i}")
ax[0].plot(z, pnew, ls="-", color=f"C{i}")
ax[1].plot(z, np.log10(pdef / pnew), ls="-", color=f"C{i}")
ax[1].set_xlabel("z")
ax[0].set_ylabel(r"$\Delta^2 [{\rm mK}^2]$")
ax[1].set_ylabel(r"log ratio of $\Delta^2 [{\rm mK}^2]$")
ax[0].legend()
plt.savefig("pr_feature_power_history.pdf")
else:
raise NotImplementedError()
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/cli.py
|
cli.py
|
from pathlib import Path
DATA_PATH = Path(__file__).parent
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/src/py21cmfast/_data/__init__.py
|
__init__.py
|
Developer Documentation
=======================
If you are new to developing ``21cmFAST``, please read the :ref:`contributing:Contributing`
section *first*, which outlines the general concepts for contributing to development,
and provides a step-by-step walkthrough for getting setup.
This page lists some more detailed notes which may be helpful through the
development process.
Compiling for debugging
-----------------------
When developing, it is usually a good idea to compile the underlying C code in ``DEBUG``
mode. This may allow extra print statements in the C, but also will allow running the C
under ``valgrind`` or ``gdb``. To do this::
$ DEBUG=True pip install -e .
See :ref:`installation:Installation` for more installation options.
Developing the C Code
---------------------
In this section we outline how one might go about modifying/extending the C code and
ensuring that the extension is compatible with the wrapper provided here. It is
critical that you run all tests after modifying _anything_ (and see the section
below about running with valgrind). When changing C code, before
testing, ensure that the new C code is compiled into your environment by running::
$ rm -rf build
$ pip install .
Note that using a developer install (`-e`) is not recommended as it stores compiled
objects in the working directory which don't get updated as you change code, and can
cause problems later.
There are two main purposes you may want to write some C code:
1. An external plugin/extension which uses the output data from 21cmFAST.
2. Modifying the internal C code of 21cmFAST.
21cmFAST currently provides no support for external plugins/extensions. It is entirely
possible to write your own C code to do whatever you want with the output data, but we
don't provide any wrapping structure for you to do this, you will need to write your
own. Internally, 21cmFAST uses the ``cffi`` library to aid the wrapping of the C code into
Python. You don't need to do the same, though we recommend it. If your desired
"extension" is something that needs to operate in-between steps of 21cmFAST, we also
provide no support for this, but it is possible, so long as the next step in the
chain maintains its API. You would be required to re-write the low-level wrapping
function _preceding_ your inserted step as well. For instance, if you had written a
self-contained piece of code that modified the initial conditions box, adding some
physical effect which is not already covered, then you would need to write a low-level
wrapper _and_ re-write the ``initial_conditions`` function to modify the box before
returning it. We provide no easy "plugin" system for doing this currently. If your
external code is meant to be inserted _within_ a basic step of 21cmFAST, this is
currently not possible. You will instead have to modify the source code itself.
Modifying the C-code of 21cmFAST should be relatively simple. If your changes are
entirely internal to a given function, then nothing extra needs to be done. A little
more work has to be done if the modifications add/remove input parameters or the output
structure. If any of the input structures are modified (i.e. an extra parameter
added to it), then the corresponding class in ``py21cmfast.wrapper`` must be modified,
usually simply to add the new parameter to the ``_defaults_`` dict with a default value.
For instance, if a new variable ``some_param`` was added to the ``user_params`` struct
in the ``ComputeInitialConditions`` C function, then the ``UserParams`` class in
the wrapper would be modified, adding ``some_param=<default_value>`` to its ``_default_``
dict. If the default value of the parameter is dependent on another parameter, its
default value in this dict can be set to ``None``, and you can give it a dynamic
definition as a Python ``@property``. For example, the ``DIM`` parameter of
``UserParams`` is defined as::
@property
def DIM(self):
if self._some_param is None:
return self._DIM or 4 * self.HII_DIM
Note the underscore in ``_DIM`` here: by default, if a dynamic property is defined for
a given parameter, the ``_default_`` value is saved with a prefixed underscore. Here we
return either the explicitly set ``DIM``, or 4 by the ``HII_DIM``. In addition, if the
new parameter is not settable -- if it is completely determined by other parameters --
then don't put it in ``_defaults_`` at all, and just give it a dynamic definition.
If you modify an output struct, which usually house a number of array quantities
(often float pointers, but not necessarily), then you'll again need to modify the
corresponding class in the wrapper. In particular, you'll need to add an entry for that
particular array in the ``_init_arrays`` method for the class. The entry consists of
initialising that array (usually to zeros, but not necessarily), and setting its proper
dtype. All arrays should be single-pointers, even for multi-dimensional data. The latter
can be handled by initalising the array as a 1D numpy array, but then setting its shape
attribute (after creation) to the appropriate n-dimensional shape (see the
``_init_arrays`` method for the ``InitialConditions`` class for examples of this).
Modifying the ``global_params`` struct should be relatively straightforward, and no
changes in the Python are necessary. However, you may want to consider adding the new
parameter to relevant ``_filter_params`` lists for the output struct wrapping classes in
the wrapper. These lists control which global parameters affect which output structs,
and merely provide for more accurate caching mechanisms.
C Function Standards
~~~~~~~~~~~~~~~~~~~~
The C-level functions are split into two groups -- low-level "private" functions, and
higher-level "public" or "API" functions. All API-level functions are callable from
python (but may also be called from other C functions). All API-level functions are
currently prototyped in ``21cmFAST.h``.
To enable consistency of error-checking in Python (and a reasonable standard for any
kind of code), we enforce that any API-level function must return an integer status.
Any "return" objects must be modified in-place (i.e. passed as pointers). This enables
Python to control the memory access of these variables, and also to receive proper
error statuses (see below for how we do exception handling). We also adhere to the
convention that "output" variables should be passed to the function as its last
argument(s). In the case that _only_ the last argument is meant to be "output", there
exists a simple wrapper ``_call_c_simple`` in ``wrapper.py`` that will neatly handle the
calling of the function in an intuitive pythonic way.
Running with Valgrind
~~~~~~~~~~~~~~~~~~~~~
If any changes to the C code are made, it is ideal to run tests under valgrind, and
check for memory leaks. To do this, install ``valgrind`` (we have tested v3.14+),
which is probably available via your package manager. We provide a
suppression file for ``valgrind`` in the ``devel/`` directory of the main repository.
It is ideal if you install a development-version of python especially for running these
tests. To do this, download the version of python you want and then configure/install with::
$ ./configure --prefix=<your-home>/<directory> --without-pymalloc --with-pydebug --with-valgrind
$ make; make install
Construct a ``virtualenv`` on top of this installation, and create your environment,
and install all requirements.
If you do not wish to run with a modified version of python, you may continue with your
usual version, but may get some extra cruft in the output. If running with Python
version > 3.6, consider running with environment variable ``PYTHONMALLOC=malloc``
(see https://stackoverflow.com/questions/20112989/how-to-use-valgrind-with-python ).
The general pattern for using valgrind with python is::
$ valgrind --tool=memcheck --track-origins=yes --leak-check=full --suppressions=devel/valgrind-suppress-all-but-c.supp <python script>
One useful command is to run valgrind over the test suite (from the top-level repo
directory)::
$ valgrind --tool=memcheck --track-origins=yes --leak-check=full --suppressions=devel/valgrind-suppress-all-but-c.supp pytest
While we will attempt to keep the suppression file updated to the best of our knowledge
so that only relevant leaks and errors are reported, you will likely have to do a bit of
digging to find the relevant parts.
Valgrind will likely run very slowly, and sometimes you will know already which exact
tests are those which may have problems, or are relevant to your particular changes.
To run these::
$ PYTHONMALLOC=malloc valgrind --tool=memcheck --track-origins=yes --leak-check=full --suppressions=devel/valgrind-suppress-all-but-c.supp pytest -v tests/<test_file>::<test_func> > valgrind.out 2>&1
Note that we also routed the stderr output to a file, which is useful because it can be
quite voluminous. There is a python script, ``devel/filter_valgrind.py`` which can be run
over the output (`valgrind.out` in the above command) to filter it down to only have
stuff from 21cmfast in it.
Producing Integration Test Data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are bunch of so-called "integration tests", which rely on previously-produced
data. To produce this data, run ``python tests/produce_integration_test_data.py``.
Furthermore, this data should only be produced with good reason -- the idea is to keep
it static while the code changes, to have something steady to compare to. If a particular
PR fixes a bug which affects a certain tests' data, then that data should be re-run, in
the context of the PR, so it can be explained.
Logging in C
~~~~~~~~~~~~
The C code has a header file ``logging.h``. The C code should *never* contain bare
print-statements -- everything should be formally logged, so that the different levels
can be printed to screen correctly. The levels are defined in ``logging.h``, and include
levels such as ``INFO``, ``WARNING`` and ``DEBUG``. Each level has a corresponding macro
that starts with ``LOG_``. Thus to log run-time information to stdout, you would use
``LOG_INFO("message");``. Note that the message does not require a final newline character.
Exception handling in C
~~~~~~~~~~~~~~~~~~~~~~~
There are various places that things can go wrong in the C code, and they need to be
handled gracefully so that Python knows what to do with it (rather than just quitting!).
We use the simple ``cexcept.h`` header file from http://www.nicemice.net/cexcept/ to
enable a simple form of exception handling. That file itself should **not be edited**.
There is another header -- ``exceptions.h`` -- that defines how we use exceptions
throughout ``21cmFAST``. Any time an error arises that can be understood, the developer
should add a ``Throw <ErrorKind>;`` line. The ``ErrorKind`` can be any of the kinds
defined in ``exceptions.h`` (eg. ``GSLError`` or ``ValueError``). These are just integers.
Any C function that has a header in ``21cmFAST.h`` -- i.e. any function that is callable
directly from Python -- *must* be globally wrapped in a ``Try {} Catch(error_code) {}`` block. See
``GenerateICs.c`` for an example. Most of the code should be in the ``Try`` block.
Anything that does a ``Throw`` at any level of the call stack within that ``Try`` will
trigger a jump to the ``Catch``. The ``error_code`` is the integer that was thrown.
Typically, one will perhaps want to do some cleanup here, and then finally *return* the
error code.
Python knows about the exit codes it can expect to receive, and will raise Python
exceptions accordingly. From the python side, two main kinds of exceptions could be
raised, depending on the error code returned from C. The lesser exception is called a
``ParameterError``, and is supposed to indicate an error that happened merely because
the parameters that were input to the calculation were just too extreme to handle.
In the case of something like an automatic Monte Carlo algorithm that's iterating over
random parameters, one would *usually* want to just keep going at this point, because
perhaps it just wandered too far in parameter space.
The other kind of error is a ``FatalCError``, and this is where things went truly wrong,
and probably will do for any combination of parameters.
If you add a kind of Exception in the C code (to ``exceptions.h``), then be sure to add
a handler for it in the ``_process_exitcode`` function in ``wrapper.py``.
Maintaining Array State
~~~~~~~~~~~~~~~~~~~~~~~
Part of the challenge of maintaining a nice wrapper around the fast C-code is keeping
track of initialized memory, and ensuring that the C structures that require that memory
are pointing to the right place. Most of the arrays that are computed in ``21cmFAST``
are initialized *in Python* (using Numpy), then a pointer to their memory is given to
the C wrapper object.
To make matters more complicated, since some of the arrays are really big, it is sometimes
necessary to write them to disk to relieve memory pressure, and load them back in as required.
That means that any time, a given array in a C-based class may have one of several different "states":
1. Completely Uninitialized
1. Allocated an initialized in memory
1. Computed (i.e. filled with the values defining that array after computation in C)
1. Stored on disk
1. Stored *and* in memory.
It's important to keep track of these states, because when passing the struct to the ``compute()``
function of another struct (as input), we go and check if the array exists in memory, and
initialize it. Of course, we shouldn't initialize it with zeros if in fact it has been computed already
and is sitting on disk ready to be loaded. Thus, the ``OutputStruct`` tries to keep track of these
states for every array in the structure, using the ``_array_state`` dictionary. Every write/read/compute/purge
operation self-consistently modifies the status of the array.
However, one needs to be careful -- you *can* modify the actual state without modifying the ``_array_state``
(eg. simply by doing a ``del object.array``). In the future, we may be able to protect this to some extent,
but for now we rely on the good intent of the user.
Purging/Loading C-arrays to/from Disk
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As of v3.1.0, there are more options for granular I/O, allowing large arrays to be purged from memory
when they are unnecessary for further computation. As a developer, you should be aware of the ``_get_required_input_arrays``
method on all ``OutputStruct`` subclasses. This is available to tell the given class what arrays need to
be available at compute time in any of the input structs. For example, if doing ``PERTURB_ON_HIGH_RES``,
the ``PerturbedField`` requires the hi-res density fields in ``InitialConditions``. This gives indications
as to what boxes can be purged to disk (all the low-res boxes in the ICs, for example).
Currently, this is only used to *check* that all boxes are available at compute time, and is not used
to actually automatically purge anything. Note however that ``InitialConditions`` does have two
custom methods that will purge unnecessary arrays before computing perturb fields or ionization fields.
.. note:: If you add a new quantity to a struct, and it is required input for other structs, you need
to add it to the relevant ``_get_required_input_arrays`` methods.
Further note that as of v3.1.0, partial structs can be written and read from disk (so you can specify
``keys=['hires_density']`` in the ``.read()`` method to just read the hi-res density field into the object.
Branching and Releasing
-----------------------
The aim is to make 21cmFAST's releases as useful, comprehendible, and automatic
as possible. This section lays out explicitly how this works (mostly for the benefit of
the admin(s)).
Versioning
~~~~~~~~~~
The first thing to mention is that we use strict `semantic versioning <https://semver.org>`_
(since v2.0). Thus the versions are ``MAJOR.MINOR.PATCH``, with ``MAJOR`` including
API-breaking changes, ``MINOR`` including new features, and ``PATCH`` fixing bugs or
documentation etc. If you depend on hmf, you can set your dependency as
``21cmFAST >= X.Y < X+1`` and not worry that we'll break your code with an update.
To mechanically handle versioning within the package, we use two methods that we make
to work together automatically. The "true" version of the package is set with
`setuptools-scm <https://pypi.org/project/setuptools-scm/>`_. This stores the version
in the git tag. There are many benefits to this -- one is that the version is unique
for every single change in the code, with commits on top of a release changing the
version. This means that versions accessed via ``py21cmfast.__version__`` are unique and track
the exact code in the package (useful for reproducing results). To get the current
version from command line, simply do ``python setup.py --version`` in the top-level
directory.
To actually bump the version, we use ``bump2version``. The reason for this is that the
CHANGELOG requires manual intervention -- we need to change the "dev-version" section
at the top of the file to the current version. Since this has to be manual, it requires
a specific commit to make it happen, which thus requires a PR (since commits can't be
pushed to master). To get all this to happen as smoothly as possible, we have a little
bash script ``bump`` that should be used to bump the version, which wraps ``bump2version``.
What it does is:
1. Runs ``bump2version`` and updates the ``major``, ``minor`` or ``patch`` part (passed like
``./bump minor``) in the VERSION file.
2. Updates the changelog with the new version heading (with the date),
and adds a new ``dev-version`` heading above that.
3. Makes a commit with the changes.
.. note:: Using the ``bump`` script is currently necessary, but future versions of
``bump2version`` may be able to do this automatically, see
https://github.com/c4urself/bump2version/issues/133.
The VERSION file might seem a bit redundant, and it is NOT recognized as the "official"
version (that is given by the git tag). Notice we didn't make a git tag in the above
script. That's because the tag should be made directly on the merge commit into master.
We do this using a Github Action (``tag-release.yaml``) which runs on every push to master,
reads the VERSION file, and makes a tag based on that version.
Branching
~~~~~~~~~
For branching, we use a very similar model to `git-flow <https://nvie.com/posts/a-successful-git-branching-model/>`_.
That is, we have a ``master`` branch which acts as the current truth against which to develop,
and ``production`` essentially as a deployment branch.
I.e., the ``master`` branch is where all features are merged (and some
non-urgent bugfixes). ``production`` is always production-ready, and corresponds
to a particular version on PyPI. Features should be branched from ``master``,
and merged back to ``production``. Hotfixes can be branched directly from ``production``,
and merged back there directly, *as well as* back into ``master``.
*Breaking changes* must only be merged to ``master`` when it has been decided that the next
version will be a major version. We do not do any long-term support of releases
(so can't make hotfixes to ``v2.x`` when the latest version is ``2.(x+1)``, or make a
new minor version in 2.x when the latest version is 3.x). We have set the default
branch to ``dev`` so that by default, branches are merged there. This is deemed best
for other developers (not maintainers/admins) to get involved, so the default thing is
usually right.
.. note:: Why not a more simple workflow like Github flow? The simple answer is it just
doesn't really make sense for a library with semantic versioning. You get into
trouble straight away if you want to merge a feature but don't want to update
the version number yet (you want to merge multiple features into a nice release).
In practice, this happens quite a lot.
.. note:: OK then, why not just use ``production`` to accrue features and fixes until such
time we're ready to release? The problem here is that if you've merged a few
features into master, but then realize a patch fix is required, there's no
easy way to release that patch without releasing all the merged features, thus
updating the minor version of the code (which may not be desirable). You could
then just keep all features in their own branches until you're ready to release,
but this is super annoying, and doesn't give you the chance to see how they
interact.
Releases
~~~~~~~~
To make a **patch** release, follow these steps:
1. Branch off of ``production``.
2. Write the fix.
3. Write a test that would have broken without the fix.
4. Update the changelog with your changes, under the ``**Bugfixes**`` heading.
5. Commit, push, and create a PR.
6. Locally, run ``./bump patch``.
7. Push.
8. Get a PR review and ensure CI passes.
9. Merge the PR
Note that in the background, Github Actions *should* take care of then tagging ``production``
with the new version, deploying that to PyPI, creating a new PR from master back into
``master``, and accepting that PR. If it fails for one of these steps, they can all be done
manually.
Note that you don't have to merge fixes in this way. You can instead just branch off
``master``, but then the fix won't be included until the next ``minor`` version.
This is easier (the admins do the adminy work) and useful for non-urgent fixes.
Any other fix/feature should be branched from ``master``. Every PR that does anything
noteworthy should have an accompanying edit to the changelog. However, you do not have
to update the version in the changelog -- that is left up to the admin(s). To make a
minor release, they should:
1. Locally, ``git checkout release``
2. ``git merge master``
3. No new features should be merged into ``master`` after that branching occurs.
4. Run ``./bump minor``
5. Make sure everything looks right.
6. ``git push``
7. Ensure all tests pass and get a CI review.
8. Merge into ``production``
The above also works for ``MAJOR`` versions, however getting them *in* to ``master`` is a little
different, in that they should wait for merging until we're sure that the next version
will be a major version.
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/notes_for_developers.rst
|
notes_for_developers.rst
|
.. include:: ../CONTRIBUTING.rst
.. include:: notes_for_developers.rst
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/contributing.rst
|
contributing.rst
|
Tutorials and FAQs
==================
The following introductory tutorials will help you get started with ``21cmFAST``:
.. toctree::
:maxdepth: 2
tutorials/coeval_cubes
tutorials/lightcones
tutorials/mini-halos
tutorials/gather_data
tutorials/relative_velocities
If you've covered the tutorials and still have questions about "how to do stuff" in
``21cmFAST``, consult the FAQs:
.. toctree::
:maxdepth: 2
faqs/installation_faq
faqs/misc
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/tutorials.rst
|
tutorials.rst
|
.. include:: ../AUTHORS.rst
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/authors.rst
|
authors.rst
|
.. include:: readme.rst
Contents
========
.. toctree::
:maxdepth: 2
installation
design
tutorials
reference/index
contributing
authors
changelog
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/index.rst
|
index.rst
|
.. include:: ../INSTALLATION.rst
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/installation.rst
|
installation.rst
|
.. include:: ../CHANGELOG.rst
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/changelog.rst
|
changelog.rst
|
.. include:: ../README.rst
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/readme.rst
|
readme.rst
|
# -*- coding: utf-8 -*-
"""Configuration options for the docs."""
from __future__ import unicode_literals
import os
import subprocess
import sys
from unittest.mock import MagicMock
from pathlib import Path
sys.path.insert(0, str(Path(__file__).absolute().parent.parent / "src"))
class Mock(MagicMock):
"""Make a Mock so that a package doesn't have to actually exist."""
@classmethod
def __getattr__(cls, name):
"""Get stuff."""
return MagicMock()
MOCK_MODULES = [
"py21cmfast.c_21cmfast",
"click",
"tqdm",
"pyyaml",
"scipy",
"scipy.interpolate",
"scipy.integrate",
"scipy.special",
"h5py",
"cached_property",
]
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
# Get the version by running from shell -- this uses the git repo info, rather than
# requiring it to be installed.
out = subprocess.run(["python", "setup.py", "--version"], capture_output=True)
try:
from py21cmfast import cache_tools
except ImportError:
raise
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.coverage",
"sphinx.ext.doctest",
"sphinx.ext.extlinks",
"sphinx.ext.ifconfig",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
"sphinx.ext.mathjax",
"sphinx.ext.autosectionlabel",
"numpydoc",
"nbsphinx",
"IPython.sphinxext.ipython_console_highlighting",
]
if os.getenv("SPELLCHECK"):
extensions += ("sphinxcontrib.spelling",)
spelling_show_suggestions = True
spelling_lang = "en_US"
autosectionlabel_prefix_document = True
autosummary_generate = True
numpydoc_show_class_members = False
source_suffix = ".rst"
master_doc = "index"
project = "21cmFAST"
year = "2020"
author = "The 21cmFAST collaboration"
copyright = "{0}, {1}".format(year, author)
version = (
release
) = out.stdout.decode().rstrip() # Get it from `python setup.py --version`
templates_path = ["templates"]
pygments_style = "trac"
extlinks = {
"issue": ("https://github.com/21cmFAST/21cmFAST/issues/%s", "#"),
"pr": ("https://github.com/21cmFAST/21cmFAST/pull/%s", "PR #"),
}
# on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get("READTHEDOCS", None) == "True"
if not on_rtd: # only set the theme if we're building docs locally
html_theme = "sphinx_rtd_theme"
html_use_smartypants = True
html_last_updated_fmt = "%b %d, %Y"
html_split_index = False
html_sidebars = {"**": ["searchbox.html", "globaltoc.html", "sourcelink.html"]}
html_short_title = "%s-%s" % (project, version)
napoleon_use_ivar = True
napoleon_use_rtype = False
napoleon_use_param = False
mathjax_path = (
"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
)
exclude_patterns = [
"_build",
"Thumbs.db",
".DS_Store",
"templates",
"**.ipynb_checkpoints",
]
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/conf.py
|
conf.py
|
======================================
Design Philosophy and Features for v3+
======================================
Here we describe in broad terms the design philosophy of the *new* ``21cmFAST``,
and some of its new features.
This is useful to get an initial bearing of how to go about using ``21cmFAST``, though
most likely the :doc:`tutorials <tutorials>` will be better for that.
It is also useful for those who have used the "old" ``21cmFAST`` (versions 2.1 and less)
and want to know why they should use this new version (and how to convert).
In doing so, we'll go over some of the key features of ``21cmFAST`` v3+.
To get a more in-depth view of all the options and features available, look at the
very thorough :doc:`API Reference <reference/index>`.
Design Philosophy
=================
The goal of v3 of ``21cmFAST`` is to provide the same computational efficiency and
scientific features of the previous generations, but packaged in a form that adopts the
best modern programming standards, including:
* simple installation
* comprehensive documentation
* comprehensive test suite
* more modular code
* standardised code formatting
* truly open-source and collaborative design (via Github)
Partly to enable these standards, and partly due to the many *extra* benefits it brings,
v3 also has the major distinction of being wrapped entirely in Python. The *extra*
benefits brought by this include:
* a native python library interface (eg. get your output box directly as a ``numpy`` array).
* better file-writing, into the HDF5 format, which saves metadata along with the box data.
* a caching system so that the same data never has to be calculated twice.
* reproducibility: know which exact version of ``21cmFAST``, with what parameters, produced a given dataset.
* significantly improved warnings and error checking/propagation.
* simplicity for adding new additional effects, and inserting them in the calculation pipeline.
We hope that additional features and benefits will be found by the growing community
of ``21cmFAST`` developers and users.
How it Works
============
v3 is *not* a complete rewrite of ``21cmFAST``. Most of the C-code of previous versions
is kept, though it has been modularised and modified in many places. The fundamental
routines are the same (barring bugfixes!).
The major programs of the original version (``init``, ``perturb``, ``ionize`` etc.) have
been converted into modular *functions* in C. Furthermore, most of the global parameters
(and, more often than not, global ``#define`` options) have been modularised and converted
into a series of input "parameter" ``structs``. These get passed into the functions.
Furthermore, each C function, instead of writing a bunch of files, returns an output
``struct`` containing all the stuff it computed.
Each of these functions and structs are wrapped in Python using the ``cffi`` package.
CFFI compiles the C code once upon *installation*. Due to the fact that parameters are
now passed around to the different functions, rather than being global defines, we no
longer need to re-compile every time an option is changed. Python itself can handle
changing the parameters, and can use the outputs in whatever way the user desires.
To maintain continuity with previous versions, a CLI interface is provided (see below)
that acts in a similar fashion to previous versions.
High-level configuration of ``21cmFAST`` can be set using the ``py21cmfast.config``
object. It is essentially a dictionary with its key/values the parameters. To make any
changes in the object permanent, use the ``py21cmfast.config.write()`` method.
One global configuration option is ``direc``, which specifies the directory in which
``21cmFAST`` will cache results by default (this can be overriden directly in any
function, see below for details).
Finally, ``21cmFAST`` contains a more robust cataloguing/caching method. Instead of
saving data with a selection of the dependent parameters written into the filename --
a method which is prone to error if a parameter which is not part of that selection is
modified -- ``21cmFAST`` writes all data into a configurable central directory with a hash
filename unique to *all* parameters upon which the data depends. Each kind of dataset has
attached methods which efficiently search this central directory for matching data to be
read when necessary.
Several arguments are available for all library functions which produce such datasets
that control this output. In this way, the data that is being retrieved is always
reliably produced with the desired parameters, and users need not concern themselves
with how and where the data is saved -- it can be retrieved merely by creating an empty
object with the desired parameters and calling ``.read()``, or even better, by calling
the function to *produce* the given dataset, which will by default just read it in if
available.
CLI
===
The CLI interface always starts with the command ``21cmfast``, and has a number of
subcommands. To list the available subcommands, use::
$ 21cmfast --help
To get help on any subcommand, simply use::
$ 21cmfast <subcommand> --help
Any subcommand which runs some aspect of ``21cmFAST`` will have a ``--config`` option,
which specifies a configuration file. This config file specifies the parameters of the
run. Furthermore, any particular parameter that can be specified in the config file can
be alternatively specified on the command line by appending the command with the
parameter name, eg.::
$ 21cmfast init --config=my_config.yml --HII_DIM=40 hlittle=0.7 --DIM 100 SIGMA_8 0.9
The above command shows the numerous ways in which these parameters can be specified
(with or without leading dashes, and with or without "=").
The CLI interface, while simple to use, does have the limitation that more complex
arguments than can be passed to the library functions are disallowed. For example,
one cannot pass a previously calculated initial conditions box to the ``perturb``
command. However, if such a box has been calculated with the default option to write it
to disk, then it will automatically be found and used in such a situation, i.e. the
following will not re-calculate the init box::
$ 21cmfast init
$ 21cmfast perturb redshift=8.0
This means that almost all of the functionality provided in the library is accessible
via the CLI.
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/design.rst
|
design.rst
|
Installation FAQ
================
Errors with "recompile with -fPIC" for FFTW
-------------------------------------------
Make sure you have installed FFTW with ``--enable-shared``. On Ubuntu, you will
also need to have ``libfftw3-dev`` installed.
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/faqs/installation_faq.rst
|
installation_faq.rst
|
Miscellaneous FAQs
==================
My run seg-faulted, what should I do?
-------------------------------------
Since ``21cmFAST`` is written in C, there is the off-chance that something
catastrophic will happen, causing a segfault. Typically, if this happens, Python will
not print a traceback where the error occurred, and finding the source of such errors
can be difficult. However, one has the option of using the standard library
`faulthandler <https://docs.python.org/3/library/faulthandler.html>`_. Specifying
``-X faulthandler`` when invoking Python will cause a minimal traceback to be printed
to ``stderr`` if a segfault occurs.
Configuring 21cmFAST
--------------------
``21cmFAST`` has a configuration file located at ``~/.21cmfast/config.yml``. This file
specifies some options to use in a rather global sense, especially to do with I/O.
You can directly edit this file to change how ``21cmFAST`` behaves for you across
sessions.
For any particular function call, any of the options may be overwritten by supplying
arguments to the function itself.
To set the configuration for a particular session, you can also set the global ``config``
instance, for example::
>>> import py21cmfast as p21
>>> p21.config['regenerate'] = True
>>> p21.run_lightcone(...)
All functions that use the ``regenerate`` keyword will now use the value you've set in the
config. Sometimes, you may want to be a little more careful -- perhaps you want to change
the configuration for a set of calls, but have it change back to the defaults after that.
We provide a context manager to do this::
>>> with p21.config.use(regenerate=True):
>>> p21.run_lightcone()
>>> print(p21.config['regenerate']) # prints "True"
>>> print(p21.config['regenerate']) # prints "False"
To make the current configuration permanent, simply use the ``write`` method::
>>> p21.config['direc'] = 'my_own_cache'
>>> p21.config.write()
Global Parameters
-----------------
There are a bunch of "global" parameters that are used throughout the C code. These are
parameters that are deemed to be constant enough to not expose them through the
regularly-used input structs, but nevertheless may necessitate modification from
time-to-time. These are accessed through the ``global_params`` object::
>>> from py21cmfast import global_params
Help on the attributes can be obtained via ``help(global_params)`` or
`in the docs <../reference/_autosummary/py21cmfast.inputs.html>`_. Setting the
attributes (which affects them everywhere throughout the code) is as simple as, eg::
>>> global_params.Z_HEAT_MAX = 30.0
If you wish to use a certain parameter for a fixed portion of your code (eg. for a single
run), it is encouraged to use the context manager, eg.::
>>> with global_params.use(Z_HEAT_MAX=10):
>>> run_lightcone(...)
How can I read a Coeval object from disk?
-----------------------------------------
The simplest way to read a :class:`py21cmfast.outputs.Coeval` object that has been
written to disk is by doing::
import py21cmfast as p21c
coeval = p21c.Coeval.read("my_coeval.h5")
However, you may want to read parts of the data, or read the data using a different
language or environment. You can do this as long as you have the HDF5 library (i.e.
h5py for Python). HDF5 is self-documenting, so you should be able to determine the
structure of the file yourself interactively. But here is an example using h5py::
import h5py
fl = h5py.File("my_coeval.h5", "r")
# print a dict of all the UserParams
# the CosmoParams, FlagOptions and AstroParams are accessed the same way.
print(dict(fl['user_params'].attrs))
# print a dict of all globals used for the coeval
print(dict(fl['_globals'].attrs))
# Get the redshift and random seed of the coeval box
redshift = fl.attrs['redshift']
seed = fl.attrs['random_seed']
# Get the Initial Conditions:
print(np.max(fl['InitialConditions']['hires_density'][:]))
# Or brightness temperature
print(np.max(fl['BrightnessTemp']['brightness_temperature'][:]))
# Basically, the different stages of computation are groups in the file, and all
# their consituent boxes are datasets in that group.
# Print out the keys of the group to see what is available:
print(fl['TsBox'].keys())
How can I read a LightCone object from file?
--------------------------------------------
Just like the :class:`py21cmfast.outputs.Coeval` object documented above, the
:class:`py21cmfast.outputs.LightCone` object is most easily read via its ``.read()`` method.
Similarly, it is written using HDF5. Again, the input parameters are stored in their
own sub-objects. However, the lightcone boxes themselves are in the "lightcones" group,
while the globally averaged quantities are in the ``global_quantities`` group::
import h5py
import matplotlib.pyplot as plt
fl = h5py.File("my_lightcone.h5", "r")
Tb = fl['lightcones']['brightness_temp'][:]
assert Tb.ndim==3
global_Tb = fl['global_quantities']['brightness_temp'][:]
redshifts = fl['node_redshifts']
plt.plot(redshifts, global_Tb)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/faqs/misc.rst
|
misc.rst
|
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"ExecuteTime": {
"end_time": "2020-03-14T21:18:49.274149Z",
"start_time": "2020-03-14T21:18:39.580491Z"
}
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib\n",
"%matplotlib inline\n",
"import matplotlib.pyplot as plt\n",
"import py21cmfast as p21c\n",
"\n",
"from py21cmfast import global_params\n",
"from py21cmfast import plotting\n",
"\n",
"\n",
"\n",
"random_seed = 1605\n",
"\n",
"EoR_colour = matplotlib.colors.LinearSegmentedColormap.from_list('mycmap',\\\n",
" [(0, 'white'),(0.33, 'yellow'),(0.5, 'orange'),(0.68, 'red'),\\\n",
" (0.83333, 'black'),(0.9, 'blue'),(1, 'cyan')])\n",
"plt.register_cmap(cmap=EoR_colour)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This result was obtained using 21cmFAST at commit 2bb4807c7ef1a41649188a3efc462084f2e3b2e0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook shows how to include the effect of the DM-baryon relative velocities, and the new EOS2021 parameters.\n",
"\n",
"Based on Muñoz+21 (https://arxiv.org/abs/2110.13919). See https://drive.google.com/drive/folders/1-50AO-i3arCnfHc22YWXJacs4u-xsPL6?usp=sharing for the large (1.5Gpc) AllGalaxies simulation with the same parameters.\n",
"\n",
"It is recommended to do the other tutorials first"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Fiducial and lightcones"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's fix the initial condition for this tutorial."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"ExecuteTime": {
"end_time": "2020-03-14T21:18:50.491836Z",
"start_time": "2020-03-14T21:18:49.277655Z"
}
},
"outputs": [],
"source": [
"output_dir = '/Users/julian/Dropbox/Research/EOS_21/'\n",
"\n",
"HII_DIM = 64\n",
"BOX_LEN = 200 #cell size of ~3 Mpc or below for relative velocities\n",
"\n",
"# USE_FFTW_WISDOM make FFT faster AND use relative velocities. , 'USE_INTERPOLATION_TABLES': True or code is too slow\n",
"user_params = {\"HII_DIM\":HII_DIM, \"BOX_LEN\": BOX_LEN, \"USE_FFTW_WISDOM\": True, 'USE_INTERPOLATION_TABLES': True, \n",
" \"FAST_FCOLL_TABLES\": True, \n",
" \"USE_RELATIVE_VELOCITIES\": True, \"POWER_SPECTRUM\": 5}\n",
"\n",
"#set FAST_FCOLL_TABLES to TRUE if using minihaloes, it speeds up the generation of tables by ~x30 (see Appendix of 2110.13919)\n",
"#USE_RELATIVE_VELOCITIES is important for minihaloes. If True, POWER_SPECTRUM has to be set to 5 (CLASS) to get the transfers.\n",
"\n",
"\n",
"\n",
"initial_conditions = p21c.initial_conditions(user_params=user_params,\n",
" random_seed=random_seed, \n",
" direc=output_dir\n",
" #, regenerate=True\n",
" )\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAATkAAAEKCAYAAABpDyLyAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAgAElEQVR4nO29eZhlV3Uf+lt3HurW1NVdXT1oHkACWzIKTozjgEeMnchDbMOXB9jGlnkxH/aL/YLwBHFMPuwXsJ0Xx4lseGADAmyQIX4eUDBEJn4MEgghEEJT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EtELuhz3z4noc0T0JSL6H0Q0Hu//T0T0G/H29xHRfUSUiDXWfjne/0Yi+lp8nQ9usmnPAMgR0XjMxn85gL9W7fk0Ef0eEf0DET1MRC+O9w8Q0f8T6/I9REQ/ur0RCugXHKhENgF7B2b+AhF9HMBvAcgDeB8zd0vU/RkA/5iZmYh+BsC/BfBL6GiMfYGI/h7AfwLwCmZud+alNdwJ4GpmrhPR8GU0788B/BiALwH4IoC6Ky8y87fFQgbvRifJ+K8DWGTmFwLAYREZDdh9hEnuuY3fRCcOuAbgjT2OOQXgQ3GcZgbAUwDAzBUi+lkA9wH4P5j5iS7nPgTg/UT0FwD+4jLa9WEAHwLwPHTCqb7Nld8dt+E+IhqMJ9DvRse0RVw2fxnXC+hjBHP1uY1RAAPoKMLmAICI3rYq5x0f838D+M/xG9LPrR4X44UAZgGc6FH/DwD4AwAvAvAAEW3qR5WZL6ATI/o96MRNrjuky2fqsj8gIExyz3HchY6Z934Avw0AzPyrzHwLM98SHzME4Nl4e1WVAkR0JTpm660Avp+IvlVXTEQJAKeZ+VPomLjD6Eyom8VvAHgTM0ddyn4ivsa3o2OiLgL4BIA3qOsHczUAQDBXn7OIaR4tZv4AESUB/AMRfScz/5079K0A/oyIngXwWQBXK3meX2bm8zHl4z1E9I/UeUkA7yOiIXTesn6XmRc22z5m/ocNiueJ6B8ADAL46XjfbwH4A+okmokA/DsAH+1xfsBzCEGFJGDfQEQ/CeA2Zn7DpY5V53wancl107SQrZwT0D8I5mrAfqKKjqn7x7t1ASL6FDqafc3dukbAwUZ4kwsICOhrhDe5gICAvkaY5AICAvoaYZILCAjoa4RJLiAgoK8RJrmAgIC+xv8PwWWu95Rm00wAAAAASUVORK5CYII=\n",
"text/plain": [
"<Figure size 432x288 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAATsAAAEKCAYAAABt+vLPAAAABHNCSVQICAgIfAhkiAAAAAlw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r5mZpBuBbwBfJ8lxtkzS08CdwDwz60vs0yEWANPNrFtS2zDEexj4DPAcsALoLto+1swuSRMm3ENSLP3bwG4zOxcgL8lOnROHG7va5rsk84wPADeVaHMa8FA6D7QReA3AzPZL+gKwGPiamW0YYN9VwP2SHgUeHYZcfwIeAt5FMk3rkqLtD6QyLJY0LjWkHyJxeUm37RrG+ZwawN3Y2mYi0EKSobYZQNL3+tOMp21+Bvw8fWL6Yn+7lHOBncCpJY7/EeAu4N3AcklD+udqZm+SzEG9gmRe5mFNBvitAdY7ziHc2NU2vyJx/+4H7gAws1vM7HwzOz9tMx7Yki73Z8FA0hkk7uwFwFWSLs4eWFId8E4zW0Ti+raRGNahcivwTTMrDLDtmvQcl5G4rruBJ4D5mfO7G+tEuBtbo6TDQw6a2R8l1QNLJH3QzP5V1PQ24M+StgDPANMzaYFuNrOt6VCR30m6KLNfPXCfpPEkT10/NrOOocpnZkuOsHmXpCXAOODz6bqyA5rWAAAAcUlEQVTbgbuUFMQpAN8BHimxv1ODeNYTp2xIuh6YY2bzB2ub2ecpEiM75OEkR7OPU324G+uUky4SF/ju43UCSYtIcgb2Hq9zOPnAn+wcx6kJ/MnOcZyawI2d4zg1gRs7x3FqAjd2juPUBG7sHMepCf4Pewjg4ARrZqUAAAAASUVORK5CYII=\n",
"text/plain": [
"<Figure size 432x288 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plotting.coeval_sliceplot(initial_conditions, \"lowres_vcb\");\n",
"plotting.coeval_sliceplot(initial_conditions, \"lowres_density\");"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's run a 'fiducial' model and see its lightcones\n",
"\n",
"Note that the reference model has \n",
"\n",
" F_STAR7_MINI ~ F_STAR10\n",
" and\n",
" F_ESC7_MINI ~ 1%, as low, but conservative fiducial\n",
" Also we take L_X_MINI=L_X out of simplicity (and ignorance)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"ExecuteTime": {
"end_time": "2020-03-14T21:22:09.380149Z",
"start_time": "2020-03-14T21:18:50.496755Z"
}
},
"outputs": [],
"source": [
"# the lightcones we want to plot later together with their color maps and min/max\n",
"lightcone_quantities = ('brightness_temp','Ts_box','xH_box',\"dNrec_box\",'z_re_box','Gamma12_box','J_21_LW_box',\"density\")\n",
"cmaps = [EoR_colour,'Reds','magma','magma','magma','cubehelix','cubehelix','viridis']\n",
"vmins = [-150, 1e1, 0, 0, 5, 0, 0, -1]\n",
"vmaxs = [ 30, 1e3, 1, 2, 9, 1,10, 1]\n",
"\n",
"\n",
"astro_params_vcb = {\"ALPHA_ESC\": -0.3, \"F_ESC10\": -1.35, \n",
" \"ALPHA_STAR\": 0.5, \"F_STAR10\": -1.25, \"t_STAR\" :0.5, \n",
" \"F_STAR7_MINI\": -2.5, \"ALPHA_STAR_MINI\": 0, \"F_ESC7_MINI\" : -1.35, \n",
" \"L_X\": 40.5, \"L_X_MINI\": 40.5, \"NU_X_THRESH\": 500.0, \n",
" \"A_VCB\": 1.0, \"A_LW\": 2.0}\n",
"\n",
"\n",
"\n",
"astro_params_novcb=astro_params_vcb\n",
"astro_params_novcb.update({'A_VCB': 0.0})\n",
"#setting 'A_VCB': 0 sets to zero the effect of relative velocities (fiducial value is 1.0)\n",
"#the parameter 'A_LW' (with fid value of 2.0) does the same for LW feedback.\n",
"\n",
"\n",
"flag_options_fid = {\"INHOMO_RECO\":True, 'USE_MASS_DEPENDENT_ZETA':True, 'USE_TS_FLUCT':True, \n",
" 'USE_MINI_HALOS':True, 'FIX_VCB_AVG':False}\n",
"\n",
"\n",
"flag_options_fid_vavg = flag_options_fid\n",
"flag_options_fid_vavg.update({'FIX_VCB_AVG': True})\n",
"#the flag FIX_VCB_AVG side-steps the relative-velocity ICs, and instead fixes all velocities to some average value. \n",
"#It gets the background right but it's missing VAOs and 21cm power at large scales"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ZMIN=5.\n",
"\n",
"lightcone_fid_vcb = p21c.run_lightcone(\n",
" redshift = ZMIN,\n",
" init_box = initial_conditions,\n",
" flag_options = flag_options_fid,\n",
" astro_params = astro_params_vcb,\n",
" lightcone_quantities=lightcone_quantities,\n",
" global_quantities=lightcone_quantities,\n",
" random_seed = random_seed,\n",
" direc = output_dir,\n",
" write=True#, regenerate=True\n",
")\n",
"\n",
"\n",
"\n",
"\n",
"fig, axs = plt.subplots(len(lightcone_quantities),1,\n",
" figsize=(20,10))#(getattr(lightcone_fid_vcb, lightcone_quantities[0]).shape[2]*0.01,\n",
" #getattr(lightcone_fid_vcb, lightcone_quantities[0]).shape[1]*0.01*len(lightcone_quantities)))\n",
"for ii, lightcone_quantity in enumerate(lightcone_quantities):\n",
" axs[ii].imshow(getattr(lightcone_fid_vcb, lightcone_quantity)[1],\n",
" vmin=vmins[ii], vmax=vmaxs[ii],cmap=cmaps[ii])\n",
" axs[ii].text(1, 0.05, lightcone_quantity,horizontalalignment='right',verticalalignment='bottom',\n",
" transform=axs[ii].transAxes,color = 'red',backgroundcolor='white',fontsize = 15)\n",
" axs[ii].xaxis.set_tick_params(labelsize=10)\n",
" axs[ii].yaxis.set_tick_params(labelsize=0)\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.01)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#also run one without velocities and with fixed vcb=vavg (for comparison) \n",
"\n",
"lightcone_fid_novcb = p21c.run_lightcone(\n",
" redshift = ZMIN,\n",
" init_box = initial_conditions,\n",
" flag_options = flag_options_fid,\n",
" astro_params = astro_params_novcb,\n",
" lightcone_quantities=lightcone_quantities,\n",
" global_quantities=lightcone_quantities,\n",
" random_seed = random_seed,\n",
" direc = output_dir,\n",
" write=True#, regenerate=True\n",
")\n",
"\n",
"lightcone_fid_vcbavg = p21c.run_lightcone(\n",
" redshift = ZMIN,\n",
" init_box = initial_conditions,\n",
" flag_options = flag_options_fid_vavg,\n",
" astro_params = astro_params_vcb,\n",
" lightcone_quantities=lightcone_quantities,\n",
" global_quantities=lightcone_quantities,\n",
" random_seed = random_seed,\n",
" direc = output_dir,\n",
" write=True#, regenerate=True\n",
")\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#plus run one with only atomic-cooling galaxies but same otherwise\n",
"\n",
"flag_options_NOMINI=flag_options_fid\n",
"flag_options_NOMINI.update({'USE_MINI_HALOS': False})\n",
"\n",
"lightcone_fid_NOMINI = p21c.run_lightcone(\n",
" redshift = ZMIN,\n",
" init_box = initial_conditions,\n",
" flag_options = flag_options_NOMINI,\n",
" astro_params = astro_params_vcb,\n",
" lightcone_quantities=lightcone_quantities,\n",
" global_quantities=lightcone_quantities,\n",
" random_seed = random_seed,\n",
" direc = output_dir,\n",
" write=True#, regenerate=True\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#compare vcb and novcb\n",
"\n",
"fig, axs = plt.subplots(2 ,1,\n",
" figsize=(20,6))\n",
"\n",
"axs[0].imshow(getattr(lightcone_fid_vcb, 'brightness_temp')[1],\n",
" vmin=vmins[0], vmax=vmaxs[0],cmap=cmaps[0])\n",
"axs[1].imshow(getattr(lightcone_fid_novcb, 'brightness_temp')[1],\n",
" vmin=vmins[0], vmax=vmaxs[0],cmap=cmaps[0])\n",
"axs[0].text(1, 0.05, 'vcb' ,horizontalalignment='right',verticalalignment='bottom',\n",
" transform=axs[0].transAxes,color = 'red',backgroundcolor='white',fontsize = 15)\n",
"axs[1].text(1, 0.05, 'novcb' ,horizontalalignment='right',verticalalignment='bottom',\n",
" transform=axs[1].transAxes,color = 'red',backgroundcolor='white',fontsize = 15) \n",
"# axs[0].xaxis.set_tick_params(labelsize=10)\n",
"# axs[1].yaxis.set_tick_params(labelsize=0)\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.01)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#plot tau\n",
"\n",
"tau_vcb=tau_novcb=tau_NOMINI=np.array([])\n",
"for il,lightcone in enumerate([lightcone_fid_vcb,lightcone_fid_novcb,lightcone_fid_NOMINI]):\n",
" z_e=np.array([]);\n",
" tau_e=np.array([]);\n",
" for i in range(len(lightcone.node_redshifts)-1):\n",
" tauz=p21c.compute_tau(redshifts=lightcone.node_redshifts[-1:-2-i:-1], \n",
" global_xHI=lightcone.global_xHI[-1:-2-i:-1]) \n",
" tau_e=np.append(tau_e,tauz)\n",
" z_e=np.append(z_e,lightcone.node_redshifts[-2-i])\n",
"\n",
" #add lower zs where we manually set xH=1\n",
" zlow=np.linspace(lightcone.node_redshifts[-1]-0.1, 0.1, 14)\n",
" for zl in zlow:\n",
" tauz=p21c.compute_tau(redshifts=np.array([zl]), global_xHI=np.array([lightcone.global_xHI[-1]])) \n",
" tau_e=np.append([tauz],tau_e)\n",
" z_e=np.append([zl],z_e)\n",
" \n",
" if(il==0):\n",
" tau_vcb=tau_e \n",
" elif (il==1):\n",
" tau_novcb=tau_e \n",
" else:\n",
" tau_NOMINI=tau_e\n",
"\n",
"\n",
"\n",
" \n",
" \n",
"linestyles = ['-', '-.',':']\n",
"colors = ['black','gray','#377eb8']\n",
"lws = [3,1,2]\n",
"\n",
"fig, axs = plt.subplots(1, 1, sharex=True, figsize=(8,4))\n",
" \n",
"kk=0\n",
"axs.plot(z_e, tau_vcb, label = 'vcb',\n",
" color=colors[kk],linestyle=linestyles[kk], lw=lws[kk])\n",
"kk=1\n",
"axs.plot(z_e, tau_novcb, label = 'no vcb',\n",
" color=colors[kk],linestyle=linestyles[kk], lw=lws[kk])\n",
"kk=2\n",
"axs.plot(z_e, tau_NOMINI, label = 'no MINI',\n",
" color=colors[kk],linestyle=linestyles[kk],lw=lws[kk])\n",
"\n",
"axs.set_ylim(0., 0.1)\n",
"axs.set_xlabel('redshift',fontsize=15)\n",
"axs.xaxis.set_tick_params(labelsize=15)\n",
"\n",
"axs.set_xlim(0.,20.)\n",
"axs.set_ylabel('$\\\\tau$',fontsize=15)\n",
"axs.yaxis.set_tick_params(labelsize=15)\n",
"\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.0,wspace=0.0)\n",
"\n",
"tauPmin=0.0561-0.0071\n",
"tauPmax=0.0561+0.0071\n",
"axs.axhspan(tauPmin, tauPmax, alpha=0.34, color='black')\n",
"axs.grid()\n",
"\n",
"#Planck2020: tau=0.0561±0.0071"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#check that the tau z=15-30 is below 0.02 as Planck requires\n",
"print(z_e[-1],z_e[55])\n",
"tau_vcb[-1]-tau_vcb[55]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"linestyles = ['-', '-.',':']\n",
"colors = ['black','gray','#377eb8']\n",
"lws = [3,1,2]\n",
"labels = ['vcb', 'no vcb', 'no MINI']\n",
"\n",
"fig, axs = plt.subplots(1, 1, sharex=True, figsize=(8,4))\n",
" \n",
"for kk,lightcone in enumerate([lightcone_fid_vcb,lightcone_fid_novcb,lightcone_fid_NOMINI]):\n",
" \n",
" axs.plot(lightcone.node_redshifts, lightcone.global_xHI, label = labels[kk],\n",
" color=colors[kk],linestyle=linestyles[kk], lw=lws[kk])\n",
"\n",
"axs.set_ylim(0., 1.)\n",
"axs.set_xlabel('redshift',fontsize=15)\n",
"axs.xaxis.set_tick_params(labelsize=15)\n",
"\n",
"axs.set_xlim(5.,20.)\n",
"axs.set_ylabel('$x_{HI}$',fontsize=15)\n",
"axs.yaxis.set_tick_params(labelsize=15)\n",
"\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.0,wspace=0.0)\n",
"\n",
"axs.grid()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#choose a redshift to print coeval slices and see if there are VAOs. Usually best then T21~T21min/2\n",
"zz=zlist21[40]\n",
"print(zz)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#We plot a coeval box, but we compare the vcb case against the vcb=vavg, since the no velocity (vcb=0) case has a background evolution that is too different.\n",
"coeval_fid_vcb = p21c.run_coeval(\n",
" redshift = zz,\n",
" init_box = initial_conditions,\n",
" flag_options = flag_options_fid,\n",
" astro_params = astro_params_vcb,\n",
" random_seed = random_seed,\n",
" direc = output_dir,\n",
" write=True#, regenerate=True\n",
")\n",
"\n",
"coeval_fid_vcbavg = p21c.run_coeval(\n",
" redshift = zz,\n",
" init_box = initial_conditions,\n",
" flag_options = flag_options_fid_vavg,\n",
" astro_params = astro_params_vcb,\n",
" random_seed = random_seed,\n",
" direc = output_dir,\n",
" write=True#, regenerate=True\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"T21slice_vcb=coeval_fid_vcb.brightness_temp\n",
"T21avg_vcb = np.mean(T21slice_vcb)\n",
"dT21slice_vcb = T21slice_vcb - T21avg_vcb\n",
"\n",
"T21slice_novcb=coeval_fid_vcbavg.brightness_temp\n",
"T21avg_novcb = np.mean(T21slice_novcb)\n",
"dT21slice_novcb = T21slice_novcb - T21avg_novcb\n",
"\n",
"\n",
"\n",
"sigma21=np.sqrt(np.var(dT21slice_vcb))\n",
"\n",
"T21maxplot = 3.0*sigma21\n",
"T21minplot = -2.0 * sigma21\n",
"\n",
"\n",
"\n",
"origin = 'lower'\n",
"extend = 'both'\n",
"\n",
"origin = None\n",
"extend = 'neither'\n",
"\n",
"xx = np.linspace(0, BOX_LEN, HII_DIM, endpoint=False)\n",
"yy = xx\n",
"\n",
"\n",
"\n",
"indexv=0\n",
"\n",
"fig, ax = plt.subplots(2, 2, constrained_layout=True, figsize=(10,8), \n",
" sharex='col', sharey='row',\n",
" gridspec_kw={'hspace': 0, 'wspace': 0})\n",
"\n",
"cs0=ax[0,0].contourf(xx, yy, dT21slice_novcb[indexv], extend=extend, origin=origin, \n",
" vmin=T21minplot, vmax=T21maxplot,cmap='bwr') \n",
"fig.colorbar(cs0, ax=ax[0,0], shrink=0.9, location='left')\n",
"cs1=ax[0,1].contourf(xx, yy, dT21slice_vcb[indexv], extend=extend, origin=origin, \n",
" vmin=T21minplot, vmax=T21maxplot,cmap='bwr')\n",
"fig.colorbar(cs1, ax=ax[0,1], shrink=0.9)\n",
"\n",
"\n",
"\n",
"deltaslice=initial_conditions.lowres_density\n",
"deltaavg = np.mean(deltaslice)\n",
"ddeltaslice = deltaslice - deltaavg\n",
"\n",
"vcbslice=initial_conditions.lowres_vcb\n",
"vcbavg = np.mean(vcbslice)\n",
"dvcbslice = vcbslice\n",
"\n",
"print(vcbavg)\n",
"\n",
"\n",
"csd=ax[1,0].contourf(xx, yy, ddeltaslice[indexv]) \n",
"fig.colorbar(csd, ax=ax[1,0], shrink=0.9, location='left')\n",
"csv=ax[1,1].contourf(xx, yy, dvcbslice[indexv])\n",
"fig.colorbar(csv, ax=ax[1,1], shrink=0.9, extend=extend)\n",
"plt.show()\n",
"\n",
"plt.tight_layout()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"global_quantities = ('brightness_temp','Ts_box','xH_box',\"dNrec_box\",'z_re_box','Gamma12_box','J_21_LW_box',\"density\")\n",
"#choose some to plot...\n",
"plot_quantities = ('brightness_temp','Ts_box','xH_box',\"dNrec_box\",'Gamma12_box','J_21_LW_box')\n",
"ymins = [-120, 1e1, 0, 0, 0, 0]\n",
"ymaxs = [ 30, 1e3, 1, 1, 1,5]\n",
"linestyles = ['-', '-',':','-.','-.',':']\n",
"colors = ['gray','black','#e41a1c','#377eb8','#e41a1c','#377eb8']\n",
"lws = [2,2,2,2]\n",
"\n",
"textss = ['vcb','MCGs']\n",
"factorss = [[0, 1],] * len(textss)\n",
"labelss = [['NO', 'reference'],] * len(textss)\n",
"\n",
"\n",
"fig, axss = plt.subplots(len(plot_quantities), len(labelss),\n",
" sharex=True, figsize=(4*len(labelss),2*len(plot_quantities)))\n",
"\n",
"for pp, texts in enumerate(textss):\n",
" labels = labelss[pp]\n",
" factors = factorss[pp] \n",
" axs = axss[:,pp]\n",
" for kk, label in enumerate(labels):\n",
" factor = factors[kk]\n",
"\n",
" \n",
" if kk==0:\n",
" if pp == 0:\n",
" lightcone = lightcone_fid_NOMINI\n",
" else: \n",
" lightcone = lightcone_fid_novcb\n",
" else:\n",
" lightcone = lightcone_fid_vcb\n",
" \n",
" freqs = 1420.4 / (np.array(lightcone.node_redshifts) + 1.) \n",
" for jj, global_quantity in enumerate(plot_quantities):\n",
" axs[jj].plot(freqs, getattr(lightcone, 'global_%s'%global_quantity.replace('_box','')),\n",
" color=colors[kk],linestyle=linestyles[kk], label = labels[kk],lw=lws[kk])\n",
" \n",
" axs[0].text(0.01, 0.99, texts,horizontalalignment='right',verticalalignment='bottom',\n",
" transform=axs[0].transAxes,fontsize = 15)\n",
" for jj, global_quantity in enumerate(plot_quantities):\n",
" axs[jj].set_ylim(ymins[jj], ymaxs[jj])\n",
" axs[-1].set_xlabel('Frequency/MHz',fontsize=15)\n",
" axs[-1].xaxis.set_tick_params(labelsize=15)\n",
"\n",
" axs[0].set_xlim(1420.4 / (35 + 1.), 1420.4 / (5.5 + 1.))\n",
" zlabels = np.array([ 6, 7, 8, 10, 13, 18, 25, 35])\n",
" ax2 = axs[0].twiny()\n",
" ax2.set_xlim(axs[0].get_xlim())\n",
" ax2.set_xticks(1420.4 / (zlabels + 1.))\n",
" ax2.set_xticklabels(zlabels.astype(np.str)) \n",
" ax2.set_xlabel(\"redshift\",fontsize=15)\n",
" ax2.xaxis.set_tick_params(labelsize=15)\n",
" ax2.grid(False)\n",
" \n",
" if pp == 0:\n",
" axs[0].legend(loc='lower right', ncol=2,fontsize=13,fancybox=True,frameon=True)\n",
" for jj, global_quantity in enumerate(plot_quantities):\n",
" axs[jj].set_ylabel('global_%s'%global_quantity.replace('_box',''),fontsize=15)\n",
" axs[jj].yaxis.set_tick_params(labelsize=15)\n",
" else:\n",
" for jj, global_quantity in enumerate(plot_quantities):\n",
" axs[jj].set_ylabel('global_%s'%global_quantity.replace('_box',''),fontsize=0)\n",
" axs[jj].yaxis.set_tick_params(labelsize=0)\n",
"\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.0,wspace=0.0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" # varying parameters"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"let's vary the parameters that describe mini-halos and see the impact to the global signal.\n",
"Warning: It may take a while to run all these boxes!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We keep other parameters fixed and vary one of following by a factor of 1/3 and 3:\n",
"\n",
" F_STAR7_MINI\n",
" F_ESC7_MINI\n",
" L_X_MINI\n",
" A_LW\n",
" \n",
"We also have a NOmini model where mini-halos are not included"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#defining those color, linstyle, blabla\n",
"linestyles = ['-', '-',':','-.','-.',':']\n",
"colors = ['gray','black','#e41a1c','#377eb8','#e41a1c','#377eb8']\n",
"lws = [1,3,2,2,2,2]\n",
"\n",
"textss = ['varying '+r'$f_{*,7}^{\\rm mol}$',\\\n",
" 'varying '+r'$f_{\\rm esc}^{\\rm mol}$',\\\n",
" 'varying '+r'$L_{\\rm x}^{\\rm mol}$',\\\n",
" 'varying '+r'$A_{\\rm LW}$']\n",
"factorss = [[0, 1, 0.33, 3.0],] * len(textss)\n",
"labelss = [['No Velocity', 'Fiducial', '/3', 'x3'],] * len(textss)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecuteTime": {
"end_time": "2020-03-14T21:28:24.543996Z",
"start_time": "2020-03-14T21:28:24.540228Z"
},
"scrolled": true
},
"outputs": [],
"source": [
"global_quantities = ('brightness_temp','Ts_box','xH_box',\"dNrec_box\",'z_re_box','Gamma12_box','J_21_LW_box',\"density\")\n",
"#choose some to plot...\n",
"plot_quantities = ('brightness_temp','Ts_box','xH_box',\"dNrec_box\",'Gamma12_box','J_21_LW_box')\n",
"ymins = [-120, 1e1, 0, 0, 0, 0]\n",
"ymaxs = [ 30, 1e3, 1, 1, 1,10]\n",
"\n",
"fig, axss = plt.subplots(len(plot_quantities), len(labelss),\n",
" sharex=True, figsize=(4*len(labelss),2*len(global_quantities)))\n",
"\n",
"for pp, texts in enumerate(textss):\n",
" labels = labelss[pp]\n",
" factors = factorss[pp] \n",
" axs = axss[:,pp]\n",
" for kk, label in enumerate(labels):\n",
" flag_options = flag_options_fid.copy()\n",
" astro_params = astro_params_vcb.copy()\n",
" factor = factors[kk]\n",
" if label == 'No Velocity':\n",
" lightcone = lightcone_fid_novcb\n",
" elif label == 'Fiducial':\n",
" lightcone = lightcone_fid_vcb\n",
" else:\n",
" if pp == 0:\n",
" astro_params.update({'F_STAR7_MINI': astro_params_vcb['F_STAR7_MINI']+np.log10(factor)})\n",
" elif pp == 1:\n",
" astro_params.update({'F_ESC7_MINI': astro_params_vcb['F_ESC7_MINI']+np.log10(factor)})\n",
" elif pp == 2:\n",
" astro_params.update({'L_X_MINI': astro_params_vcb['L_X_MINI']+np.log10(factor)})\n",
" elif pp == 3:\n",
" astro_params.update({'A_LW': astro_params_vcb['A_LW']*factor})\n",
" else:\n",
" print('Make a choice!') \n",
"\n",
" lightcone = p21c.run_lightcone(\n",
" redshift = ZMIN,\n",
" init_box = initial_conditions,\n",
" flag_options = flag_options_fid,\n",
" astro_params = astro_params,\n",
" global_quantities=global_quantities,\n",
" random_seed = random_seed,\n",
" direc = output_dir\n",
" )\n",
" \n",
" \n",
"\n",
" freqs = 1420.4 / (np.array(lightcone.node_redshifts) + 1.)\n",
" for jj, global_quantity in enumerate(plot_quantities):\n",
" axs[jj].plot(freqs, getattr(lightcone, 'global_%s'%global_quantity.replace('_box','')),\n",
" color=colors[kk],linestyle=linestyles[kk], label = labels[kk],lw=lws[kk])\n",
" \n",
" axs[0].text(0.01, 0.99, texts,horizontalalignment='left',verticalalignment='top',\n",
" transform=axs[0].transAxes,fontsize = 15)\n",
" for jj, global_quantity in enumerate(plot_quantities):\n",
" axs[jj].set_ylim(ymins[jj], ymaxs[jj])\n",
" axs[-1].set_xlabel('Frequency/MHz',fontsize=15)\n",
" axs[-1].xaxis.set_tick_params(labelsize=15)\n",
"\n",
" axs[0].set_xlim(1420.4 / (35 + 1.), 1420.4 / (5.5 + 1.))\n",
" zlabels = np.array([ 6, 7, 8, 10, 13, 18, 25, 35])\n",
" ax2 = axs[0].twiny()\n",
" ax2.set_xlim(axs[0].get_xlim())\n",
" ax2.set_xticks(1420.4 / (zlabels + 1.))\n",
" ax2.set_xticklabels(zlabels.astype(np.str)) \n",
" ax2.set_xlabel(\"redshift\",fontsize=15)\n",
" ax2.xaxis.set_tick_params(labelsize=15)\n",
" ax2.grid(False)\n",
" \n",
" if pp == 0:\n",
" axs[0].legend(loc='lower right', ncol=2,fontsize=13,fancybox=True,frameon=True)\n",
" for jj, global_quantity in enumerate(plot_quantities):\n",
" axs[jj].set_ylabel('global_%s'%global_quantity.replace('_box',''),fontsize=15)\n",
" axs[jj].yaxis.set_tick_params(labelsize=15)\n",
" else:\n",
" for jj, global_quantity in enumerate(plot_quantities):\n",
" axs[jj].set_ylabel('global_%s'%global_quantity.replace('_box',''),fontsize=0)\n",
" axs[jj].yaxis.set_tick_params(labelsize=0)\n",
"\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.0,wspace=0.0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecuteTime": {
"end_time": "2020-03-14T23:04:29.138653Z",
"start_time": "2020-03-14T23:04:28.772417Z"
}
},
"outputs": [],
"source": [
"# define functions to calculate PS, following py21cmmc\n",
"from powerbox.tools import get_power\n",
"\n",
"def compute_power(\n",
" box,\n",
" length,\n",
" n_psbins,\n",
" log_bins=True,\n",
" ignore_kperp_zero=True,\n",
" ignore_kpar_zero=False,\n",
" ignore_k_zero=False,\n",
"):\n",
" # Determine the weighting function required from ignoring k's.\n",
" k_weights = np.ones(box.shape, dtype=np.int)\n",
" n0 = k_weights.shape[0]\n",
" n1 = k_weights.shape[-1]\n",
"\n",
" if ignore_kperp_zero:\n",
" k_weights[n0 // 2, n0 // 2, :] = 0\n",
" if ignore_kpar_zero:\n",
" k_weights[:, :, n1 // 2] = 0\n",
" if ignore_k_zero:\n",
" k_weights[n0 // 2, n0 // 2, n1 // 2] = 0\n",
"\n",
" res = get_power(\n",
" box,\n",
" boxlength=length,\n",
" bins=n_psbins,\n",
" bin_ave=False,\n",
" get_variance=False,\n",
" log_bins=log_bins,\n",
" k_weights=k_weights,\n",
" )\n",
"\n",
" res = list(res)\n",
" k = res[1]\n",
" if log_bins:\n",
" k = np.exp((np.log(k[1:]) + np.log(k[:-1])) / 2)\n",
" else:\n",
" k = (k[1:] + k[:-1]) / 2\n",
"\n",
" res[1] = k\n",
" return res\n",
"\n",
"def powerspectra(brightness_temp, n_psbins=50, nchunks=10, min_k=0.1, max_k=1.0, logk=True):\n",
" data = []\n",
" chunk_indices = list(range(0,brightness_temp.n_slices,round(brightness_temp.n_slices / nchunks),))\n",
"\n",
" if len(chunk_indices) > nchunks:\n",
" chunk_indices = chunk_indices[:-1]\n",
" chunk_indices.append(brightness_temp.n_slices)\n",
"\n",
" for i in range(nchunks):\n",
" start = chunk_indices[i]\n",
" end = chunk_indices[i + 1]\n",
" chunklen = (end - start) * brightness_temp.cell_size\n",
"\n",
" power, k = compute_power(\n",
" brightness_temp.brightness_temp[:, :, start:end],\n",
" (BOX_LEN, BOX_LEN, chunklen),\n",
" n_psbins,\n",
" log_bins=logk,\n",
" )\n",
" data.append({\"k\": k, \"delta\": power * k ** 3 / (2 * np.pi ** 2)})\n",
" return data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# do 5 chunks but only plot 1 - 4, the 0th has no power for minihalo models where xH=0\n",
"nchunks = 4\n",
"k_fundamental = 2*np.pi/BOX_LEN\n",
"k_max = k_fundamental * HII_DIM\n",
"Nk=np.floor(HII_DIM/1).astype(int)\n",
"\n",
"fig, axss = plt.subplots(nchunks, len(labelss), sharex=True,sharey=True,figsize=(4*len(labelss),3*(nchunks)),subplot_kw={\"xscale\":'log', \"yscale\":'log'})\n",
"\n",
"for pp, texts in enumerate(textss):\n",
" labels = labelss[pp]\n",
" factors = factorss[pp] \n",
" axs = axss[:,pp]\n",
" for kk, label in enumerate(labels):\n",
" flag_options = flag_options_fid.copy()\n",
" astro_params = astro_params_vcb.copy()\n",
" factor = factors[kk]\n",
" if label == 'No Velocity':\n",
" lightcone = lightcone_fid_novcb\n",
" elif label == 'Fiducial':\n",
" lightcone = lightcone_fid_vcb\n",
" else:\n",
" if pp == 0:\n",
" astro_params.update({'F_STAR7_MINI': astro_params_vcb['F_STAR7_MINI']+np.log10(factor)})\n",
" elif pp == 1:\n",
" astro_params.update({'F_ESC7_MINI': astro_params_vcb['F_ESC7_MINI']+np.log10(factor)})\n",
" elif pp == 2:\n",
" astro_params.update({'L_X_MINI': astro_params_vcb['L_X_MINI']+np.log10(factor)})\n",
" elif pp == 3:\n",
" astro_params.update({'A_LW': astro_params_vcb['A_LW']+np.log10(factor)})\n",
" else:\n",
" print('Make a choice!') \n",
"\n",
" lightcone = p21c.run_lightcone(\n",
" redshift = ZMIN,\n",
" init_box = initial_conditions,\n",
" flag_options = flag_options_fid,\n",
" astro_params = astro_params,\n",
" global_quantities=global_quantities,\n",
" random_seed = random_seed,\n",
" direc = output_dir\n",
" )\n",
" \n",
" PS = powerspectra(lightcone, min_k = k_fundamental, max_k = k_max)\n",
" \n",
" for ii in range(nchunks):\n",
" axs[ii].plot(PS[ii+1]['k'], PS[ii+1]['delta'], color=colors[kk],linestyle=linestyles[kk], label = labels[kk],lw=lws[kk])\n",
" \n",
" if pp == len(textss)-1 and kk == 0:\n",
" axs[ii].text(0.99, 0.01, 'Chunk-%02d'%(ii+1),horizontalalignment='right',verticalalignment='bottom',\n",
" transform=axs[ii].transAxes,fontsize = 15)\n",
" \n",
" axs[0].text(0.01, 0.99, texts,horizontalalignment='left',verticalalignment='top',\n",
" transform=axs[0].transAxes,fontsize = 15)\n",
"\n",
" axs[-1].set_xlabel(\"$k$ [Mpc$^{-3}$]\",fontsize=15)\n",
" axs[-1].xaxis.set_tick_params(labelsize=15)\n",
" \n",
" if pp == 0:\n",
" for ii in range(nchunks):\n",
" axs[ii].set_ylim(2e-1, 2e2)\n",
" axs[ii].set_ylabel(\"$k^3 P$\", fontsize=15)\n",
" axs[ii].yaxis.set_tick_params(labelsize=15)\n",
" else:\n",
" for ii in range(nchunks-1):\n",
" axs[ii].set_ylim(2e-1, 2e2)\n",
" axs[ii].set_ylabel(\"$k^3 P$\", fontsize=0)\n",
" axs[ii].yaxis.set_tick_params(labelsize=0)\n",
"\n",
"axss[0,0].legend(loc='lower left', ncol=2,fontsize=13,fancybox=True,frameon=True)\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.0,wspace=0.0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that I've run these simulations in parallel before this tutorial. With these setup, each took ~6h to finish. Here, running means read the cached outputs."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## global properties -- optical depth"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#defining those color, linstyle, blabla\n",
"linestyles = ['-', '-',':','-.','-.',':']\n",
"colors = ['gray','black','#e41a1c','#377eb8','#e41a1c','#377eb8']\n",
"lws = [1,3,2,2,2,2]\n",
"\n",
"textss_tau = ['varying '+r'$f_{*,7}^{\\rm mol}$',\\\n",
" 'varying '+r'$f_{\\rm esc}^{\\rm mol}$',\\\n",
" 'varying '+r'$A_{\\rm LW}$']\n",
"\n",
"factorss_tau = [[0, 1, 0.33, 3.0],] * len(textss_tau)\n",
"labelss_tau = [['No Velocity', 'Fiducial', '/3', 'x3'],] * len(textss_tau)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecuteTime": {
"end_time": "2020-03-14T23:03:40.364465Z",
"start_time": "2020-03-14T23:03:38.244179Z"
},
"scrolled": true
},
"outputs": [],
"source": [
"plot_quantities = ['tau_e']\n",
"ymins = [0]\n",
"ymaxs = [0.2]\n",
"\n",
"\n",
"fig, axss_tau = plt.subplots(len(plot_quantities), len(labelss_tau),\n",
" sharex=True, figsize=(4*len(labelss_tau),3*len(plot_quantities)))\n",
"\n",
"\n",
"\n",
"for pp, texts in enumerate(textss_tau):\n",
" labels = labelss_tau[pp]\n",
" factors = factorss_tau[pp] \n",
" axs = axss_tau[pp]\n",
" for kk, label in enumerate(labels):\n",
" flag_options = flag_options_fid.copy()\n",
" astro_params = astro_params_vcb.copy()\n",
" factor = factors[kk]\n",
" if label == 'No Velocity':\n",
" lightcone = lightcone_fid_novcb\n",
" elif label == 'Fiducial':\n",
" lightcone = lightcone_fid_vcb\n",
" else:\n",
" if pp == 0:\n",
" astro_params.update({'F_STAR7_MINI': astro_params_vcb['F_STAR7_MINI']+np.log10(factor)})\n",
" elif pp == 1:\n",
" astro_params.update({'F_ESC7_MINI': astro_params_vcb['F_ESC7_MINI']+np.log10(factor)})\n",
" elif pp == 2:\n",
" astro_params.update({'A_LW': astro_params_vcb['A_LW']*factor})\n",
" else:\n",
" print('Make a choice!') \n",
"\n",
" lightcone = p21c.run_lightcone(\n",
" redshift = ZMIN,\n",
" init_box = initial_conditions,\n",
" flag_options = flag_options_fid,\n",
" astro_params = astro_params,\n",
" global_quantities=global_quantities,\n",
" random_seed = random_seed,\n",
" direc = output_dir\n",
" )\n",
" \n",
"\n",
" z_e=np.array([]);\n",
" tau_e=np.array([]);\n",
" for i in range(len(lightcone.node_redshifts)-1):\n",
" tauz=p21c.compute_tau(redshifts=lightcone.node_redshifts[-1:-2-i:-1], \n",
" global_xHI=lightcone.global_xHI[-1:-2-i:-1]) \n",
" tau_e=np.append(tau_e,tauz)\n",
" z_e=np.append(z_e,lightcone.node_redshifts[-2-i])\n",
" #print(i,lightcone.node_redshifts[i],tauz)\n",
" \n",
" #add lower zs where we manually set xH=1\n",
" zlow=np.linspace(lightcone.node_redshifts[-1]-0.1, 0.1, 14)\n",
" for zl in zlow:\n",
" tauz=p21c.compute_tau(redshifts=np.array([zl]), global_xHI=np.array([lightcone.global_xHI[-1]])) \n",
" tau_e=np.append([tauz],tau_e)\n",
" z_e=np.append([zl],z_e)\n",
" \n",
" \n",
"# freqs = 1420.4 / (np.array(lightcone.node_redshifts) + 1.)\n",
" for jj, global_quantity in enumerate(plot_quantities):\n",
" axs.plot(z_e, tau_e,\n",
" color=colors[kk],linestyle=linestyles[kk], label = labels[kk],lw=lws[kk])\n",
" \n",
" \n",
" axs.text(0.01, 0.99, texts,horizontalalignment='left',verticalalignment='top',\n",
" transform=axs.transAxes,fontsize = 15)\n",
" axs.set_ylim(ymins[0], ymaxs[0])\n",
" axs.set_xlabel('redshift',fontsize=15)\n",
" axs.xaxis.set_tick_params(labelsize=15)\n",
"\n",
" axs.set_xlim(0.,20.)\n",
"\n",
" if pp == 0:\n",
" for ii in range(nchunks):\n",
" axs.set_ylabel('$\\\\tau$',fontsize=15)\n",
" axs.yaxis.set_tick_params(labelsize=15)\n",
" else:\n",
" for ii in range(nchunks-1):\n",
" axs.yaxis.set_tick_params(labelsize=0)\n",
"\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.0,wspace=0.0)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 21-cm power spectra"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecuteTime": {
"end_time": "2020-03-15T00:04:49.728969Z",
"start_time": "2020-03-15T00:04:47.792544Z"
}
},
"outputs": [],
"source": [
"# do 5 chunks but only plot 1 - 4, the 0th has no power for minihalo models where xH=0\n",
"nchunks = 4\n",
"\n",
"fig, axss = plt.subplots(nchunks, len(labelss), sharex=True,sharey=True,figsize=(4*len(labelss),3*(nchunks)),subplot_kw={\"xscale\":'log', \"yscale\":'log'})\n",
"\n",
"for pp, texts in enumerate(textss):\n",
" labels = labelss[pp]\n",
" factors = factorss[pp] \n",
" axs = axss[:,pp]\n",
" for kk, label in enumerate(labels):\n",
" factor = factors[kk]\n",
" \n",
" if kk==0:\n",
" lightcone = lightcone_fid_vcbavg\n",
" else:\n",
" lightcone = lightcone_fid_vcb\n",
" \n",
" PS = powerspectra(lightcone, min_k = k_fundamental, max_k = k_max)\n",
" for ii in range(nchunks):\n",
" axs[ii].plot(PS[ii+1]['k'], PS[ii+1]['delta'], color=colors[kk],linestyle=linestyles[kk], label = labels[kk],lw=lws[kk])\n",
" \n",
" if pp == len(textss)-1 and kk == 0:\n",
" axs[ii].text(0.99, 0.01, 'Chunk-%02d'%(ii+1),horizontalalignment='right',verticalalignment='bottom',\n",
" transform=axs[ii].transAxes,fontsize = 15)\n",
" \n",
" axs[0].text(0.01, 0.99, texts,horizontalalignment='left',verticalalignment='top',\n",
" transform=axs[0].transAxes,fontsize = 15)\n",
"\n",
" axs[-1].set_xlabel(\"$k$ [Mpc$^{-3}$]\",fontsize=15)\n",
" axs[-1].xaxis.set_tick_params(labelsize=15)\n",
" \n",
" if pp == 0:\n",
" for ii in range(nchunks):\n",
" axs[ii].set_ylim(2e-1, 2e2)\n",
" axs[ii].set_ylabel(\"$k^3 P$\", fontsize=15)\n",
" axs[ii].yaxis.set_tick_params(labelsize=15)\n",
" else:\n",
" for ii in range(nchunks-1):\n",
" axs[ii].set_ylim(2e-1, 2e2)\n",
" axs[ii].set_ylabel(\"$k^3 P$\", fontsize=0)\n",
" axs[ii].yaxis.set_tick_params(labelsize=0)\n",
"\n",
"axss[0,0].legend(loc='lower left', ncol=2,fontsize=13,fancybox=True,frameon=True)\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.0,wspace=0.0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"nchunks=5\n",
"\n",
"textss = ['vcb','vcb']\n",
"factorss = [[0, 1],] * len(textss)\n",
"labelss = [['Regular', 'Avg'],] * len(textss)\n",
"\n",
"k_fundamental = 2*np.pi/BOX_LEN\n",
"k_max = k_fundamental * HII_DIM\n",
"Nk=np.floor(HII_DIM/1).astype(int)\n",
"\n",
"PSv= powerspectra(lightcone_fid_vcb, min_k = k_fundamental, max_k = k_max)\n",
"PSvavg= powerspectra(lightcone_fid_vcbavg, min_k = k_fundamental, max_k = k_max)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"klist= PSv[0]['k']\n",
"P21diff = [(PSv[i]['delta']-PSvavg[i]['delta'])/PSvavg[i]['delta'] for i in range(nchunks)]\n",
"\n",
"import matplotlib.pyplot as plt\n",
"\n",
"\n",
"fig, axss = plt.subplots(nchunks, 1, sharex=True,sharey=True,figsize=(2*len(labelss),3*(nchunks)),subplot_kw={\"xscale\":'linear', \"yscale\":'linear'})\n",
"\n",
"for ii in range(nchunks):\n",
" axss[ii].plot(klist, P21diff[ii])\n",
"\n",
"plt.xscale('log')\n",
"axss[0].legend(loc='lower left', ncol=2,fontsize=13,fancybox=True,frameon=True)\n",
"plt.tight_layout()\n",
"fig.subplots_adjust(hspace = 0.0,wspace=0.0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" "
]
}
],
"metadata": {
"hide_input": false,
"kernelspec": {
"display_name": "Py3.8",
"language": "python",
"name": "py3.8"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/tutorials/relative_velocities.ipynb
|
relative_velocities.ipynb
|
{{ fullname | escape | underline }}
.. currentmodule:: {{ module }}
.. autoclass:: {{ objname }}
{% block methods %}
{% if methods %}
.. rubric:: Methods
.. autosummary::
:toctree: {{ objname }}
{% for item in methods %}
~{{ name }}.{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block attributes %}
{% if attributes %}
.. rubric:: Attributes
.. autosummary::
:toctree: {{ objname }}
{% for item in attributes %}
~{{ name }}.{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/templates/class.rst
|
class.rst
|
{{ fullname | escape | underline }}
.. automodule:: {{ fullname }}
{% block functions %}
{% if functions %}
.. rubric:: Functions
.. autosummary::
:toctree: {{ objname }}
{% for item in functions %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block classes %}
{% if classes %}
.. rubric:: Classes
.. autosummary::
:toctree: {{ objname }}
:template: class.rst
{% for item in classes %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block exceptions %}
{% if exceptions %}
.. rubric:: Exceptions
.. autosummary::
{% for item in exceptions %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/templates/module.rst
|
module.rst
|
py21cmfast
==========
.. testsetup::
from py21cmfast import *
.. autosummary::
:toctree: _autosummary
:template: module.rst
py21cmfast.inputs
py21cmfast.outputs
py21cmfast.wrapper
py21cmfast.plotting
py21cmfast.cache_tools
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/reference/py21cmfast.rst
|
py21cmfast.rst
|
API Reference
=============
.. toctree::
:glob:
:maxdepth: 3
py21cmfast*
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/docs/reference/index.rst
|
index.rst
|
"""Simple script to simulate an MCMC-like routine to check for memory leaks."""
import numpy as np
import os
import psutil
import tracemalloc
from py21cmfast import initial_conditions, perturb_field, run_lightcone
tracemalloc.start()
snapshot = tracemalloc.take_snapshot()
PROCESS = psutil.Process(os.getpid())
oldmem = 0
def trace_print():
"""Print a trace of memory leaks."""
global snapshot
global oldmem
snapshot2 = tracemalloc.take_snapshot()
snapshot2 = snapshot2.filter_traces(
(
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
tracemalloc.Filter(False, tracemalloc.__file__),
)
)
if snapshot is not None:
thismem = PROCESS.memory_info().rss / 1024**2
diff = thismem - oldmem
print(
"===================== Begin Trace (TOTAL MEM={:1.4e} MB... [{:+1.4e} MB]):".format(
thismem, diff
)
)
top_stats = snapshot2.compare_to(snapshot, "lineno", cumulative=True)
for stat in top_stats[:4]:
print(stat)
print("End Trace ===========================================")
oldmem = thismem
snapshot = snapshot2
trace_print()
run_lightcone(
redshift=15,
user_params={
"USE_INTERPOLATION_TABLES": True,
"N_THREADS": 1,
"DIM": 100,
"HII_DIM": 25,
"PERTURB_ON_HIGH_RES": True,
"USE_FFTW_WISDOM": False,
},
flag_options={
"USE_MASS_DEPENDENT_ZETA": True,
"INHOMO_RECO": True,
"USE_TS_FLUCT": True,
},
direc="_cache_%s" % (os.path.basename(__file__)[:-3]),
random_seed=1993,
)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/devel/simulate_mcmc_memory_leak_lightcone.py
|
simulate_mcmc_memory_leak_lightcone.py
|
#!/usr/bin/python
"""Filter valgrind output to only include stuff that's compiled directly from C sources."""
import fileinput
import re
START = re.compile(r"^==\d+== \w")
STOP = re.compile(r"^==\d+== $")
ANY = re.compile(r"^==\d+==")
GOOD = [
re.compile(r"py21cmfast\.c_21cmfast\.c:\d+"),
re.compile(r"SUMMARY"),
]
def main():
"""Find only lines with specified GOOD strings in them."""
in_line = False
current = []
for line in fileinput.input():
if not ANY.search(line):
print(line, end="")
continue
in_line = not STOP.search(line) if in_line else START.search(line)
if in_line:
current.append(line)
else:
for g in GOOD:
match = g.findall("".join(current))
if match:
print("".join(current))
continue
current = []
if __name__ == "__main__":
main()
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/devel/filter_valgrind.py
|
filter_valgrind.py
|
"""Run over output of logging to prepare for diffing."""
import sys
fname = sys.argv[1]
if len(sys.argv) > 2:
REMOVE_LINE_NUMBERS = True
print("REMOVING LINE NUMBERS ")
else:
REMOVE_LINE_NUMBERS = False
with open(fname) as fl:
lines = fl.readlines()
out_lines = []
for line in lines:
bits = line.split("|")
# Get rid of time.
if len(bits) > 2:
line = "|".join(bits[1:])
# get rid of pid
if len(bits) > 2:
pid_bit = line.split("[pid=")[-1].split("]")[0]
line = line.replace(pid_bit, "")
if REMOVE_LINE_NUMBERS and len(bits) > 2:
line_no = line.split(":")[1].split("[")[0].strip()
line = line.replace(line_no, "")
out_lines.append(line)
with open(fname + ".out", "w") as fl:
fl.writelines(out_lines)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/devel/prepare_log_for_diff.py
|
prepare_log_for_diff.py
|
{
"cells": [
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"import matplotlib.pyplot as plt\n",
"\n",
"from py21cmmc import run_lightcone\n",
"import numpy as np\n",
"\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"\n",
"import py21cmmc as p21\n",
"from powerbox import get_power"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"init, perturb, xHI, Tb = p21.run_coeval(\n",
" redshift= 8.0,\n",
" user_params = dict(\n",
" HII_DIM = 100,\n",
" BOX_LEN = 300.0\n",
" )\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAQsAAAD8CAYAAABgtYFHAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvhp/UCwAAIABJREFUeJzsvWmUZddVJvjdN794L17MERljRs6jck4NTlmDLcs2BhuDcWOKoRnKdGOopotiVcPqtYBFUQ2rKGiqi4KyMQWmDNgMRsYWtixLKQ+SUlJOyiFyzsiY53gRbx5v//i+884Np7DCSmGn17p7rVwv333n3nvOuTfO3mfvb3/bcV0Xvvjiiy+vJ4HvdAd88cWX7w7xFwtffPFlXeIvFr744su6xF8sfPHFl3WJv1j44osv6xJ/sfDFF1/WJa+7WDiOE3M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jx7PrX5ZbAhauOu6Y/qcAvAtcKInDXTV59RbH+GG2Fud/5bNmeu6k3ogVwH8OSyMvuFjchynAvxP+Veu6/6dvr6lc/RmY7qVc2TMdd0FAM+CMYuk4ziGfOk9Z3k8+nsC77DsvNUvi1tOC3ccp9JxnGrzM4BHwQrYJwF8Upt9EsB3bua43ub8TwL4l4r43wVg0UDxG22vWylt68gAAAEUSURBVPf/E9hK4ScBfFwR9s0AegC8eh3P6wD47wAuuq77ec+fbtkcvdWYbuEcNTqOk9TPMQCPgHGUZwB8VJu9fo7M3H0UwE9cRTvf0q53lPhdRHEfByPJVwH8h1tw/i1glPo0gPNmDOD67ccAruiz7gaO4W9AyFoA3/i/8VbnB+HjFzRfZwHccRPH9BWd84wetlbP9v9BY+oF8Nh1Hst9IEQ+A+CU/j1+K+fobcZ0q+ZoP4DXdN5zAP5fz/P9KhhQ/QaAiL6P6vc+/X3LO53Dp3v75ptv67JbvQzxzTfffkbMf1n45ptv6zL/ZeGbb76ty/yXhW+++bYu818Wvvnm27rMf1n45ptv6zL/ZeGbb76ty/5/pjv2pF//jL0AAAAASUVORK5CYII=\n",
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(init.lowres_density[:,:,0], extent=(0,300,0,300));"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x7fab4e5afa20>"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAQsAAAD8CAYAAABgtYFHAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvhp/UCwAAIABJREFUeJzsfXd4W9d99ntBgOAACe49RZ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ig9rsPNP2JxZllUjH8heAH+GptHjPiYhhB38T/mqZVmb5NcTOkcDjWki50jBsqxGAJ+APoswIYQSX7qe0zke+fdQDLPsnOiXxYTLwoUQgUKIYPUZwDVgBuxmAHfLze4G8O7FHNcQ598M4OvS478YgENR8fFGv3X/euhM4c0Abpce9ikAUgGMWTciuZZ+HsBxy7KecvnThM3RYGOawDmKFkKEyc/+AK4C/Sg7AdwiN+s/R2rubgGww5LezkEx1l7iEXhx14Ke5BIAP56A808FvdRHAOSpMYDrt48BFMmfEeM4hg0gZe0C3/j3DnZ+kD7+Qc7XUQDzL+KYXpHnzJEP2ySX7X8sx1QAYM0Yj2UZSJFzAGTLf2snco6GGNNEzdFsAIfleXMB/KfL8/0F6FB9E4Cv/N5P/l4s/z51uHMYubeBgYFbmOhliIGBwd8IzMvCwMDALZiXhYGBgVswLwsDAwO3YF4WBgYGbsG8LAwMDNyCeVkYGBi4hf8PM0lgXLvpzdkAAAAASUVORK5CYII=\n",
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(Tb.brightness_temp[:,:,0], extent=(0,300,0,300))"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"p, k = get_power(Tb.brightness_temp, boxlength=Tb.user_params.BOX_LEN)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXoAAAEACAYAAAC9Gb03AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvhp/UCwAAIABJREFUeJzt3Xl8VOW9BvDnzb4Hsk1ICAkkgWTYgkR2KNsgLoggVtHW1nq12nq1i0WpS2urVLi21movLfYqLhVqcUHEBYIsln0newiBrG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SeiQicgFMChcS6OuFH00dCk8PYFpyhNJN0ghlAAACzUlEQVTjEJGLYNC7mCdvTFF6BCJyMfwwlohI4xj0REQax6AnItI4Bj0RkcYx6ImINI5BT0SkcQx6IiKNY9ATEWmckFIqPQOEEDUAiu10uFAA9i7PudZj9vf5fXmerY+15XG9PSYCQK2NM6mdI94rSr2uPY7Zn2P09Tn2ep9e7dfd5X0aL6WMvOoRpJSa+gFgjdqO2d/n9+V5tj7Wlsf19hgAh5T+M1bLn6uaXtcex+zPMfr6HHu9T234db5PL/qhxaWbTSo8Zn+f35fn2fpYWx7niP+HaqTU71ON79H+HqOvz7HX+9Rd3qOAHX6vqli6IdchhDgkpUxXeg6i3vB9eiktntGTY61RegAiG/B9ehGe0RMRaRzP6ImINI5BT0SkcQx6IiKNY9CT3Qghhgkh/k8IsUHpWYguJoQIFEK8JYR4XQhxj9LzOBuDngAAQog3hBDVQoisy74+XwiRL4QoFEI82dsxpJRFUsr7HTspUZc+vmcXA9ggpXwAwK1OH1ZhDHrqthbA/Iu/IITwBPBXADcC0ANYKoTQCyFGCyE+vexHlPNHJje3Fja+ZwEMBlB6/mEWJ86oCrw5OAEApJS7hBAJl315AoBCKWURAAgh1gNYKKX8A4BbnDsh0aX68p4FUIausD8GNzzBdbvfMPVJLL45CwK6/rLEXunBQohwIcTfAIwTQix39HBEPbjSe/ZDALcLIVbDveoTAPCMnnonevjaFa+wk1LWAXjIceMQXVWP71kpZQuA+5w9jFrwjJ56UwYg7qKfDwZQodAsRLbge7YHDHrqzUEAyUKIoUIIHwB3AfhE4ZmIesP3bA8Y9AQAEEKsA7AXwAghRJkQ4n4ppRnAIwC+BJAL4H0pZbaScxJ143vWdiw1IyLSOJ7RExFpHIOeiEjjGPRERBrHoCci0jgGPRGRxjHoiYg0jkFPRKRxDHoiIo1j0BMRadz/A67PoIE0fFOIAAAAAElFTkSuQmCC\n",
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.plot(k,p*k**3)\n",
"plt.xscale('log')\n",
"plt.yscale('log')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"lc = run_lightcone(6.5, max_redshift=12.0, user_params={\"HII_DIM\":100, \"DIM\":300})\n",
"plt.figure(figsize=(10,4))\n",
"plt.imshow(lc.brightness_temp[0], origin='lower')\n",
"plt.colorbar()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:21CMMC]",
"language": "python",
"name": "conda-env-21CMMC-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autoclose": false,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/devel/visualise_boxes_and_power.ipynb
|
visualise_boxes_and_power.ipynb
|
"""Given a log file from Github Actions, takes away stuff that *should* change between runs.
Useful for preparing it to be diff'ed against another log to check where things went wrong.
"""
import sys
fname = sys.argv[1]
if len(sys.argv) > 2:
ignores = sys.argv[2:]
else:
ignores = []
pids = set()
threads = set()
pid_map = {}
with open(fname) as fl:
lines = fl.readlines()
# Get to the start of the testing
for i, line in enumerate(lines):
if "==== test session starts ====" in line:
break
print(f"Starting on line {i}")
for line in lines[i:]:
pids.add(line.split("pid=")[1].split("/")[0] if "pid=" in line else "other")
threads.add(line.split("thr=")[1].split("]")[0] if "thr=" in line else "other")
for ii, pid in enumerate(sorted(pids)):
pid_map[pid] = ii
out = {p: {t: [] for t in threads} for p in pid_map}
for line in lines[(i + 1) :]:
if "======" in line:
break
if any(ign in line for ign in ignores):
continue
ln = "|".join(line.split("|")[1:])
pid = ln.split("pid=")[1].split("/")[0] if "pid=" in ln else "other"
thread = ln.split("thr=")[1].split("]")[0] if "thr=" in ln else "other"
ln = ln.replace(f"pid={pid}", f"pid={pid_map[pid]}")
out[pid][thread].append(ln)
with open(fname + ".processed", "w") as fl:
for key in sorted(pids):
for t in sorted(threads):
fl.writelines(out[key][t])
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/devel/prepare_gh_logs_for_diff.py
|
prepare_gh_logs_for_diff.py
|
"""Simple example script for plotting estimated memory usage."""
import matplotlib.pyplot as plt
import numpy as np
from py21cmfast import AstroParams, CosmoParams, FlagOptions, UserParams
from py21cmfast._memory import estimate_memory_lightcone
user_params = UserParams(
{
"HII_DIM": 250,
"BOX_LEN": 2000.0,
"DIM": 1000,
"N_THREADS": 8,
"USE_RELATIVE_VELOCITIES": True,
"POWER_SPECTRUM": 5,
"USE_FFTW_WISDOM": True,
"PERTURB_ON_HIGH_RES": True,
"USE_INTERPOLATION_TABLES": True,
"FAST_FCOLL_TABLES": True,
}
)
flag_options = FlagOptions(
{
"INHOMO_RECO": True,
"USE_MASS_DEPENDENT_ZETA": True,
"USE_TS_FLUCT": True,
"USE_MINI_HALOS": True,
},
USE_VELS_AUX=True,
)
h2dim = np.array(list(range(200, 1500, 100)))
mems4 = []
for h2 in range(200, 1500, 100):
user_params.update(HII_DIM=h2, DIM=4 * h2)
mem = estimate_memory_lightcone(
max_redshift=1420 / 50 - 1,
redshift=1420 / 200 - 1,
user_params=user_params,
flag_options=flag_options,
cosmo_params=CosmoParams(),
astro_params=AstroParams(),
)
mems4.append(mem)
peaks4 = np.array([m["peak_memory"] / (1024**3) for m in mems4])
mems3 = []
for h2 in range(200, 1500, 100):
user_params.update(HII_DIM=h2, DIM=3 * h2)
mem = estimate_memory_lightcone(
max_redshift=1420 / 50 - 1,
redshift=1420 / 200 - 1,
user_params=user_params,
flag_options=flag_options,
cosmo_params=CosmoParams(),
astro_params=AstroParams(),
)
mems3.append(mem)
peaks3 = np.array([m["peak_memory"] / (1024**3) for m in mems3])
mems2 = []
for h2 in range(200, 1500, 100):
user_params.update(HII_DIM=h2, DIM=2 * h2)
mem = estimate_memory_lightcone(
max_redshift=1420 / 50 - 1,
redshift=1420 / 200 - 1,
user_params=user_params,
flag_options=flag_options,
cosmo_params=CosmoParams(),
astro_params=AstroParams(),
)
mems2.append(mem)
peaks2 = np.array([m["peak_memory"] / (1024**3) for m in mems2])
user_params.update(HII_DIM=1300, DIM=2600) # what we actually did.
mem = estimate_memory_lightcone(
max_redshift=1420 / 50 - 1,
redshift=1420 / 200 - 1,
user_params=user_params,
flag_options=flag_options,
cosmo_params=CosmoParams(),
astro_params=AstroParams(),
)
plt.plot(h2dim, peaks2, label="DIM=2*HII_DIM")
plt.plot(h2dim, peaks3, label="DIM=3*HII_DIM")
plt.plot(h2dim, peaks4, label="DIM=4*HII_DIM")
plt.scatter(
1300,
mem["peak_memory"] / 1024**3,
marker="*",
color="k",
label="Proposed Sims",
s=100,
zorder=3,
)
plt.scatter(
1300, 2924.847, marker="+", color="r", label="Measured Peak RAM", s=75, zorder=3
)
theory = h2dim**3
plt.plot(
h2dim,
theory * (peaks3.max() / theory.max()) * 1.2,
label="HII_DIM^3 scaling",
color="grey",
ls="--",
)
plt.axhline(4000, linestyle="dashed", color="k")
plt.text(h2dim[0], 4300, "Avail RAM on Bridges2-EM")
plt.legend()
plt.yscale("log")
plt.xscale("log")
plt.ylabel("Peak memory (GB)")
plt.xlabel("HII_DIM")
plt.savefig("peak_memory_usage.png")
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/devel/estimated_mem_usage_plot.py
|
estimated_mem_usage_plot.py
|
"""Simple script to simulate an MCMC-like routine to check for memory leaks."""
import numpy as np
import os
import psutil
import tracemalloc
from py21cmfast import initial_conditions, perturb_field, run_coeval
tracemalloc.start()
snapshot = tracemalloc.take_snapshot()
PROCESS = psutil.Process(os.getpid())
oldmem = 0
def trace_print():
"""Print a trace of memory leaks."""
global snapshot
global oldmem
snapshot2 = tracemalloc.take_snapshot()
snapshot2 = snapshot2.filter_traces(
(
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
tracemalloc.Filter(False, tracemalloc.__file__),
)
)
if snapshot is not None:
thismem = PROCESS.memory_info().rss / 1024**2
diff = thismem - oldmem
print(
"===================== Begin Trace (TOTAL MEM={:1.4e} MB... [{:+1.4e} MB]):".format(
thismem, diff
)
)
top_stats = snapshot2.compare_to(snapshot, "lineno", cumulative=True)
for stat in top_stats[:4]:
print(stat)
print("End Trace ===========================================")
oldmem = thismem
snapshot = snapshot2
NITER = 50
init = initial_conditions(
user_params={"HII_DIM": 50, "BOX_LEN": 125.0}, regenerate=True
)
perturb = (
perturb_field(redshift=7, init_boxes=init),
perturb_field(redshift=8, init_boxes=init),
perturb_field(redshift=9, init_boxes=init),
)
astro_params = {"HII_EFF_FACTOR": np.random.normal(30, 0.1)}
for i in range(NITER):
trace_print()
coeval = run_coeval(
redshift=[7, 8, 9],
astro_params=astro_params,
init_box=init,
perturb=perturb,
regenerate=True,
random_seed=init.random_seed,
write=False,
)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/devel/simulate_mcmc_memory_leak.py
|
simulate_mcmc_memory_leak.py
|
"""Quick test of finding halos."""
from py21cmfast import (
AstroParams,
CosmoParams,
FlagOptions,
UserParams,
determine_halo_list,
initial_conditions,
perturb_field,
)
from py21cmfast._utils import StructInstanceWrapper
from py21cmfast.c_21cmfast import ffi, lib
global_params = StructInstanceWrapper(lib.global_params, ffi)
user_params = UserParams(
DIM=150,
HII_DIM=50,
BOX_LEN=150.0,
USE_FFTW_WISDOM=False,
HMF=1,
N_THREADS=1,
NO_RNG=True,
PERTURB_ON_HIGH_RES=True,
)
flag_options = FlagOptions(
USE_MASS_DEPENDENT_ZETA=True,
USE_TS_FLUCT=False,
INHOMO_RECO=False,
SUBCELL_RSD=False,
M_MIN_in_Mass=False,
PHOTON_CONS=False,
)
if __name__ == "__main__":
random_seed = 42
cosmo_params = CosmoParams(
OMb=0.0486, OMm=0.3075, POWER_INDEX=0.97, SIGMA_8=0.82, hlittle=0.6774
)
astro_params = AstroParams(
ALPHA_ESC=-0.5,
ALPHA_STAR=0.5,
F_ESC10=-1.30102999566,
F_STAR10=-1.0,
L_X=40.5,
M_TURN=8.7,
NU_X_THRESH=500.0,
X_RAY_SPEC_INDEX=1.0,
t_STAR=0.5,
R_BUBBLE_MAX=15.0,
)
init_box = initial_conditions(
user_params=user_params,
cosmo_params=cosmo_params,
random_seed=random_seed,
regenerate=True,
write=False,
)
redshift = 9.0
pt_box = perturb_field(
redshift=redshift,
init_boxes=init_box,
user_params=user_params,
cosmo_params=cosmo_params,
)
halos = determine_halo_list(
redshift=redshift,
init_boxes=init_box,
user_params=user_params,
cosmo_params=cosmo_params,
astro_params=astro_params,
flag_options=flag_options,
regenerate=True,
write=False,
OPTIMIZE=False,
)
print(halos.halo_masses)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/devel/TestFindHalos.py
|
TestFindHalos.py
|
import pytest
import logging
import os
from py21cmfast import UserParams, config, global_params, run_lightcone, wrapper
from py21cmfast.cache_tools import clear_cache
def pytest_addoption(parser):
parser.addoption("--log-level-21", action="store", default="WARNING")
@pytest.fixture(scope="session")
def tmpdirec(tmp_path_factory):
"""Pytest fixture instantiating a new session-scope "data" folder.
Parameters
----------
tmpdir_factory :
Pytest fixture for creating temporary directories.
"""
return tmp_path_factory.mktemp("data")
def printdir(direc):
try:
width = os.get_terminal_size().columns
except OSError:
width = 100
print()
print(f" Files In {direc} ".center(width, "="))
for pth in direc.iterdir():
print(f"\t {pth.name:<20}:\t\t {pth.stat().st_size / 1024**2:.3f} KB")
print("=" * width)
@pytest.fixture(scope="module")
def module_direc(tmp_path_factory):
original = config["direc"]
direc = tmp_path_factory.mktemp("modtmp")
config["direc"] = str(direc)
yield direc
printdir(direc)
# Clear all cached items created.
clear_cache(direc=str(direc))
# Set direc back to original.
config["direc"] = original
@pytest.fixture(scope="function")
def test_direc(tmp_path_factory):
original = config["direc"]
direc = tmp_path_factory.mktemp("testtmp")
config["direc"] = str(direc)
yield direc
printdir(direc)
# Clear all cached items created.
clear_cache(direc=str(direc))
# Set direc back to original.
config["direc"] = original
@pytest.fixture(autouse=True, scope="session")
def setup_and_teardown_package(tmpdirec, request):
# Set nice global defaults for testing purposes, to make runs faster
# (can always be over-ridden per-test).
original_zprime = global_params.ZPRIME_STEP_FACTOR
# Set default global parameters for all tests
global_params.ZPRIME_STEP_FACTOR = 1.2
# Set default config parameters for all tests.
config["direc"] = str(tmpdirec)
config["regenerate"] = True
config["write"] = False
log_level = request.config.getoption("--log-level-21") or logging.INFO
logging.getLogger("py21cmfast").setLevel(log_level)
yield
printdir(tmpdirec)
clear_cache(direc=str(tmpdirec))
global_params.ZPRIME_STEP_FACTOR = original_zprime
# ======================================================================================
# Create a default set of boxes that can be used throughout.
# ======================================================================================
@pytest.fixture(scope="session")
def default_user_params():
return UserParams(HII_DIM=35, DIM=70, BOX_LEN=50)
@pytest.fixture(scope="session")
def ic(default_user_params, tmpdirec):
return wrapper.initial_conditions(
user_params=default_user_params, write=True, direc=tmpdirec, random_seed=12
)
@pytest.fixture(scope="session")
def redshift():
"""A default redshift to evaluate at. Not too high, not too low."""
return 15
@pytest.fixture(scope="session")
def max_redshift():
"""A default redshift to evaluate at. Not too high, not too low."""
return 25
@pytest.fixture(scope="session")
def low_redshift():
"""A default redshift to evaluate at. Not too high, not too low."""
return 8
@pytest.fixture(scope="session")
def perturb_field(ic, redshift):
"""A default perturb_field"""
return wrapper.perturb_field(redshift=redshift, init_boxes=ic, write=True)
@pytest.fixture(scope="session")
def lc(perturb_field, max_redshift):
return run_lightcone(perturb=perturb_field, max_redshift=max_redshift)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/conftest.py
|
conftest.py
|
import pytest
from py21cmfast._utils import PHOTONCONSERROR, ParameterError
from py21cmfast.c_21cmfast import lib
from py21cmfast.wrapper import _call_c_simple
@pytest.mark.parametrize("subfunc", [True, False])
def test_basic(subfunc):
status = lib.SomethingThatCatches(subfunc)
assert status == PHOTONCONSERROR
@pytest.mark.parametrize("subfunc", [True, False])
def test_simple(subfunc):
with pytest.raises(ParameterError):
_call_c_simple(lib.FunctionThatCatches, subfunc, False)
def test_pass():
answer = _call_c_simple(lib.FunctionThatCatches, True, True)
assert answer == 5.0
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_exceptions.py
|
test_exceptions.py
|
"""
Unit tests for input structures
"""
import pytest
import pickle
from py21cmfast import AstroParams # An example of a struct with defaults
from py21cmfast import CosmoParams, FlagOptions, UserParams, __version__, global_params
from py21cmfast.inputs import validate_all_inputs
@pytest.fixture(scope="module")
def c():
return CosmoParams(SIGMA_8=0.8)
def test_diff(c):
"""Ensure that the python dict has all fields"""
d = CosmoParams(SIGMA_8=0.9)
assert c is not d
assert c != d
assert hash(c) != hash(d)
def test_constructed_the_same(c):
c2 = CosmoParams(SIGMA_8=0.8)
assert c is not c2
assert c == c2
assert hash(c) == hash(c2)
def test_bad_construction(c):
with pytest.raises(TypeError):
CosmoParams(c, c)
with pytest.raises(TypeError):
CosmoParams(UserParams())
with pytest.raises(TypeError):
CosmoParams(1)
def test_warning_bad_params():
with pytest.warns(
UserWarning, match="The following parameters to CosmoParams are not supported"
):
CosmoParams(SIGMA_8=0.8, bad_param=1)
def test_constructed_from_itself(c):
c3 = CosmoParams(c)
assert c == c3
assert c is not c3
def test_dynamic_variables():
u = UserParams()
assert u.DIM == 3 * u.HII_DIM
u.update(DIM=200)
assert u.DIM == 200
def test_clone():
u = UserParams()
v = u.clone()
assert u == v
def test_repr(c):
assert "SIGMA_8:0.8" in repr(c)
def test_pickle(c):
# Make sure we can pickle/unpickle it.
c4 = pickle.dumps(c)
c4 = pickle.loads(c4)
assert c == c4
# Make sure the c data gets loaded fine.
assert c4._cstruct.SIGMA_8 == c._cstruct.SIGMA_8
def test_self(c):
c5 = CosmoParams(c.self)
assert c5 == c
assert c5.pystruct == c.pystruct
assert c5.defining_dict == c.defining_dict
assert (
c5.defining_dict != c5.pystruct
) # not the same because the former doesn't include dynamic parameters.
assert c5.self == c.self
def test_update():
c = CosmoParams()
c_pystruct = c.pystruct
c.update(
SIGMA_8=0.9
) # update c parameters. since pystruct as dynamically created, it is a new object each call.
assert c_pystruct != c.pystruct
def test_c_structures(c):
# See if the C structures are behaving correctly
c2 = CosmoParams(SIGMA_8=0.8)
assert c() != c2()
assert (
c() is c()
) # Re-calling should not re-make the object (object should have persistence)
def test_c_struct_update():
c = CosmoParams()
_c = c()
c.update(SIGMA_8=0.8)
assert _c != c()
def test_update_inhomo_reco(caplog):
ap = AstroParams(R_BUBBLE_MAX=25)
ap.update(INHOMO_RECO=True)
msg = (
"You are setting R_BUBBLE_MAX != 50 when INHOMO_RECO=True. "
+ "This is non-standard (but allowed), and usually occurs upon manual update of INHOMO_RECO"
)
ap.R_BUBBLE_MAX
assert msg in caplog.text
def test_mmin():
fo = FlagOptions(USE_MASS_DEPENDENT_ZETA=True)
assert fo.M_MIN_in_Mass
def test_globals():
orig = global_params.Z_HEAT_MAX
with global_params.use(Z_HEAT_MAX=10.0):
assert global_params.Z_HEAT_MAX == 10.0
assert global_params._cobj.Z_HEAT_MAX == 10.0
assert global_params.Z_HEAT_MAX == orig
def test_fcoll_on(caplog):
f = UserParams(FAST_FCOLL_TABLES=True, USE_INTERPOLATION_TABLES=False)
assert not f.FAST_FCOLL_TABLES
assert (
"You cannot turn on FAST_FCOLL_TABLES without USE_INTERPOLATION_TABLES"
in caplog.text
)
@pytest.mark.xfail(
__version__ >= "4.0.0", reason="the warning can be removed in v4", strict=True
)
def test_interpolation_table_warning():
with pytest.warns(UserWarning, match="setting has changed in v3.1.2"):
UserParams().USE_INTERPOLATION_TABLES
with pytest.warns(None) as record:
UserParams(USE_INTERPOLATION_TABLES=True).USE_INTERPOLATION_TABLES
assert not record
def test_validation():
c = CosmoParams()
a = AstroParams(R_BUBBLE_MAX=100)
f = FlagOptions()
u = UserParams(BOX_LEN=50)
with global_params.use(HII_FILTER=2):
with pytest.warns(UserWarning, match="Setting R_BUBBLE_MAX to BOX_LEN"):
validate_all_inputs(
cosmo_params=c, astro_params=a, flag_options=f, user_params=u
)
assert a.R_BUBBLE_MAX == u.BOX_LEN
a.update(R_BUBBLE_MAX=20)
with global_params.use(HII_FILTER=1):
with pytest.raises(ValueError, match="Your R_BUBBLE_MAX is > BOX_LEN/3"):
validate_all_inputs(
cosmo_params=c, astro_params=a, flag_options=f, user_params=u
)
def test_user_params():
up = UserParams()
up_non_cubic = UserParams(NON_CUBIC_FACTOR=1.5)
assert up_non_cubic.tot_fft_num_pixels == 1.5 * up.tot_fft_num_pixels
assert up_non_cubic.HII_tot_num_pixels == up.HII_tot_num_pixels * 1.5
with pytest.raises(
ValueError,
match="NON_CUBIC_FACTOR \\* DIM and NON_CUBIC_FACTOR \\* HII_DIM must be integers",
):
up = UserParams(NON_CUBIC_FACTOR=1.1047642)
up.NON_CUBIC_FACTOR
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_input_structs.py
|
test_input_structs.py
|
import pytest
import yaml
from click.testing import CliRunner
from py21cmfast import InitialConditions, cli, query_cache
@pytest.fixture(scope="module")
def runner():
return CliRunner()
@pytest.fixture(scope="module")
def cfg(default_user_params, tmpdirec):
with open(tmpdirec / "cfg.yml", "w") as f:
yaml.dump({"user_params": default_user_params.self}, f)
return tmpdirec / "cfg.yml"
def test_init(module_direc, default_user_params, runner, cfg):
# Run the CLI. There's no way to turn off writing from the CLI (since that
# would be useless). We produce a *new* initial conditions box in a new
# directory and check that it exists. It gets auto-deleted after.
result = runner.invoke(
cli.main,
["init", "--direc", str(module_direc), "--seed", "101010", "--config", cfg],
)
if result.exception:
print(result.output)
assert result.exit_code == 0
ic = InitialConditions(user_params=default_user_params, random_seed=101010)
assert ic.exists(direc=str(module_direc))
def test_init_param_override(module_direc, runner, cfg):
# Run the CLI
result = runner.invoke(
cli.main,
[
"init",
"--direc",
str(module_direc),
"--seed",
"102030",
"--config",
cfg,
"--",
"HII_DIM",
"37",
"DIM=52",
"--OMm",
"0.33",
],
)
assert result.exit_code == 0
boxes = [
res[1]
for res in query_cache(
direc=str(module_direc), kind="InitialConditions", seed=102030
)
]
assert len(boxes) == 1
box = boxes[0]
assert box.user_params.HII_DIM == 37
assert box.user_params.DIM == 52
assert box.cosmo_params.OMm == 0.33
assert box.cosmo_params.cosmo.Om0 == 0.33
def test_perturb(module_direc, runner, cfg):
# Run the CLI
result = runner.invoke(
cli.main,
[
"perturb",
"35",
"--direc",
str(module_direc),
"--seed",
"101010",
"--config",
cfg,
],
)
assert result.exit_code == 0
def test_spin(module_direc, runner, cfg):
# Run the CLI
result = runner.invoke(
cli.main,
[
"spin",
"34.9",
"--direc",
str(module_direc),
"--seed",
"101010",
"--config",
cfg,
],
)
print(result.output)
assert result.exit_code == 0
def test_ionize(module_direc, runner, cfg):
# Run the CLI
result = runner.invoke(
cli.main,
[
"ionize",
"35",
"--direc",
str(module_direc),
"--seed",
"101010",
"--config",
cfg,
],
)
assert result.exit_code == 0
def test_coeval(module_direc, runner, cfg):
# Run the CLI
result = runner.invoke(
cli.main,
[
"coeval",
"35",
"--direc",
str(module_direc),
"--seed",
"101010",
"--config",
cfg,
],
)
assert result.exit_code == 0
def test_lightcone(module_direc, runner, cfg):
# Run the CLI
result = runner.invoke(
cli.main,
[
"lightcone",
"30",
"--direc",
str(module_direc),
"--seed",
"101010",
"--config",
cfg,
"-X",
"35",
],
)
assert result.exit_code == 0
def test_query(test_direc, runner, cfg):
# Quickly run the default example once again.
# Run the CLI
result = runner.invoke(
cli.main,
["init", "--direc", str(test_direc), "--seed", "101010", "--config", cfg],
)
assert result.exit_code == 0
result = runner.invoke(
cli.main, ["query", "--direc", str(test_direc), "--seed", "101010"]
)
assert result.output.startswith("1 Data Sets Found:")
assert "random_seed:101010" in result.output
assert "InitialConditions(" in result.output
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_cli.py
|
test_cli.py
|
import pytest
from py21cmfast.inputs import DATA_PATH
@pytest.fixture(scope="module")
def datafiles():
return list(DATA_PATH.glob("*.dat"))
def test_exists(datafiles):
for fl in datafiles:
assert fl.exists()
assert (DATA_PATH / "x_int_tables").exists()
assert (DATA_PATH / "x_int_tables").is_dir()
def test_readable(datafiles):
for fname in datafiles:
with open(fname) as fl:
assert len(fl.read()) > 0
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_data_exists.py
|
test_data_exists.py
|
import pytest
import yaml
from os import path
import py21cmfast as p21
from py21cmfast._cfg import Config
@pytest.fixture(scope="module")
def cfgdir(tmp_path_factory):
return tmp_path_factory.mktemp("config_test_dir")
def test_config_context(cfgdir, default_user_params):
with p21.config.use(direc=cfgdir, write=True):
init = p21.initial_conditions(user_params=default_user_params)
assert (cfgdir / init.filename).exists()
assert "config_test_dir" not in p21.config["direc"]
def test_config_write(cfgdir):
with p21.config.use(direc=str(cfgdir)):
p21.config.write(cfgdir / "config.yml")
with open(cfgdir / "config.yml") as fl:
new_config = yaml.load(fl, Loader=yaml.FullLoader)
# Test adding new kind of string alias
new_config["boxdir"] = new_config["direc"]
del new_config["direc"]
with open(cfgdir / "config.yml", "w") as fl:
yaml.dump(new_config, fl)
with pytest.warns(UserWarning):
new_config = Config.load(cfgdir / "config.yml")
assert "boxdir" not in new_config
assert "direc" in new_config
with open(cfgdir / "config.yml") as fl:
new_config = yaml.load(fl, Loader=yaml.FullLoader)
assert "boxdir" not in new_config
assert "direc" in new_config
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_config.py
|
test_config.py
|
from py21cmfast.c_21cmfast import lib
def test_init_heat():
out = lib.init_heat()
assert out == 0
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_tables.py
|
test_tables.py
|
"""
Produce integration test data, which is tested by the `test_integration_features.py`
tests. One thing to note here is that all redshifts are reasonably high.
This is necessary, because low redshifts mean that neutral fractions are small,
and then numerical noise gets relatively more important, and can make the comparison
fail at the tens-of-percent level.
"""
import click
import glob
import h5py
import logging
import numpy as np
import os
import questionary as qs
import sys
import tempfile
from pathlib import Path
from powerbox import get_power
from py21cmfast import (
AstroParams,
CosmoParams,
FlagOptions,
InitialConditions,
UserParams,
config,
determine_halo_list,
global_params,
initial_conditions,
perturb_field,
perturb_halo_list,
run_coeval,
run_lightcone,
)
logger = logging.getLogger("py21cmfast")
logging.basicConfig()
SEED = 12345
DATA_PATH = Path(__file__).parent / "test_data"
DEFAULT_USER_PARAMS = {
"HII_DIM": 50,
"DIM": 150,
"BOX_LEN": 100,
"NO_RNG": True,
"USE_INTERPOLATION_TABLES": True,
}
DEFAULT_ZPRIME_STEP_FACTOR = 1.04
LIGHTCONE_FIELDS = [
"density",
"velocity",
"xH_box",
"Ts_box",
"z_re_box",
"Gamma12_box",
"dNrec_box",
"x_e_box",
"Tk_box",
"J_21_LW_box",
"brightness_temp",
]
COEVAL_FIELDS = [
"lowres_density",
"lowres_vx_2LPT",
"lowres_vx",
] + LIGHTCONE_FIELDS
OPTIONS = {
"simple": [12, {}],
"perturb_high_res": [12, {"PERTURB_ON_HIGH_RES": True}],
"change_step_factor": [11, {"zprime_step_factor": 1.02}],
"change_z_heat_max": [30, {"z_heat_max": 40}],
"larger_step_factor": [
13,
{"zprime_step_factor": 1.05, "z_heat_max": 25, "HMF": 0},
],
"interp_perturb_field": [16, {"interp_perturb_field": True}],
"mdzeta": [14, {"USE_MASS_DEPENDENT_ZETA": True}],
"rsd": [9, {"SUBCELL_RSD": True}],
"inhomo": [10, {"INHOMO_RECO": True}],
"tsfluct": [16, {"HMF": 3, "USE_TS_FLUCT": True}],
"mmin_in_mass": [20, {"z_heat_max": 45, "M_MIN_in_Mass": True, "HMF": 2}],
"fftw_wisdom": [35, {"USE_FFTW_WISDOM": True}],
"mini_halos": [
18,
{
"z_heat_max": 25,
"USE_MINI_HALOS": True,
"USE_MASS_DEPENDENT_ZETA": True,
"INHOMO_RECO": True,
"USE_TS_FLUCT": True,
"zprime_step_factor": 1.1,
"N_THREADS": 4,
"USE_FFTW_WISDOM": True,
"NUM_FILTER_STEPS_FOR_Ts": 8,
},
],
"nthreads": [8, {"N_THREADS": 2}],
"photoncons": [10, {"PHOTON_CONS": True}],
"mdz_and_photoncons": [
8.5,
{
"USE_MASS_DEPENDENT_ZETA": True,
"PHOTON_CONS": True,
"z_heat_max": 25,
"zprime_step_factor": 1.1,
},
],
"mdz_and_ts_fluct": [
9,
{
"USE_MASS_DEPENDENT_ZETA": True,
"USE_TS_FLUCT": True,
"INHOMO_RECO": True,
"PHOTON_CONS": True,
"z_heat_max": 25,
"zprime_step_factor": 1.1,
},
],
"minimize_mem": [
9,
{
"USE_MASS_DEPENDENT_ZETA": True,
"USE_TS_FLUCT": True,
"INHOMO_RECO": True,
"PHOTON_CONS": True,
"z_heat_max": 25,
"zprime_step_factor": 1.1,
"MINIMIZE_MEMORY": True,
},
],
"mdz_and_tsfluct_nthreads": [
8.5,
{
"N_THREADS": 2,
"USE_FFTW_WISDOM": True,
"USE_MASS_DEPENDENT_ZETA": True,
"INHOMO_RECO": True,
"USE_TS_FLUCT": True,
"PHOTON_CONS": True,
"z_heat_max": 25,
"zprime_step_factor": 1.1,
},
],
"halo_field": [9, {"USE_HALO_FIELD": True}],
"halo_field_mdz": [
8.5,
{
"USE_MASS_DEPENDENT_ZETA": True,
"USE_HALO_FIELD": True,
"USE_TS_FLUCT": True,
"z_heat_max": 25,
"zprime_step_factor": 1.1,
},
],
"halo_field_mdz_highres": [
8.5,
{
"USE_MASS_DEPENDENT_ZETA": True,
"USE_HALO_FIELD": True,
"USE_TS_FLUCT": False,
"PERTURB_ON_HIGH_RES": True,
"N_THREADS": 4,
"z_heat_max": 25,
"zprime_step_factor": 1.1,
},
],
"mdz_tsfluct_nthreads": [
12.0,
{
"USE_MASS_DEPENDENT_ZETA": True,
"USE_TS_FLUCT": True,
"PERTURB_ON_HIGH_RES": False,
"N_THREADS": 4,
"z_heat_max": 25,
"zprime_step_factor": 1.2,
"NUM_FILTER_STEPS_FOR_Ts": 4,
"USE_INTERPOLATION_TABLES": False,
},
],
"ts_fluct_no_tables": [
12.0,
{
"USE_TS_FLUCT": True,
"N_THREADS": 4,
"z_heat_max": 25,
"zprime_step_factor": 1.2,
"NUM_FILTER_STEPS_FOR_Ts": 4,
"USE_INTERPOLATION_TABLES": False,
},
],
"minihalos_no_tables": [
12.0,
{
"USE_MINI_HALOS": True,
"USE_MASS_DEPENDENT_ZETA": True,
"USE_TS_FLUCT": True,
"N_THREADS": 4,
"z_heat_max": 25,
"zprime_step_factor": 1.1,
"NUM_FILTER_STEPS_FOR_Ts": 4,
"USE_INTERPOLATION_TABLES": False,
},
],
"fast_fcoll_hiz": [
18,
{"N_THREADS": 4, "FAST_FCOLL_TABLES": True, "USE_INTERPOLATION_TABLES": True},
],
"fast_fcoll_lowz": [
8,
{"N_THREADS": 4, "FAST_FCOLL_TABLES": True, "USE_INTERPOLATION_TABLES": True},
],
"relvel": [
18,
{
"z_heat_max": 25,
"USE_MINI_HALOS": True,
"zprime_step_factor": 1.1,
"N_THREADS": 4,
"NUM_FILTER_STEPS_FOR_Ts": 8,
"USE_INTERPOLATION_TABLES": True,
"FAST_FCOLL_TABLES": True,
"USE_RELATIVE_VELOCITIES": True,
},
],
"lyman_alpha_heating": [
8,
{"N_THREADS": 4, "USE_CMB_HEATING": False},
],
"cmb_heating": [
8,
{"N_THREADS": 4, "USE_LYA_HEATING": False},
],
}
if len(set(OPTIONS.keys())) != len(list(OPTIONS.keys())):
raise ValueError("There is a non-unique option name!")
OPTIONS_PT = {
"simple": [10, {}],
"no2lpt": [10, {"USE_2LPT": False}],
"linear": [10, {"EVOLVE_DENSITY_LINEARLY": 1}],
"highres": [10, {"PERTURB_ON_HIGH_RES": True}],
}
if len(set(OPTIONS_PT.keys())) != len(list(OPTIONS_PT.keys())):
raise ValueError("There is a non-unique option_pt name!")
OPTIONS_HALO = {"halo_field": [9, {"USE_HALO_FIELD": True}]}
if len(set(OPTIONS_HALO.keys())) != len(list(OPTIONS_HALO.keys())):
raise ValueError("There is a non-unique option_halo name!")
def get_defaults(kwargs, cls):
return {k: kwargs.get(k, v) for k, v in cls._defaults_.items()}
def get_all_defaults(kwargs):
flag_options = get_defaults(kwargs, FlagOptions)
astro_params = get_defaults(kwargs, AstroParams)
cosmo_params = get_defaults(kwargs, CosmoParams)
user_params = get_defaults(kwargs, UserParams)
return user_params, cosmo_params, astro_params, flag_options
def get_all_options(redshift, **kwargs):
user_params, cosmo_params, astro_params, flag_options = get_all_defaults(kwargs)
user_params.update(DEFAULT_USER_PARAMS)
out = {
"redshift": redshift,
"user_params": user_params,
"cosmo_params": cosmo_params,
"astro_params": astro_params,
"flag_options": flag_options,
"use_interp_perturb_field": kwargs.get("use_interp_perturb_field", False),
"random_seed": SEED,
}
for key in kwargs:
if key.upper() in (k.upper() for k in global_params.keys()):
out[key] = kwargs[key]
return out
def get_all_options_ics(**kwargs):
user_params, cosmo_params, astro_params, flag_options = get_all_defaults(kwargs)
user_params.update(DEFAULT_USER_PARAMS)
out = {
"user_params": user_params,
"cosmo_params": cosmo_params,
"random_seed": SEED,
}
for key in kwargs:
if key.upper() in (k.upper() for k in global_params.keys()):
out[key] = kwargs[key]
return out
def get_all_options_halo(redshift, **kwargs):
user_params, cosmo_params, astro_params, flag_options = get_all_defaults(kwargs)
user_params.update(DEFAULT_USER_PARAMS)
out = {
"redshift": redshift,
"user_params": user_params,
"cosmo_params": cosmo_params,
"astro_params": astro_params,
"flag_options": flag_options,
"random_seed": SEED,
}
for key in kwargs:
if key.upper() in (k.upper() for k in global_params.keys()):
out[key] = kwargs[key]
return out
def produce_coeval_power_spectra(redshift, **kwargs):
options = get_all_options(redshift, **kwargs)
with config.use(ignore_R_BUBBLE_MAX_error=True):
coeval = run_coeval(write=write_ics_only_hook, **options)
p = {}
for field in COEVAL_FIELDS:
if hasattr(coeval, field):
p[field], k = get_power(
getattr(coeval, field), boxlength=coeval.user_params.BOX_LEN
)
return k, p, coeval
def produce_lc_power_spectra(redshift, **kwargs):
options = get_all_options(redshift, **kwargs)
with config.use(ignore_R_BUBBLE_MAX_error=True):
lightcone = run_lightcone(
max_redshift=options["redshift"] + 2,
lightcone_quantities=[
k
for k in LIGHTCONE_FIELDS
if (
options["flag_options"].get("USE_TS_FLUCT", False)
or k not in ("Ts_box", "x_e_box", "Tk_box", "J_21_LW_box")
)
],
write=write_ics_only_hook,
**options,
)
p = {}
for field in LIGHTCONE_FIELDS:
if hasattr(lightcone, field):
p[field], k = get_power(
getattr(lightcone, field), boxlength=lightcone.lightcone_dimensions
)
return k, p, lightcone
def produce_perturb_field_data(redshift, **kwargs):
options = get_all_options(redshift, **kwargs)
options_ics = get_all_options_ics(**kwargs)
out = {
key: kwargs[key]
for key in kwargs
if key.upper() in (k.upper() for k in global_params.keys())
}
velocity_normalisation = 1e16
with config.use(regenerate=True, write=False):
init_box = initial_conditions(**options_ics)
pt_box = perturb_field(redshift=redshift, init_boxes=init_box, **out)
p_dens, k_dens = get_power(
pt_box.density,
boxlength=options["user_params"]["BOX_LEN"],
)
p_vel, k_vel = get_power(
pt_box.velocity * velocity_normalisation,
boxlength=options["user_params"]["BOX_LEN"],
)
def hist(kind, xmin, xmax, nbins):
data = getattr(pt_box, kind)
if kind == "velocity":
data = velocity_normalisation * data
bins, edges = np.histogram(
data,
bins=np.linspace(xmin, xmax, nbins),
range=[xmin, xmax],
density=True,
)
left, right = edges[:-1], edges[1:]
X = np.array([left, right]).T.flatten()
Y = np.array([bins, bins]).T.flatten()
return X, Y
X_dens, Y_dens = hist("density", -0.8, 2.0, 50)
X_vel, Y_vel = hist("velocity", -2, 2, 50)
return k_dens, p_dens, k_vel, p_vel, X_dens, Y_dens, X_vel, Y_vel, init_box
def produce_halo_field_data(redshift, **kwargs):
options_halo = get_all_options_halo(redshift, **kwargs)
with config.use(regenerate=True, write=False):
pt_halos = perturb_halo_list(**options_halo)
return pt_halos
def get_filename(kind, name, **kwargs):
# get sorted keys
fname = f"{kind}_{name}.h5"
return DATA_PATH / fname
def get_old_filename(redshift, kind, **kwargs):
# get sorted keys
kwargs = {k: kwargs[k] for k in sorted(kwargs)}
string = "_".join(f"{k}={v}" for k, v in kwargs.items())
fname = f"{kind}_z{redshift:.2f}_{string}.h5"
return DATA_PATH / fname
def write_ics_only_hook(obj, **params):
if isinstance(obj, InitialConditions):
obj.write(**params)
def produce_power_spectra_for_tests(name, redshift, force, direc, **kwargs):
fname = get_filename("power_spectra", name)
# Need to manually remove it, otherwise h5py tries to add to it
if fname.exists():
if force:
fname.unlink()
else:
print(f"Skipping {fname} because it already exists.")
return fname
# For tests, we *don't* want to use cached boxes, but we also want to use the
# cache between the power spectra and lightcone. So we create a temporary
# directory in which to cache results.
with config.use(direc=direc):
k, p, coeval = produce_coeval_power_spectra(redshift, **kwargs)
k_l, p_l, lc = produce_lc_power_spectra(redshift, **kwargs)
with h5py.File(fname, "w") as fl:
for k, v in kwargs.items():
fl.attrs[k] = v
fl.attrs["HII_DIM"] = coeval.user_params.HII_DIM
fl.attrs["DIM"] = coeval.user_params.DIM
fl.attrs["BOX_LEN"] = coeval.user_params.BOX_LEN
coeval_grp = fl.create_group("coeval")
coeval_grp["k"] = k
for key, val in p.items():
coeval_grp[f"power_{key}"] = val
lc_grp = fl.create_group("lightcone")
lc_grp["k"] = k_l
for key, val in p_l.items():
lc_grp[f"power_{key}"] = val
lc_grp["global_xH"] = lc.global_xH
lc_grp["global_brightness_temp"] = lc.global_brightness_temp
print(f"Produced {fname} with {kwargs}")
return fname
def produce_data_for_perturb_field_tests(name, redshift, force, **kwargs):
(
k_dens,
p_dens,
k_vel,
p_vel,
X_dens,
Y_dens,
X_vel,
Y_vel,
init_box,
) = produce_perturb_field_data(redshift, **kwargs)
fname = get_filename("perturb_field_data", name)
# Need to manually remove it, otherwise h5py tries to add to it
if os.path.exists(fname):
if force:
os.remove(fname)
else:
return fname
with h5py.File(fname, "w") as fl:
for k, v in kwargs.items():
fl.attrs[k] = v
fl.attrs["HII_DIM"] = init_box.user_params.HII_DIM
fl.attrs["DIM"] = init_box.user_params.DIM
fl.attrs["BOX_LEN"] = init_box.user_params.BOX_LEN
fl["power_dens"] = p_dens
fl["k_dens"] = k_dens
fl["power_vel"] = p_vel
fl["k_vel"] = k_vel
fl["pdf_dens"] = Y_dens
fl["x_dens"] = X_dens
fl["pdf_vel"] = Y_vel
fl["x_vel"] = X_vel
print(f"Produced {fname} with {kwargs}")
return fname
def produce_data_for_halo_field_tests(name, redshift, force, **kwargs):
pt_halos = produce_halo_field_data(redshift, **kwargs)
fname = get_filename("halo_field_data", name)
# Need to manually remove it, otherwise h5py tries to add to it
if os.path.exists(fname):
if force:
os.remove(fname)
else:
return fname
with h5py.File(fname, "w") as fl:
for k, v in kwargs.items():
fl.attrs[k] = v
fl["n_pt_halos"] = pt_halos.n_halos
fl["pt_halo_masses"] = pt_halos.halo_masses
print(f"Produced {fname} with {kwargs}")
return fname
main = click.Group()
@main.command()
@click.option("--log-level", default="WARNING")
@click.option("--force/--no-force", default=False)
@click.option("--remove/--no-remove", default=True)
@click.option("--pt-only/--not-pt-only", default=False)
@click.option("--no-pt/--pt", default=False)
@click.option("--no-halo/--do-halo", default=False)
@click.option(
"--names",
multiple=True,
type=click.Choice(list(OPTIONS.keys())),
default=list(OPTIONS.keys()),
)
def go(
log_level: str,
force: bool,
remove: bool,
pt_only: bool,
no_pt: bool,
no_halo,
names,
):
logger.setLevel(log_level.upper())
global_params.ZPRIME_STEP_FACTOR = DEFAULT_ZPRIME_STEP_FACTOR
if names != list(OPTIONS.keys()):
remove = False
force = True
if pt_only or no_pt or no_halo:
remove = False
# For tests, we *don't* want to use cached boxes, but we also want to use the
# cache between the power spectra and lightcone. So we create a temporary
# directory in which to cache results.
direc = tempfile.mkdtemp()
fnames = []
if not pt_only:
for name in names:
redshift = OPTIONS[name][0]
kwargs = OPTIONS[name][1]
fnames.append(
produce_power_spectra_for_tests(name, redshift, force, direc, **kwargs)
)
if not no_pt:
for name, (redshift, kwargs) in OPTIONS_PT.items():
fnames.append(
produce_data_for_perturb_field_tests(name, redshift, force, **kwargs)
)
if not no_halo:
for name, (redshift, kwargs) in OPTIONS_HALO.items():
fnames.append(
produce_data_for_halo_field_tests(name, redshift, force, **kwargs)
)
# Remove extra files that
if not (names or pt_only or no_pt or no_halo):
all_files = DATA_PATH.glob("*")
for fl in all_files:
if fl not in fnames:
if remove:
print(f"Removing old file: {fl}")
os.remove(fl)
else:
print(f"File is now redundant and can be removed: {fl}")
@main.command()
def convert():
"""Convert old-style data file names to new ones."""
all_files = DATA_PATH.glob("*")
old_names = {
get_old_filename(v[0], "power_spectra", **v[1]): k for k, v in OPTIONS.items()
}
old_names_pt = {
get_old_filename(v[0], "perturb_field_data", **v[1]): k
for k, v in OPTIONS_PT.items()
}
old_names_hf = {
get_old_filename(v[0], "halo_field_data", **v[1]): k
for k, v in OPTIONS_HALO.items()
}
for fl in all_files:
if fl.name.startswith("power_spectra"):
if fl.stem.split("power_spectra_")[-1] in OPTIONS:
continue
elif fl in old_names:
new_file = get_filename("power_spectra", old_names[fl])
fl.rename(new_file)
continue
elif fl.name.startswith("perturb_field_data"):
if fl.stem.split("perturb_field_data_")[-1] in OPTIONS_PT:
continue
elif fl in old_names_pt:
new_file = get_filename("perturb_field_data", old_names_pt[fl])
fl.rename(new_file)
continue
elif fl.name.startswith("halo_field_data"):
if fl.stem.split("halo_field_data_")[-1] in OPTIONS_HALO:
continue
elif fl in old_names_hf:
new_file = get_filename("halo_field_data", old_names_hf[fl])
fl.rename(new_file)
continue
if qs.confirm(f"Remove {fl}?").ask():
fl.unlink()
@main.command()
def clean():
"""Convert old-style data file names to new ones."""
all_files = DATA_PATH.glob("*")
for fl in all_files:
if (
fl.stem.startswith("power_spectra")
and fl.stem.split("power_spectra_")[-1] in OPTIONS
):
continue
elif (
fl.stem.startswith("perturb_field_data")
and fl.stem.split("perturb_field_data_")[-1] in OPTIONS_PT
):
continue
elif (
fl.stem.startswith("halo_field_data")
and fl.stem.split("halo_field_data_")[-1] in OPTIONS_HALO
):
continue
if qs.confirm(f"Remove {fl}?").ask():
fl.unlink()
if __name__ == "__main__":
main()
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/produce_integration_test_data.py
|
produce_integration_test_data.py
|
"""
Various tests of the initial_conditions() function and InitialConditions class.
"""
import pytest
import numpy as np
from multiprocessing import cpu_count
from py21cmfast import wrapper
def test_box_shape(ic):
"""Test basic properties of the InitialConditions struct"""
shape = (35, 35, 35)
hires_shape = tuple(2 * s for s in shape)
assert ic.lowres_density.shape == shape
assert ic.lowres_vx.shape == shape
assert ic.lowres_vy.shape == shape
assert ic.lowres_vz.shape == shape
assert ic.lowres_vx_2LPT.shape == shape
assert ic.lowres_vy_2LPT.shape == shape
assert ic.lowres_vz_2LPT.shape == shape
assert ic.hires_density.shape == hires_shape
assert ic.hires_vx.shape == hires_shape
assert ic.hires_vy.shape == hires_shape
assert ic.hires_vz.shape == hires_shape
assert ic.hires_vx_2LPT.shape == hires_shape
assert ic.hires_vy_2LPT.shape == hires_shape
assert ic.hires_vz_2LPT.shape == hires_shape
assert not hasattr(ic, "lowres_vcb")
assert ic.cosmo_params == wrapper.CosmoParams()
def test_modified_cosmo(ic):
"""Test using a modified cosmology"""
cosmo = wrapper.CosmoParams(SIGMA_8=0.9)
ic2 = wrapper.initial_conditions(
cosmo_params=cosmo,
user_params=ic.user_params,
)
assert ic2.cosmo_params != ic.cosmo_params
assert ic2.cosmo_params == cosmo
assert ic2.cosmo_params.SIGMA_8 == cosmo.SIGMA_8
def test_transfer_function(ic, default_user_params):
"""Test using a modified transfer function"""
user_params = default_user_params.clone(POWER_SPECTRUM=5)
ic2 = wrapper.initial_conditions(
random_seed=ic.random_seed,
user_params=user_params,
)
rmsnew = np.sqrt(np.mean(ic2.hires_density**2))
rmsdelta = np.sqrt(np.mean((ic2.hires_density - ic.hires_density) ** 2))
assert rmsdelta < rmsnew
assert rmsnew > 0.0
assert not np.allclose(ic2.hires_density, ic.hires_density)
def test_relvels():
"""Test for relative velocity initial conditions"""
ic = wrapper.initial_conditions(
random_seed=1,
user_params=wrapper.UserParams(
HII_DIM=100,
DIM=300,
BOX_LEN=300,
POWER_SPECTRUM=5,
USE_RELATIVE_VELOCITIES=True,
N_THREADS=cpu_count(), # To make this one a bit faster.
),
)
vcbrms_lowres = np.sqrt(np.mean(ic.lowres_vcb**2))
vcbavg_lowres = np.mean(ic.lowres_vcb)
# we test the lowres box
# rms should be about 30 km/s for LCDM, so we check it is finite and not far off
# the average should be 0.92*vrms, since it follows a maxwell boltzmann
assert vcbrms_lowres > 20.0
assert vcbrms_lowres < 40.0
assert vcbavg_lowres < 0.97 * vcbrms_lowres
assert vcbavg_lowres > 0.88 * vcbrms_lowres
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_initial_conditions.py
|
test_initial_conditions.py
|
"""
Testing plots is kind of hard, but we just check that it runs through without crashing.
"""
import pytest
from py21cmfast import plotting
def test_coeval_sliceplot(ic):
fig, ax = plotting.coeval_sliceplot(ic)
assert ax.xaxis.get_label().get_text() == "x-axis [Mpc]"
assert ax.yaxis.get_label().get_text() == "y-axis [Mpc]"
with pytest.raises(ValueError): # bad slice axis
plotting.coeval_sliceplot(ic, slice_axis=-2)
with pytest.raises(IndexError): # tring to plot slice that doesn't exist
plotting.coeval_sliceplot(ic, slice_index=50)
fig2, ax2 = plotting.coeval_sliceplot(ic, fig=fig, ax=ax)
assert fig2 is fig
assert ax2 is ax
fig2, ax2 = plotting.coeval_sliceplot(ic, fig=fig)
assert fig2 is fig
assert ax2 is ax
fig2, ax2 = plotting.coeval_sliceplot(ic, ax=ax)
assert fig2 is fig
assert ax2 is ax
fig, ax = plotting.coeval_sliceplot(
ic, kind="hires_density", slice_index=50, slice_axis=1
)
assert ax.xaxis.get_label().get_text() == "x-axis [Mpc]"
assert ax.yaxis.get_label().get_text() == "z-axis [Mpc]"
def test_lightcone_sliceplot_default(lc):
fig, ax = plotting.lightcone_sliceplot(lc)
assert ax.yaxis.get_label().get_text() == "y-axis [Mpc]"
assert ax.xaxis.get_label().get_text() == "Redshift"
def test_lightcone_sliceplot_vertical(lc):
fig, ax = plotting.lightcone_sliceplot(lc, vertical=True)
assert ax.yaxis.get_label().get_text() == "Redshift"
assert ax.xaxis.get_label().get_text() == "y-axis [Mpc]"
def test_lc_sliceplot_freq(lc):
fig, ax = plotting.lightcone_sliceplot(lc, zticks="frequency")
assert ax.yaxis.get_label().get_text() == "y-axis [Mpc]"
assert ax.xaxis.get_label().get_text() == "Frequency [MHz]"
def test_lc_sliceplot_cdist(lc):
fig, ax = plotting.lightcone_sliceplot(lc, zticks="comoving_distance")
assert ax.yaxis.get_label().get_text() == "y-axis [Mpc]"
assert ax.xaxis.get_label().get_text() == "Comoving Distance [Mpc]"
xlim = ax.get_xticks()
assert xlim.min() >= 0
assert xlim.max() <= lc.lightcone_dimensions[-1]
def test_lc_sliceplot_sliceax(lc):
fig, ax = plotting.lightcone_sliceplot(lc, slice_axis=2)
assert ax.yaxis.get_label().get_text() == "y-axis [Mpc]"
assert ax.xaxis.get_label().get_text() == "x-axis [Mpc]"
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_plotting.py
|
test_plotting.py
|
import pytest
import h5py
import numpy as np
from py21cmfast import (
BrightnessTemp,
Coeval,
InitialConditions,
LightCone,
TsBox,
global_params,
run_coeval,
run_lightcone,
)
@pytest.fixture(scope="module")
def coeval(ic):
return run_coeval(
redshift=25.0, init_box=ic, write=True, flag_options={"USE_TS_FLUCT": True}
)
@pytest.fixture(scope="module")
def lightcone(ic):
return run_lightcone(
max_redshift=35,
redshift=25.0,
init_box=ic,
write=True,
flag_options={"USE_TS_FLUCT": True},
)
def test_lightcone_roundtrip(test_direc, lc):
fname = lc.save(direc=test_direc)
lc2 = LightCone.read(fname)
assert lc == lc2
assert lc.get_unique_filename() == lc2.get_unique_filename()
assert np.all(np.isclose(lc.brightness_temp, lc2.brightness_temp))
def test_lightcone_io_abspath(lc, test_direc):
lc.save(test_direc / "abs_path_lightcone.h5")
assert (test_direc / "abs_path_lightcone.h5").exists()
def test_coeval_roundtrip(test_direc, coeval):
fname = coeval.save(direc=test_direc)
coeval2 = Coeval.read(fname)
assert coeval == coeval2
assert coeval.get_unique_filename() == coeval2.get_unique_filename()
assert np.all(
np.isclose(
coeval.brightness_temp_struct.brightness_temp,
coeval2.brightness_temp_struct.brightness_temp,
)
)
def test_coeval_cache(coeval):
assert coeval.cache_files is not None
out = coeval.get_cached_data(kind="brightness_temp", redshift=25.1, load_data=True)
assert isinstance(out, BrightnessTemp)
assert np.all(out.brightness_temp == coeval.brightness_temp)
out = coeval.get_cached_data(
kind="spin_temp", redshift=global_params.Z_HEAT_MAX * 1.01, load_data=True
)
assert isinstance(out, TsBox)
assert not np.all(out.Ts_box == coeval.Ts_box)
with pytest.raises(ValueError):
coeval.get_cached_data(kind="bad", redshift=100.0)
def test_gather(coeval, test_direc):
fname = coeval.gather(
fname="tmpfile_test_gather.h5",
kinds=("perturb_field", "init"),
direc=str(test_direc),
)
with h5py.File(fname, "r") as fl:
assert "cache" in fl
assert "perturb_field" in fl["cache"]
assert "z25.00" in fl["cache"]["perturb_field"]
assert "density" in fl["cache"]["perturb_field"]["z25.00"]
assert (
fl["cache"]["perturb_field"]["z25.00"]["density"].shape
== (coeval.user_params.HII_DIM,) * 3
)
assert "z0.00" in fl["cache"]["init"]
def test_lightcone_cache(lightcone):
assert lightcone.cache_files is not None
out = lightcone.get_cached_data(
kind="brightness_temp", redshift=25.1, load_data=True
)
assert isinstance(out, BrightnessTemp)
out = lightcone.get_cached_data(
kind="brightness_temp", redshift=global_params.Z_HEAT_MAX * 1.01, load_data=True
)
assert isinstance(out, BrightnessTemp)
assert out.redshift != lightcone.redshift
with pytest.raises(ValueError):
lightcone.get_cached_data(kind="bad", redshift=100.0)
print(lightcone.cache_files)
lightcone.gather(fname="tmp_lightcone_gather.h5", clean=["brightness_temp"])
with pytest.raises(IOError):
lightcone.get_cached_data(kind="brightness_temp", redshift=25.1)
def test_write_to_group(ic, test_direc):
ic.save(test_direc / "a_new_file.h5", h5_group="new_group")
with h5py.File(test_direc / "a_new_file.h5", "r") as fl:
assert "new_group" in fl
assert "global_params" in fl["new_group"]
ic2 = InitialConditions.from_file(
test_direc / "a_new_file.h5", h5_group="new_group"
)
assert ic2 == ic
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_high_level_io.py
|
test_high_level_io.py
|
"""
Tests for the tools in the wrapper.
"""
import pytest
import numpy as np
from py21cmfast import cache_tools
def test_query(ic):
things = list(cache_tools.query_cache())
print(things)
classes = [t[1] for t in things]
assert ic in classes
def test_bad_fname(tmpdirec):
with pytest.raises(ValueError):
cache_tools.readbox(direc=str(tmpdirec), fname="a_really_fake_file.h5")
def test_readbox_data(tmpdirec, ic):
box = cache_tools.readbox(direc=str(tmpdirec), fname=ic.filename)
assert np.all(box.hires_density == ic.hires_density)
def test_readbox_filter(ic, tmpdirec):
ic2 = cache_tools.readbox(
kind="InitialConditions", hsh=ic._md5, direc=str(tmpdirec)
)
assert np.all(ic2.hires_density == ic.hires_density)
def test_readbox_seed(ic, tmpdirec):
ic2 = cache_tools.readbox(
kind="InitialConditions",
hsh=ic._md5,
seed=ic.random_seed,
direc=str(tmpdirec),
)
assert np.all(ic2.hires_density == ic.hires_density)
def test_readbox_nohash(ic, tmpdirec):
with pytest.raises(ValueError):
cache_tools.readbox(
kind="InitialConditions", seed=ic.random_seed, direc=str(tmpdirec)
)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_cache_tools.py
|
test_cache_tools.py
|
"""
A set of large-scale tests which test code updates against previously-run "golden"
results.
The idea here is that any new updates (except for major versions) should be non-breaking;
firstly, they should not break the API, so that the tests should run without crashing without
being changed.
Secondly, the actual results of running the basic functions should remain the same for
the same input code, except for potential bug-fixes. In these cases, these tests should
pick these changes up. The test data should then be changed to reflect the new gold
standard, and if applicable, a new test should be written that reflects the previous
broken code.
Thirdly, it enforces that new features, where possible, are added in such a way as to
keep the default behaviour constant. That is, the tests here should *not* run the added
feature, and therefore should continue to produce the same test results regardless of
the new feature added. The new feature should be accompanied by its own tests, whether
in this or another test module. If a new feature *must* be included by default, then
it must be implemented in a new major version of the code, at which point the test data
is able to be updated.
Comparison tests here are meant to be as small as possible while attempting to form
a reasonable test: they should be of reduced data such as power spectra or global xHI
measurements, and they should be generated with small simulations.
"""
import pytest
import h5py
import logging
import matplotlib as mpl
import numpy as np
from py21cmfast import config, global_params
from . import produce_integration_test_data as prd
logger = logging.getLogger("21cmFAST")
logger.setLevel(logging.INFO)
options = list(prd.OPTIONS.keys())
options_pt = list(prd.OPTIONS_PT.keys())
options_halo = list(prd.OPTIONS_HALO.keys())
@pytest.mark.parametrize("name", options)
def test_power_spectra_coeval(name, module_direc, plt):
redshift, kwargs = prd.OPTIONS[name]
print(f"Options used for the test at z={redshift}: ", kwargs)
# First get pre-made data
with h5py.File(prd.get_filename("power_spectra", name), "r") as fl:
true_powers = {
"_".join(key.split("_")[1:]): value[...]
for key, value in fl["coeval"].items()
if key.startswith("power_")
}
# Now compute the Coeval object
with config.use(direc=module_direc, regenerate=False, write=True):
with global_params.use(zprime_step_factor=prd.DEFAULT_ZPRIME_STEP_FACTOR):
# Note that if zprime_step_factor is set in kwargs, it will over-ride this.
test_k, test_powers, _ = prd.produce_coeval_power_spectra(
redshift, **kwargs
)
if plt == mpl.pyplot:
make_coeval_comparison_plot(test_k, true_powers, test_powers, plt)
for key, value in true_powers.items():
print(f"Testing {key}")
assert np.sum(~np.isclose(value, test_powers[key], atol=0, rtol=1e-2)) < 10
np.testing.assert_allclose(value, test_powers[key], atol=0, rtol=1e-1)
@pytest.mark.parametrize("name", options)
def test_power_spectra_lightcone(name, module_direc, plt):
redshift, kwargs = prd.OPTIONS[name]
print(f"Options used for the test at z={redshift}: ", kwargs)
# First get pre-made data
with h5py.File(prd.get_filename("power_spectra", name), "r") as fl:
true_powers = {}
true_global = {}
for key in fl["lightcone"].keys():
if key.startswith("power_"):
true_powers["_".join(key.split("_")[1:])] = fl["lightcone"][key][...]
elif key.startswith("global_"):
true_global[key] = fl["lightcone"][key][...]
# Now compute the lightcone
with config.use(direc=module_direc, regenerate=False, write=True):
with global_params.use(zprime_step_factor=prd.DEFAULT_ZPRIME_STEP_FACTOR):
# Note that if zprime_step_factor is set in kwargs, it will over-ride this.
test_k, test_powers, lc = prd.produce_lc_power_spectra(redshift, **kwargs)
if plt == mpl.pyplot:
make_lightcone_comparison_plot(
test_k, lc.node_redshifts, true_powers, true_global, test_powers, lc, plt
)
for key, value in true_powers.items():
print(f"Testing {key}")
# Ensure all but 10 of the values is within 1%, and none of the values
# is outside 10%
assert np.sum(~np.isclose(value, test_powers[key], atol=0, rtol=1e-2)) < 10
assert np.allclose(value, test_powers[key], atol=0, rtol=1e-1)
for key, value in true_global.items():
print(f"Testing Global {key}")
assert np.allclose(value, getattr(lc, key), atol=0, rtol=1e-3)
def make_lightcone_comparison_plot(
k, z, true_powers, true_global, test_powers, lc, plt
):
n = len(true_global) + len(true_powers)
fig, ax = plt.subplots(2, n, figsize=(3 * n, 5))
for i, (key, val) in enumerate(true_powers.items()):
make_comparison_plot(
k, val, test_powers[key], ax[:, i], xlab="k", ylab=f"{key} Power"
)
for i, (key, val) in enumerate(true_global.items(), start=i + 1):
make_comparison_plot(
z, val, getattr(lc, key), ax[:, i], xlab="z", ylab=f"{key}"
)
def make_coeval_comparison_plot(k, true_powers, test_powers, plt):
fig, ax = plt.subplots(
2, len(true_powers), figsize=(3 * len(true_powers), 6), sharex=True
)
for i, (key, val) in enumerate(true_powers.items()):
make_comparison_plot(
k, val, test_powers[key], ax[:, i], xlab="k", ylab=f"{key} Power"
)
def make_comparison_plot(x, true, test, ax, logx=True, logy=True, xlab=None, ylab=None):
ax[0].plot(x, true, label="True")
ax[0].plot(x, test, label="Test")
if logx:
ax[0].set_xscale("log")
if logy:
ax[0].set_yscale("log")
if xlab:
ax[0].set_xlabel(xlab)
if ylab:
ax[0].set_ylabel(ylab)
ax[0].legend()
ax[1].plot(x, (test - true) / true)
ax[1].set_ylabel("Fractional Difference")
@pytest.mark.parametrize("name", options_pt)
def test_perturb_field_data(name):
redshift, kwargs = prd.OPTIONS_PT[name]
print("Options used for the test: ", kwargs)
# First get pre-made data
with h5py.File(prd.get_filename("perturb_field_data", name), "r") as f:
power_dens = f["power_dens"][...]
power_vel = f["power_vel"][...]
pdf_dens = f["pdf_dens"][...]
pdf_vel = f["pdf_vel"][...]
with global_params.use(zprime_step_factor=prd.DEFAULT_ZPRIME_STEP_FACTOR):
# Note that if zprime_step_factor is set in kwargs, it will over-ride this.
(
k_dens,
p_dens,
k_vel,
p_vel,
x_dens,
y_dens,
x_vel,
y_vel,
ic,
) = prd.produce_perturb_field_data(redshift, **kwargs)
assert np.allclose(power_dens, p_dens, atol=5e-3, rtol=1e-3)
assert np.allclose(power_vel, p_vel, atol=5e-3, rtol=1e-3)
assert np.allclose(pdf_dens, y_dens, atol=5e-3, rtol=1e-3)
assert np.allclose(pdf_vel, y_vel, atol=5e-3, rtol=1e-3)
@pytest.mark.parametrize("name", options_halo)
def test_halo_field_data(name):
redshift, kwargs = prd.OPTIONS_HALO[name]
print("Options used for the test: ", kwargs)
# First get pre-made data
with h5py.File(prd.get_filename("halo_field_data", name), "r") as f:
n_pt_halos = f["n_pt_halos"][...]
pt_halo_masses = f["pt_halo_masses"][...]
with global_params.use(zprime_step_factor=prd.DEFAULT_ZPRIME_STEP_FACTOR):
# Note that if zprime_step_factor is set in kwargs, it will over-ride this.
pt_halos = prd.produce_halo_field_data(redshift, **kwargs)
assert np.allclose(n_pt_halos, pt_halos.n_halos, atol=5e-3, rtol=1e-3)
assert np.allclose(
np.sum(pt_halo_masses), np.sum(pt_halos.halo_masses), atol=5e-3, rtol=1e-3
)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_integration_features.py
|
test_integration_features.py
|
import py21cmfast as p21c
def test_first_box(default_user_params):
"""Tests whether the first_box idea works for spin_temp.
This test was breaking before we set the z_heat_max box to actually get
the correct dimensions (before it was treated as a dummy).
"""
initial_conditions = p21c.initial_conditions(
user_params=default_user_params.clone(HII_DIM=default_user_params.HII_DIM + 1),
random_seed=1,
)
perturbed_field = p21c.perturb_field(redshift=29.0, init_boxes=initial_conditions)
spin_temp = p21c.spin_temperature(perturbed_field=perturbed_field, z_heat_max=30.0)
assert spin_temp.redshift == 29.0
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_spin_temp.py
|
test_spin_temp.py
|
"""
These are designed to be unit-tests of the wrapper functionality. They do not test for
correctness of simulations,
but whether different parameter options work/don't work as intended.
"""
import pytest
import numpy as np
from py21cmfast import wrapper
@pytest.fixture(scope="module")
def perturb_field_lowz(ic, low_redshift):
"""A default perturb_field"""
return wrapper.perturb_field(redshift=low_redshift, init_boxes=ic, write=True)
@pytest.fixture(scope="module")
def ionize_box(perturb_field):
"""A default ionize_box"""
return wrapper.ionize_box(perturbed_field=perturb_field, write=True)
@pytest.fixture(scope="module")
def ionize_box_lowz(perturb_field_lowz):
"""A default ionize_box at lower redshift."""
return wrapper.ionize_box(perturbed_field=perturb_field_lowz, write=True)
@pytest.fixture(scope="module")
def spin_temp(perturb_field):
"""A default perturb_field"""
return wrapper.spin_temperature(perturbed_field=perturb_field, write=True)
def test_perturb_field_no_ic(default_user_params, redshift, perturb_field):
"""Run a perturb field without passing an init box"""
pf = wrapper.perturb_field(redshift=redshift, user_params=default_user_params)
assert len(pf.density) == pf.user_params.HII_DIM == default_user_params.HII_DIM
assert pf.redshift == redshift
assert pf.random_seed != perturb_field.random_seed
assert not np.all(pf.density == 0)
assert pf != perturb_field
assert pf._seedless_repr() == perturb_field._seedless_repr()
def test_ib_no_z(ic):
with pytest.raises(ValueError):
wrapper.ionize_box(init_boxes=ic)
def test_pf_unnamed_param():
"""Try using an un-named parameter."""
with pytest.raises(TypeError):
wrapper.perturb_field(7)
def test_perturb_field_ic(perturb_field, ic):
# this will run perturb_field again, since by default regenerate=True for tests.
# BUT it should produce exactly the same as the default perturb_field since it has
# the same seed.
pf = wrapper.perturb_field(redshift=perturb_field.redshift, init_boxes=ic)
assert len(pf.density) == len(ic.lowres_density)
assert pf.cosmo_params == ic.cosmo_params
assert pf.user_params == ic.user_params
assert not np.all(pf.density == 0)
assert pf.user_params == perturb_field.user_params
assert pf.cosmo_params == perturb_field.cosmo_params
assert pf == perturb_field
def test_cache_exists(default_user_params, perturb_field, tmpdirec):
pf = wrapper.PerturbedField(
redshift=perturb_field.redshift,
cosmo_params=perturb_field.cosmo_params,
user_params=default_user_params,
)
assert pf.exists(tmpdirec)
pf.read(tmpdirec)
assert np.all(pf.density == perturb_field.density)
assert pf == perturb_field
def test_pf_new_seed(perturb_field, tmpdirec):
pf = wrapper.perturb_field(
redshift=perturb_field.redshift,
user_params=perturb_field.user_params,
random_seed=1,
)
# we didn't write it, and this has a different seed
assert not pf.exists(direc=tmpdirec)
assert pf.random_seed != perturb_field.random_seed
assert not np.all(pf.density == perturb_field.density)
def test_ib_new_seed(ionize_box_lowz, perturb_field_lowz, tmpdirec):
# this should fail because perturb_field has a seed set already, which isn't 1.
with pytest.raises(ValueError):
wrapper.ionize_box(
perturbed_field=perturb_field_lowz,
random_seed=1,
)
ib = wrapper.ionize_box(
cosmo_params=perturb_field_lowz.cosmo_params,
redshift=perturb_field_lowz.redshift,
user_params=perturb_field_lowz.user_params,
random_seed=1,
)
# we didn't write it, and this has a different seed
assert not ib.exists(direc=tmpdirec)
assert ib.random_seed != ionize_box_lowz.random_seed
assert not np.all(ib.xH_box == ionize_box_lowz.xH_box)
def test_st_new_seed(spin_temp, perturb_field, tmpdirec):
# this should fail because perturb_field has a seed set already, which isn't 1.
with pytest.raises(ValueError):
wrapper.spin_temperature(
perturbed_field=perturb_field,
random_seed=1,
)
st = wrapper.spin_temperature(
cosmo_params=spin_temp.cosmo_params,
user_params=spin_temp.user_params,
astro_params=spin_temp.astro_params,
flag_options=spin_temp.flag_options,
redshift=spin_temp.redshift,
random_seed=1,
)
# we didn't write it, and this has a different seed
assert not st.exists(direc=tmpdirec)
assert st.random_seed != spin_temp.random_seed
assert not np.all(st.Ts_box == spin_temp.Ts_box)
def test_st_from_z(perturb_field_lowz, spin_temp):
# This one has all the same parameters as the nominal spin_temp, but is evaluated
# with an interpolated perturb_field
st = wrapper.spin_temperature(
perturbed_field=perturb_field_lowz,
astro_params=spin_temp.astro_params,
flag_options=spin_temp.flag_options,
redshift=spin_temp.redshift, # Higher redshift
)
assert st != spin_temp
assert not np.all(st.Ts_box == spin_temp.Ts_box)
def test_ib_from_pf(perturb_field):
ib = wrapper.ionize_box(perturbed_field=perturb_field)
assert ib.redshift == perturb_field.redshift
assert ib.user_params == perturb_field.user_params
assert ib.cosmo_params == perturb_field.cosmo_params
def test_ib_from_z(default_user_params, perturb_field):
ib = wrapper.ionize_box(
redshift=perturb_field.redshift,
user_params=default_user_params,
regenerate=False,
)
assert ib.redshift == perturb_field.redshift
assert ib.user_params == perturb_field.user_params
assert ib.cosmo_params == perturb_field.cosmo_params
assert ib.cosmo_params is not perturb_field.cosmo_params
def test_ib_override_z(perturb_field):
with pytest.raises(ValueError):
wrapper.ionize_box(
redshift=perturb_field.redshift + 1,
perturbed_field=perturb_field,
)
def test_ib_override_z_heat_max(perturb_field):
# save previous z_heat_max
zheatmax = wrapper.global_params.Z_HEAT_MAX
wrapper.ionize_box(
redshift=perturb_field.redshift,
perturbed_field=perturb_field,
z_heat_max=12.0,
)
assert wrapper.global_params.Z_HEAT_MAX == zheatmax
def test_ib_bad_st(ic, redshift):
with pytest.raises(ValueError):
wrapper.ionize_box(redshift=redshift, spin_temp=ic)
def test_bt(ionize_box, spin_temp, perturb_field):
with pytest.raises(TypeError): # have to specify param names
wrapper.brightness_temperature(ionize_box, spin_temp, perturb_field)
# this will fail because ionized_box was not created with spin temperature.
with pytest.raises(ValueError):
wrapper.brightness_temperature(
ionized_box=ionize_box, perturbed_field=perturb_field, spin_temp=spin_temp
)
bt = wrapper.brightness_temperature(
ionized_box=ionize_box, perturbed_field=perturb_field
)
assert bt.cosmo_params == perturb_field.cosmo_params
assert bt.user_params == perturb_field.user_params
assert bt.flag_options == ionize_box.flag_options
assert bt.astro_params == ionize_box.astro_params
def test_coeval_against_direct(ic, perturb_field, ionize_box):
coeval = wrapper.run_coeval(perturb=perturb_field, init_box=ic)
assert coeval.init_struct == ic
assert coeval.perturb_struct == perturb_field
assert coeval.ionization_struct == ionize_box
def test_lightcone(lc, default_user_params, redshift, max_redshift):
assert lc.lightcone_redshifts[-1] >= max_redshift
assert np.isclose(lc.lightcone_redshifts[0], redshift, atol=1e-4)
assert lc.cell_size == default_user_params.BOX_LEN / default_user_params.HII_DIM
def test_lightcone_quantities(ic, max_redshift, perturb_field):
lc = wrapper.run_lightcone(
init_box=ic,
perturb=perturb_field,
max_redshift=max_redshift,
lightcone_quantities=("dNrec_box", "density", "brightness_temp"),
global_quantities=("density", "Gamma12_box"),
)
assert hasattr(lc, "dNrec_box")
assert hasattr(lc, "density")
assert hasattr(lc, "global_density")
assert hasattr(lc, "global_Gamma12")
# dNrec is not filled because we're not doing INHOMO_RECO
assert lc.dNrec_box.max() == lc.dNrec_box.min() == 0
# density should be filled with not zeros.
assert lc.density.min() != lc.density.max() != 0
# Simply ensure that different quantities are not getting crossed/referred to each other.
assert lc.density.min() != lc.brightness_temp.min() != lc.brightness_temp.max()
# Raise an error since we're not doing spin temp.
with pytest.raises(ValueError):
wrapper.run_lightcone(
init_box=ic,
perturb=perturb_field,
max_redshift=20.0,
lightcone_quantities=("Ts_box", "density"),
)
# And also raise an error for global quantities.
with pytest.raises(ValueError):
wrapper.run_lightcone(
init_box=ic,
perturb=perturb_field,
max_redshift=20.0,
global_quantities=("Ts_box",),
)
def test_run_lf():
muv, mhalo, lf = wrapper.compute_luminosity_function(redshifts=[7, 8, 9], nbins=100)
assert np.all(lf[~np.isnan(lf)] > -30)
assert lf.shape == (3, 100)
# Check that memory is in-tact and a second run also works:
muv, mhalo, lf2 = wrapper.compute_luminosity_function(
redshifts=[7, 8, 9], nbins=100
)
assert lf2.shape == (3, 100)
assert np.allclose(lf2[~np.isnan(lf2)], lf[~np.isnan(lf)])
muv_minih, mhalo_minih, lf_minih = wrapper.compute_luminosity_function(
redshifts=[7, 8, 9],
nbins=100,
component=0,
flag_options={"USE_MINI_HALOS": True},
mturnovers=[7.0, 7.0, 7.0],
mturnovers_mini=[5.0, 5.0, 5.0],
)
assert np.all(lf_minih[~np.isnan(lf_minih)] > -30)
assert lf_minih.shape == (3, 100)
def test_coeval_st(ic, perturb_field):
coeval = wrapper.run_coeval(
init_box=ic,
perturb=perturb_field,
flag_options={"USE_TS_FLUCT": True},
)
assert isinstance(coeval.spin_temp_struct, wrapper.TsBox)
def _global_Tb(coeval_box):
assert isinstance(coeval_box, wrapper.Coeval)
global_Tb = coeval_box.brightness_temp.mean(dtype=np.float64).astype(np.float32)
assert np.isclose(global_Tb, coeval_box.brightness_temp_struct.global_Tb)
return global_Tb
def test_coeval_callback(ic, max_redshift, perturb_field):
lc, coeval_output = wrapper.run_lightcone(
init_box=ic,
perturb=perturb_field,
max_redshift=max_redshift,
lightcone_quantities=("brightness_temp",),
global_quantities=("brightness_temp",),
coeval_callback=_global_Tb,
)
assert isinstance(lc, wrapper.LightCone)
assert isinstance(coeval_output, list)
assert len(lc.node_redshifts) == len(coeval_output)
assert np.allclose(
lc.global_brightness_temp, np.array(coeval_output, dtype=np.float32)
)
def test_coeval_callback_redshifts(ic, redshift, max_redshift, perturb_field):
coeval_callback_redshifts = np.array(
[max_redshift, max_redshift, (redshift + max_redshift) / 2, redshift],
dtype=np.float32,
)
lc, coeval_output = wrapper.run_lightcone(
init_box=ic,
perturb=perturb_field,
max_redshift=max_redshift,
coeval_callback=lambda x: x.redshift,
coeval_callback_redshifts=coeval_callback_redshifts,
)
assert len(coeval_callback_redshifts) - 1 == len(coeval_output)
computed_redshifts = [
lc.node_redshifts[np.argmin(np.abs(i - lc.node_redshifts))]
for i in coeval_callback_redshifts[1:]
]
assert np.allclose(coeval_output, computed_redshifts)
def Heaviside(x):
return 1 if x > 0 else 0
def test_coeval_callback_exceptions(ic, redshift, max_redshift, perturb_field):
# should output warning in logs and not raise an error
lc, coeval_output = wrapper.run_lightcone(
init_box=ic,
perturb=perturb_field,
max_redshift=max_redshift,
coeval_callback=lambda x: 1
/ Heaviside(x.redshift - (redshift + max_redshift) / 2),
coeval_callback_redshifts=[max_redshift, redshift],
)
# should raise an error
with pytest.raises(RuntimeError) as excinfo:
lc, coeval_output = wrapper.run_lightcone(
init_box=ic,
perturb=perturb_field,
max_redshift=max_redshift,
coeval_callback=lambda x: 1 / 0,
coeval_callback_redshifts=[max_redshift, redshift],
)
assert "coeval_callback computation failed on first trial" in str(excinfo.value)
def test_coeval_vs_low_level(ic):
coeval = wrapper.run_coeval(
redshift=20,
init_box=ic,
zprime_step_factor=1.1,
regenerate=True,
flag_options={"USE_TS_FLUCT": True},
write=False,
)
st = wrapper.spin_temperature(
redshift=20,
init_boxes=ic,
zprime_step_factor=1.1,
regenerate=True,
flag_options={"USE_TS_FLUCT": True},
write=False,
)
np.testing.assert_allclose(coeval.Tk_box, st.Tk_box, rtol=1e-4, atol=1e-4)
np.testing.assert_allclose(coeval.Ts_box, st.Ts_box, rtol=1e-4, atol=1e-4)
np.testing.assert_allclose(coeval.x_e_box, st.x_e_box, rtol=1e-4, atol=1e-4)
def test_using_cached_halo_field(ic, test_direc):
"""Test whether the C-based memory in halo fields is cached correctly.
Prior to v3.1 this was segfaulting, so this test ensure that this behaviour does
not regress.
"""
halo_field = wrapper.determine_halo_list(
redshift=10.0,
init_boxes=ic,
write=True,
direc=test_direc,
)
pt_halos = wrapper.perturb_halo_list(
redshift=10.0,
init_boxes=ic,
halo_field=halo_field,
write=True,
direc=test_direc,
)
print("DONE WITH FIRST BOXES!")
# Now get the halo field again at the same redshift -- should be cached
new_halo_field = wrapper.determine_halo_list(
redshift=10.0, init_boxes=ic, write=False, regenerate=False
)
new_pt_halos = wrapper.perturb_halo_list(
redshift=10.0,
init_boxes=ic,
halo_field=new_halo_field,
write=False,
regenerate=False,
)
np.testing.assert_allclose(new_halo_field.halo_masses, halo_field.halo_masses)
np.testing.assert_allclose(pt_halos.halo_coords, new_pt_halos.halo_coords)
|
21cmFAST
|
/21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_wrapper.py
|
test_wrapper.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.