or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

coordinate-systems.mdfitting-operations.mdfunctionals.mdimage-processing.mdindex.mdquantities-units.mdtable-operations.md

quantities-units.mddocs/

0

# Quantities and Units

1

2

Physical quantities with units, unit conversions, and astronomical constants. Supports scalar and vector quantities with comprehensive unit system including SI, astronomical, and specialized radio astronomy units, enabling precise calculations with automatic unit checking and conversion.

3

4

## Core Imports

5

6

```python

7

from casacore.quanta import quantity, is_quantity

8

from casacore.quanta import constants, units, prefixes

9

```

10

11

## Capabilities

12

13

### Quantity Creation

14

15

Create scalar and vector quantities with units from various input formats.

16

17

```python { .api }

18

def quantity(*args):

19

"""

20

Create a quantity with units.

21

22

Parameters:

23

Single argument:

24

- str: Parse string like "1.5km/s", "10.3MHz", "45deg"

25

- dict: Quantity dictionary with 'value' and 'unit' keys

26

- Quantity/QuantVec: Copy existing quantity

27

28

Two arguments:

29

- value, unit: Numeric value(s) and unit string

30

31

Returns:

32

Quantity (scalar) or QuantVec (vector) object

33

34

Examples:

35

quantity(1.0, "km/s") # Scalar quantity

36

quantity("1.5km/s") # From string

37

quantity([1.0, 2.0], "km/s") # Vector quantity

38

quantity({'value': 1.5, 'unit': 'km/s'}) # From dictionary

39

"""

40

41

def is_quantity(q):

42

"""

43

Check if object is a valid quantity.

44

45

Parameters:

46

- q: object to check

47

48

Returns:

49

bool, True if q is Quantity or QuantVec

50

"""

51

```

52

53

### Scalar Quantities

54

55

Handle single-valued quantities with units and mathematical operations.

56

57

```python { .api }

58

class Quantity:

59

def __init__(self, value, unit):

60

"""

61

Create scalar quantity.

62

63

Parameters:

64

- value: float, numeric value

65

- unit: str, unit specification

66

"""

67

68

def get_value(self):

69

"""

70

Get numeric value.

71

72

Returns:

73

float, numeric value without units

74

"""

75

76

def get_unit(self):

77

"""

78

Get unit string.

79

80

Returns:

81

str, unit specification

82

"""

83

84

def to_string(self, fmt="%0.5g"):

85

"""

86

Format quantity as string.

87

88

Parameters:

89

- fmt: str, format specification

90

91

Returns:

92

str, formatted quantity with units

93

"""

94

95

def convert(self, unit):

96

"""

97

Convert to different unit.

98

99

Parameters:

100

- unit: str, target unit

101

102

Returns:

103

Quantity, converted quantity

104

105

Raises:

106

RuntimeError if units are incompatible

107

"""

108

109

def conforms(self, other):

110

"""

111

Check unit compatibility.

112

113

Parameters:

114

- other: Quantity or str, quantity or unit to check

115

116

Returns:

117

bool, True if units are compatible

118

"""

119

120

def canonical(self):

121

"""

122

Convert to canonical (SI base) units.

123

124

Returns:

125

Quantity, quantity in canonical units

126

"""

127

128

def to_dict(self):

129

"""

130

Convert to dictionary representation.

131

132

Returns:

133

dict with 'value' and 'unit' keys

134

"""

135

136

def norm(self, phase=0.0):

137

"""

138

Normalize angle to [0, 2π) range.

139

140

Parameters:

141

- phase: float, phase offset (default 0.0)

142

143

Returns:

144

Quantity, normalized angle

145

"""

146

147

def sin(self):

148

"""Calculate sine of angle quantity."""

149

150

def cos(self):

151

"""Calculate cosine of angle quantity."""

152

153

def tan(self):

154

"""Calculate tangent of angle quantity."""

155

156

def asin(self):

157

"""Calculate arcsine, returns angle quantity."""

158

159

def acos(self):

160

"""Calculate arccosine, returns angle quantity."""

161

162

def atan(self):

163

"""Calculate arctangent, returns angle quantity."""

164

165

def atan2(self, x):

166

"""

167

Calculate two-argument arctangent.

168

169

Parameters:

170

- x: Quantity, x-coordinate

171

172

Returns:

173

Quantity, angle from +x axis to (x,y) point

174

"""

175

176

def sqrt(self):

177

"""Calculate square root."""

178

179

def log(self):

180

"""Calculate natural logarithm."""

181

182

def log10(self):

183

"""Calculate base-10 logarithm."""

184

185

def exp(self):

186

"""Calculate exponential."""

187

188

def pow(self, exponent):

189

"""

190

Raise to power.

191

192

Parameters:

193

- exponent: float, exponent value

194

195

Returns:

196

Quantity, result with appropriate units

197

"""

198

```

