or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

file-operations.mdheader-operations.mdimage-operations.mdindex.mdtable-operations.md

header-operations.mddocs/

0

# Header Operations

1

2

FITS header manipulation functionality providing complete control over header keywords, comments, metadata, and FITS header formatting. Supports reading, writing, and modifying headers with proper FITS standards compliance.

3

4

## Capabilities

5

6

### FITSHDR Class

7

8

Container for FITS header records with dictionary-like interface and complete header management capabilities.

9

10

```python { .api }

11

class FITSHDR:

12

def __init__(self, record_list=None):

13

"""

14

Create FITS header object.

15

16

Parameters:

17

- record_list: list/dict/FITSHDR, initial header records

18

- list of dicts with 'name', 'value', 'comment' keys

19

- dict of keyword-value pairs (no comments)

20

- another FITSHDR object

21

"""

22

23

def add_record(self, record):

24

"""

25

Add header record.

26

27

Parameters:

28

- record: dict/str/FITSRecord, header record

29

- dict with 'name', 'value', 'comment' keys

30

- FITS card string

31

- FITSRecord object

32

"""

33

34

def get_comment(self, keyword):

35

"""

36

Get comment for keyword.

37

38

Parameters:

39

- keyword: str, header keyword name

40

41

Returns:

42

str, comment text

43

"""

44

45

def records(self):

46

"""

47

Get all header records.

48

49

Returns:

50

list of dicts with 'name', 'value', 'comment' keys

51

"""

52

53

def keys(self):

54

"""

55

Get all keyword names.

56

57

Returns:

58

list of str, keyword names

59

"""

60

61

def delete(self, name):

62

"""

63

Delete keyword(s).

64

65

Parameters:

66

- name: str, keyword name to delete

67

"""

68

69

def clean(self, is_table=False):

70

"""

71

Remove reserved keywords.

72

73

Parameters:

74

- is_table: bool, whether this is table header

75

"""

76

77

def get(self, keyword, default=None):

78

"""

79

Get keyword value with default.

80

81

Parameters:

82

- keyword: str, keyword name

83

- default: any, default value if keyword not found

84

85

Returns:

86

Keyword value or default

87

"""

88

89

def __setitem__(self, key, value):

90

"""Set keyword value."""

91

92

def __getitem__(self, key):

93

"""Get keyword value."""

94

95

def __contains__(self, key):

96

"""Check if keyword exists."""

97

98

def __len__(self):

99

"""Number of keywords."""

100

101

def __iter__(self):

102

"""Iterate over keyword names."""

103

```

104

105

### FITSRecord Class

106

107

Individual FITS header record with name, value, and comment.

108

109

```python { .api }

110

class FITSRecord:

111

def __init__(self, record):

112

"""

113

Create FITS record.

114

115

Parameters:

116

- record: dict/str, record data

117

- dict with 'name', 'value', 'comment' keys

118

- FITS card string

119

"""

120

```

121

122

### FITSCard Class

123

124

Parser for FITS header card strings (80-character FITS format).

125

126

```python { .api }

127

class FITSCard:

128

def __init__(self, card_string):

129

"""

130

Parse FITS card string.

131

132

Parameters:

133

- card_string: str, 80-character FITS card

134

"""

135

```

136

137

### HDU Header Operations

138

139

Header operations available on HDU objects for reading and writing keywords.

140

141

```python { .api }

142

class HDUBase:

143

def read_header(self):

144

"""

145

Read header as FITSHDR object.

146

147

Returns:

148

FITSHDR object

149

"""

150

151

def read_header_list(self):

152

"""

153

Read header as list of dicts.

154

155

Returns:

156

list of dicts with 'name', 'value', 'comment' keys

157

"""

158

159

def write_key(self, name, value, comment=""):

160

"""

161

Write single header keyword.

162

163

Parameters:

164

- name: str, keyword name (max 8 characters)

165

- value: any, keyword value

166

- comment: str, keyword comment

167

"""

168

169

def write_keys(self, records, clean=True):

170

"""

171

Write multiple header keywords.

172

173

Parameters:

174

- records: list/dict/FITSHDR, header records

175

- clean: bool, remove reserved keywords first

176

"""

177

178

def write_comment(self, comment):

179

"""

180

Write COMMENT record.

181

182

Parameters:

183

- comment: str, comment text

184

"""

185

186

def write_history(self, history):

187

"""

188

Write HISTORY record.

189

190

Parameters:

191

- history: str, history text

192

"""

193

```

194

195

## Header Key Type Constants

196

197

```python { .api }

198

TYP_STRUC_KEY = 10 # Structural keywords

199

TYP_CMPRS_KEY = 20 # Compression keywords

200

TYP_SCAL_KEY = 30 # Scaling keywords

201

TYP_NULL_KEY = 40 # Null value keywords

202

TYP_DIM_KEY = 50 # Dimension keywords

203

TYP_RANG_KEY = 60 # Range keywords

204

TYP_UNIT_KEY = 70 # Unit keywords

205

TYP_DISP_KEY = 80 # Display keywords

206

TYP_HDUID_KEY = 90 # HDU ID keywords

207

TYP_CKSUM_KEY = 100 # Checksum keywords

208

TYP_WCS_KEY = 110 # WCS keywords

209

TYP_REFSYS_KEY = 120 # Reference system keywords

210

TYP_COMM_KEY = 130 # Comment keywords

211

TYP_CONT_KEY = 140 # Continued keywords

212

TYP_USER_KEY = 150 # User keywords

213

```