199

200

### Vector Quantities

201

202

Handle array-valued quantities with units and vectorized operations.

203

204

```python { .api }

205

class QuantVec:

206

def __init__(self, value, unit):

207

"""

208

Create vector quantity.

209

210

Parameters:

211

- value: list or numpy array, numeric values

212

- unit: str, unit specification

213

"""

214

215

def get_value(self):

216

"""

217

Get numeric array.

218

219

Returns:

220

numpy array, numeric values without units

221

"""

222

223

def get_unit(self):

224

"""

225

Get unit string.

226

227

Returns:

228

str, unit specification

229

"""

230

231

def to_string(self, fmt="%0.5g"):

232

"""

233

Format vector quantity as string.

234

235

Parameters:

236

- fmt: str, format specification for each element

237

238

Returns:

239

str, formatted vector with units

240

"""

241

242

def convert(self, unit):

243

"""

244

Convert to different unit.

245

246

Parameters:

247

- unit: str, target unit

248

249

Returns:

250

QuantVec, converted vector quantity

251

"""

252

253

def conforms(self, other):

254

"""

255

Check unit compatibility.

256

257

Parameters:

258

- other: QuantVec, Quantity, or str

259

260

Returns:

261

bool, True if units are compatible

262

"""

263

264

def canonical(self):

265

"""

266

Convert to canonical (SI base) units.

267

268

Returns:

269

QuantVec, vector in canonical units

270

"""

271

272

def to_dict(self):

273

"""

274

Convert to dictionary representation.

275

276

Returns:

277

dict with 'value' (list) and 'unit' keys

278

"""

279

280

def __len__(self):

281

"""Get number of elements."""

282

283

def __getitem__(self, index):

284

"""

285

Get element at index.

286

287

Parameters:

288

- index: int or slice, element index

289

290

Returns:

291

Quantity (single element) or QuantVec (slice)

292

"""

293

294

def __setitem__(self, index, value):

295

"""

296

Set element at index.

297

298

Parameters:

299

- index: int or slice, element index

300

- value: Quantity or numeric value

301

"""

302

```

303

304

### Mathematical Operations

305

306

Quantities support standard mathematical operations with automatic unit handling.

307

308

```python { .api }

309

# Arithmetic operations (available for both Quantity and QuantVec)

310

def __add__(self, other):

311

"""Add quantities (requires compatible units)."""

312

313

def __sub__(self, other):

314

"""Subtract quantities (requires compatible units)."""

315

316

def __mul__(self, other):

317

"""Multiply quantities (units multiply)."""

318

319

def __truediv__(self, other):

320

"""Divide quantities (units divide)."""

321

322

def __pow__(self, exponent):

323

"""Raise to power (units raised to same power)."""

324

325

def __neg__(self):

326

"""Negate quantity."""

327

328

def __abs__(self):

329

"""Absolute value of quantity."""

330

331

# Comparison operations

332

def __eq__(self, other):

333

"""Test equality (requires compatible units)."""

334

335

def __ne__(self, other):

336

"""Test inequality."""

337

338

def __lt__(self, other):

339

"""Less than comparison."""

340

341

def __le__(self, other):

342

"""Less than or equal comparison."""

343

344

def __gt__(self, other):

345

"""Greater than comparison."""

346

347

def __ge__(self, other):

348

"""Greater than or equal comparison."""

349

```

350

351

### Physical Constants

352

353

Access fundamental physical constants with proper units.

354

355

```python { .api }

356

# Constants object provides physical constants

357

constants = {

358

# Fundamental constants

359

'c': quantity, # Speed of light in vacuum

360

'h': quantity, # Planck constant

361

'k': quantity, # Boltzmann constant

362

'G': quantity, # Gravitational constant

363

'e': quantity, # Elementary charge

364

'me': quantity, # Electron mass

365

'mp': quantity, # Proton mass

366

'mn': quantity, # Neutron mass

367

'mu0': quantity, # Permeability of free space

368

'eps0': quantity, # Permittivity of free space

369

'R': quantity, # Gas constant

370

'NA': quantity, # Avogadro number

371

'alpha': quantity, # Fine structure constant

372

373

# Astronomical constants

374

'pc': quantity, # Parsec

375

'ly': quantity, # Light year

376

'AU': quantity, # Astronomical unit

377

'R_earth': quantity, # Earth radius

378

'M_earth': quantity, # Earth mass

379

'R_sun': quantity, # Solar radius

380

'M_sun': quantity, # Solar mass

381

'L_sun': quantity, # Solar luminosity

382

383

# Spectroscopic constants

384

'HI': quantity, # 21cm hydrogen line frequency

385

'OH1612': quantity, # OH maser line

386

'OH1665': quantity, # OH maser line

387

'OH1667': quantity, # OH maser line

388

'OH1720': quantity, # OH maser line

389

}

390

391

def constants():

392

"""

393

Get constants object.

394

395

Returns:

396

dict-like object with physical constants

397

398

Usage:

399

c_light = constants['c']

400

hi_freq = constants['HI']

401

"""

402

```

403

404

### Unit System

405

406

Comprehensive unit definitions and conversion factors.

407

408

```python { .api }

409

# Units object provides unit definitions

410

def units():

411

"""

412

Get units object with conversion factors.

413

414

Returns:

415

dict-like object with unit definitions

416

417

Unit categories:

418

- Length: m, km, cm, mm, nm, pm, in, ft, mi, AU, pc, ly

419

- Time: s, min, h, d, yr, century

420

- Mass: kg, g, lb, oz, M_sun, M_earth

421

- Angle: rad, deg, arcmin, arcsec, mas, microas

422

- Frequency: Hz, kHz, MHz, GHz, THz

423

- Energy: J, eV, keV, MeV, GeV, erg, cal

424

- Power: W, kW, MW, GW, erg/s, L_sun

425

- Temperature: K, Celsius, Fahrenheit

426

- Pressure: Pa, bar, atm, Torr, psi

427

- Velocity: m/s, km/s, km/h, mph, c

428

- Acceleration: m/s2, g_earth

429

- Force: N, dyne, lbf

430

- Electric: A, V, Ohm, C, F, H

431

- Magnetic: T, G, Wb, Mx

432

"""

433

434

# Prefixes object provides SI prefixes

435

def prefixes():

436

"""

437

Get prefixes object.

438

439

Returns:

440

dict-like object with SI prefixes

441

442

Prefixes: y, z, a, f, p, n, u, m, c, d, da, h, k, M, G, T, P, E, Z, Y

443

"""

444

```

445

446

### Unit Parsing and Formatting

447

448

Advanced unit string parsing and formatting capabilities.

449

450

```python { .api }

451

# String parsing functions (used internally by quantity())

452

def from_string(s):

453

"""

454

Parse quantity from string.

455

456

Parameters:

457

- s: str, quantity string like "1.5km/s", "45deg", "1.42GHz"

458

459

Returns:

460

dict with parsed value and unit

461

462

Supported formats:

463

- "value unit" (e.g., "1.5 km/s")

464

- "valueunit" (e.g., "1.5km/s")

465

- Scientific notation (e.g., "1.5e-3m")

466

- Fractions (e.g., "1/2 deg")

467

- Compound units (e.g., "m/s2", "kg.m/s2")

468

- Time formats (e.g., "12h30m15s", "2023-01-01/12:00:00")

469

- Angle formats (e.g., "12h30m15s", "45d30m15s", "45:30:15")

470

"""

471

472

def from_dict(d):

473

"""

474

Create quantity from dictionary.

475

476

Parameters:

477

- d: dict with 'value' and 'unit' keys

478

479

Returns:

480

Quantity object

481

"""

482

483

def from_dict_v(d):

484

"""

485

Create vector quantity from dictionary.

486

487

Parameters:

488

- d: dict with 'value' (list) and 'unit' keys

489

490

Returns:

491

QuantVec object

492

"""

493

```

494

495

## Usage Examples

496

497

### Basic Quantity Operations

498

499

```python

500

from casacore.quanta import quantity, is_quantity, constants

501

502

# Create quantities different ways

503

freq1 = quantity(1.42, 'GHz')

504

freq2 = quantity('1420.405MHz') # HI line frequency

505

distance = quantity([1.0, 2.5, 10.0], 'kpc')

506

507

print(f"Frequency 1: {freq1}")

508

print(f"Frequency 2: {freq2}")

509

print(f"Distances: {distance}")

510

511

# Check if object is quantity

512

print(f"freq1 is quantity: {is_quantity(freq1)}")

513

514

# Unit conversions

515

freq1_mhz = freq1.convert('MHz')

516

print(f"Frequency in MHz: {freq1_mhz}")

517

518

# Check unit compatibility

519

print(f"freq1 compatible with MHz: {freq1.conforms('MHz')}")

520

print(f"freq1 compatible with km/s: {freq1.conforms('km/s')}")

521

```