214

215

## Usage Examples

216

217

### Creating and Modifying Headers

218

219

```python

220

import fitsio

221

222

# Create empty header

223

hdr = fitsio.FITSHDR()

224

225

# Add simple keyword

226

hdr['OBJECT'] = 'NGC 1234'

227

228

# Add keyword with comment

229

hdr.add_record({'name': 'EXPTIME', 'value': 300.0, 'comment': 'Exposure time in seconds'})

230

231

# Add from card string

232

hdr.add_record('FILTER = "V " / Filter used')

233

234

# Create header from list

235

records = [

236

{'name': 'TELESCOP', 'value': 'HST', 'comment': 'Telescope'},

237

{'name': 'INSTRUME', 'value': 'ACS', 'comment': 'Instrument'}

238

]

239

hdr = fitsio.FITSHDR(records)

240

241

# Create from dictionary (no comments)

242

simple_hdr = fitsio.FITSHDR({'NAXIS': 2, 'NAXIS1': 100, 'NAXIS2': 100})

243

```

244

245

### Reading Headers

246

247

```python

248

import fitsio

249

250

# Read header with convenience function

251

header = fitsio.read_header('data.fits', ext=0)

252

253

# Access keyword values

254

print(f"Object: {header['OBJECT']}")

255

print(f"Exposure time: {header.get('EXPTIME', 'Unknown')}")

256

257

# Get comment

258

comment = header.get_comment('EXPTIME')

259

260

# Iterate over keywords

261

for keyword in header:

262

value = header[keyword]

263

comment = header.get_comment(keyword)

264

print(f"{keyword} = {value} / {comment}")

265

266

# Get all records

267

all_records = header.records()

268

```

269

270

### Writing Headers

271

272

```python

273

import fitsio

274

import numpy as np

275

276

# Write data with header

277

image = np.random.random((100, 100))

278

header = fitsio.FITSHDR([

279

{'name': 'OBJECT', 'value': 'Test Image', 'comment': 'Object name'},

280

{'name': 'EXPTIME', 'value': 600.0, 'comment': 'Exposure time'},

281

{'name': 'FILTER', 'value': 'R', 'comment': 'Filter name'}

282

])

283

284

fitsio.write('output.fits', image, header=header)

285

286

# Modify existing header

287

with fitsio.FITS('data.fits', 'rw') as fits:

288

# Write individual keywords

289

fits[0].write_key('OBSERVER', 'John Doe', 'Observer name')

290

fits[0].write_key('DATE-OBS', '2023-01-15', 'Observation date')

291

292

# Write multiple keywords

293

new_keys = [

294

{'name': 'AIRMASS', 'value': 1.2, 'comment': 'Airmass'},

295

{'name': 'SEEING', 'value': 0.8, 'comment': 'Seeing in arcsec'}

296

]

297

fits[0].write_keys(new_keys)

298

299

# Write comments and history

300

fits[0].write_comment('This is a comment')

301

fits[0].write_history('Processed with custom pipeline')

302

```

303

304

### Advanced Header Operations

305

306

```python

307

import fitsio

308

309

# Work with complex headers

310

with fitsio.FITS('data.fits') as fits:

311

hdr = fits[0].read_header()

312

313

# Check if keywords exist

314

if 'BSCALE' in hdr:

315

scale = hdr['BSCALE']

316

zero = hdr.get('BZERO', 0.0)

317

318

# Clean reserved keywords

319

hdr.clean(is_table=False)

320

321

# Get keyword list

322

keywords = hdr.keys()

323

print(f"Header has {len(keywords)} keywords")

324

325

# Delete unwanted keywords

326

for key in ['COMMENT', 'HISTORY']:

327

if key in hdr:

328

hdr.delete(key)

329

330

# Parse FITS cards manually

331

card = fitsio.FITSCard("EXPTIME = 600.0 / Exposure time in seconds")

332

record = fitsio.FITSRecord(card)

333

334

# Convert between formats

335

header_dict = {'NAXIS': 2, 'NAXIS1': 1024, 'NAXIS2': 1024}

336

hdr = fitsio.FITSHDR(header_dict)

337

record_list = hdr.records()

338

```

339

340

### Working with Special Keywords

341

342

```python

343

import fitsio

344

345

with fitsio.FITS('data.fits', 'rw') as fits:

346

# Handle long string values (continued keywords)

347

long_comment = "This is a very long comment that exceeds the normal FITS card length and will be automatically split across multiple cards"

348

fits[0].write_key('LONGCMT', long_comment)

349

350

# Handle special characters

351

fits[0].write_key('FILENAME', "file's name with quotes", "File's original name")

352

353

# Preserve data types

354

fits[0].write_key('INTVAL', 42) # Integer

355

fits[0].write_key('FLOATVAL', 3.14159) # Float

356

fits[0].write_key('BOOLVAL', True) # Boolean

357

fits[0].write_key('STRVAL', 'text') # String

358

```