522

523

### Mathematical Operations

524

525

```python

526

# Arithmetic with automatic unit handling

527

velocity = quantity(100, 'km/s')

528

time = quantity(1, 'yr')

529

530

# Distance = velocity × time

531

distance = velocity * time

532

print(f"Distance traveled: {distance}")

533

print(f"Distance in parsecs: {distance.convert('pc')}")

534

535

# Wavelength from frequency

536

c = constants['c'] # Speed of light

537

freq = quantity('1.42GHz')

538

wavelength = c / freq

539

print(f"Wavelength: {wavelength}")

540

print(f"Wavelength in cm: {wavelength.convert('cm')}")

541

542

# Angular calculations

543

angle1 = quantity('45deg')

544

angle2 = quantity('30deg')

545

total_angle = angle1 + angle2

546

print(f"Total angle: {total_angle}")

547

print(f"Sine of angle: {angle1.sin()}")

548

```

549

550

### Astronomical Calculations

551

552

```python

553

# Distance modulus calculation

554

distance = quantity(100, 'pc') # Distance to object

555

distance_modulus = 5 * distance.convert('pc').log10() - 5

556

print(f"Distance modulus: {distance_modulus}")

557

558

# Doppler shift calculation

559

rest_freq = constants['HI'] # 21cm line

560

velocity = quantity('100km/s') # Recession velocity

561

c = constants['c']

562

563

# Non-relativistic Doppler formula: Δf/f = v/c

564

doppler_shift = velocity / c

565

observed_freq = rest_freq * (1 - doppler_shift)

566

print(f"Rest frequency: {rest_freq}")

567

print(f"Observed frequency: {observed_freq}")

568

print(f"Frequency shift: {rest_freq - observed_freq}")

569

```

570

571

### Time and Angle Parsing

572

573

```python

574

# Parse time strings

575

time1 = quantity('12h30m15s') # Hours, minutes, seconds

576

time2 = quantity('2023-01-01/18:30:00') # Date/time format

577

time3 = quantity('58000d') # Modified Julian Day

578

579

print(f"Time 1: {time1}")

580

print(f"Time 2: {time2}")

581

print(f"Time 3: {time3}")

582

583

# Parse angle strings

584

ra = quantity('12h30m15.5s') # Right ascension

585

dec = quantity('-30d15m30s') # Declination

586

angle = quantity('45:30:15') # Degrees:arcmin:arcsec

587

588

print(f"RA: {ra}")

589

print(f"RA in degrees: {ra.convert('deg')}")

590

print(f"Dec: {dec}")

591

print(f"Angle: {angle}")

592

```

593

594

### Vector Quantities

595

596

```python

597

# Work with vector quantities

598

frequencies = quantity([1.4, 1.42, 1.66, 1.67], 'GHz')

599

print(f"Frequencies: {frequencies}")

600

601

# Convert all elements

602

freq_mhz = frequencies.convert('MHz')

603

print(f"Frequencies in MHz: {freq_mhz}")

604

605

# Access individual elements

606

first_freq = frequencies[0]

607

print(f"First frequency: {first_freq}")

608

609

# Slice vector

610

mid_freqs = frequencies[1:3]

611

print(f"Middle frequencies: {mid_freqs}")

612

613

# Mathematical operations on vectors

614

wavelengths = constants['c'] / frequencies

615

print(f"Wavelengths: {wavelengths}")

616

print(f"Wavelengths in cm: {wavelengths.convert('cm')}")

617

```

618

619

### Physical Constants

620

621

```python

622

# Access physical constants

623

c = constants['c'] # Speed of light

624

h = constants['h'] # Planck constant

625

k = constants['k'] # Boltzmann constant

626

pc = constants['pc'] # Parsec

627

hi = constants['HI'] # 21cm line

628

629

print(f"Speed of light: {c}")

630

print(f"Planck constant: {h}")

631

print(f"21cm rest frequency: {hi}")

632

633

# Calculate brightness temperature

634

frequency = quantity('1.42GHz')

635

flux_density = quantity('1Jy') # Jansky

636

beam_area = quantity('1arcsec2')

637

638

# T_b = λ²S / (2k × Ω)

639

wavelength = c / frequency

640

brightness_temp = (wavelength**2 * flux_density) / (2 * k * beam_area)

641

print(f"Brightness temperature: {brightness_temp.convert('K')}")

642

```