or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

constants.mddust-physics.mdgas-physics.mdgrid-stellar.mdindex.mdplotting.mdsimulation-control.mdsimulation.mdutilities.md

utilities.mddocs/

0

# Utility Functions

1

2

Helper classes and functions for boundary conditions, data handling, and simulation utilities. The utilities module provides essential support functionality for DustPy simulations including boundary condition management, data extraction, and version checking.

3

4

## Capabilities

5

6

### Boundary Condition Management

7

8

Class for managing and applying boundary conditions to simulation quantities.

9

10

```python { .api }

11

from dustpy import utils

12

13

class utils.Boundary:

14

"""

15

Boundary condition management class.

16

17

Provides flexible boundary condition specification and application

18

for simulation variables including constant values, gradients,

19

and power-law conditions.

20

"""

21

22

def __init__(self, r, ri, S, condition=None, value=None):

23

"""

24

Initialize boundary condition object.

25

26

Parameters:

27

- r: Radial grid

28

- ri: Radial grid cell interfaces

29

- S: Field on which boundary condition is imposed

30

- condition: Boundary condition type (optional)

31

- value: Boundary condition value (optional)

32

"""

33

34

def setcondition(self, condition):

35

"""

36

Set the boundary condition type.

37

38

Parameters:

39

- condition: Boundary condition type

40

- "val": Constant value

41

- "const_val": Alias for constant value

42

- "grad": Constant gradient

43

- "const_grad": Alias for constant gradient

44

- "pow": Power-law condition

45

- "const_pow": Alias for power-law condition

46

"""

47

48

def setboundary(self, value):

49

"""

50

Set the boundary condition value.

51

52

Parameters:

53

- value: Boundary condition value

54

For "val"/"const_val": the constant value

55

For "grad"/"const_grad": the gradient value

56

For "pow"/"const_pow": the power-law exponent

57

"""

58

59

def __repr__(self):

60

"""String representation of boundary condition."""

61

62

# Properties

63

condition: str # Current boundary condition type

64

value: float # Current boundary condition value

65

```

66

67

### Data Extraction

68

69

Function for extracting and processing simulation data for analysis and plotting.

70

71

```python { .api }

72

def utils.read_data(data, filename="data", extension="hdf5", Na=50):

73

"""

74

Extract simulation data for analysis and plotting.

75

76

Processes simulation output into a convenient format with

77

derived quantities and metadata for visualization and analysis.

78

79

Parameters:

80

- data: Simulation object or None (to read from file)

81

- filename: Data file name (default: "data")

82

- extension: File extension ("hdf5", "h5", or "dump")

83

- Na: Number of particle size bins for processing (default: 50)

84

85

Returns:

86

utils.SimpleNamespace: Object containing processed data arrays

87

- r: Radial grid [cm]

88

- a: Particle sizes [cm]

89

- Sigma_gas: Gas surface density [g/cm²]

90

- Sigma_dust: Dust surface density [g/cm²]

91

- T: Temperature [K]

92

- St: Stokes numbers

93

- v_rad: Radial velocities [cm/s]

94

- Additional derived quantities for plotting

95

"""

96

```

97

98

### Namespace Management

99

100

Restricted namespace class that prevents accidental attribute addition.

101

102

```python { .api }

103

class utils.SimpleNamespace:

104

"""

105

Simple namespace that restricts adding new attributes.

106

107

Provides a container for grouped attributes while preventing

108

accidental addition of new attributes after initialization.

109

Used throughout DustPy for organizing simulation parameters.

110

"""

111

112

def __init__(self, **kwargs):

113

"""

114

Initialize namespace with given keyword arguments.

115

116

Parameters:

117

- kwargs: Initial attributes to set

118

"""

119

120

def __setattr__(self, name, value):

121

"""Controlled attribute setting."""

122

123

def __repr__(self):

124

"""String representation showing all attributes."""

125

```

126

127

### Version Management

128

129

Function for checking and warning about package version updates.

130

131

```python { .api }

132

def utils.print_version_warning(timeout=0.5):

133

"""

134

Check for package updates and print warnings if outdated.

135

136

Queries PyPI to check if a newer version of DustPy is available

137

and prints a warning message if the current installation is outdated.

138

139

Parameters:

140

- timeout: Request timeout in seconds (default: 0.5)

141

142

Returns:

143

None

144

145

Note:

146

- Requires internet connection to check PyPI

147

- Fails silently if network request times out

148

- Called automatically when importing dustpy

149

"""

150

```

151

152

## Usage Examples

153

154

### Boundary Condition Setup

155

156

```python

157

from dustpy import Simulation, utils

158

159

sim = Simulation()

160

sim.makegrids()

161

162

# Set up dust boundary conditions

163

inner_boundary = utils.Boundary()

164

inner_boundary.setcondition("val") # Constant value

165

inner_boundary.setboundary(0.0) # Zero dust influx

166

167

outer_boundary = utils.Boundary()

168

outer_boundary.setcondition("grad") # Constant gradient

169

outer_boundary.setboundary(0.0) # Zero gradient (closed)

170

171

# Apply to dust surface density

172

sim.dust.boundary.inner = inner_boundary

173

sim.dust.boundary.outer = outer_boundary

174

```

175

176

### Custom Boundary Conditions

177

178

```python

179

# Power-law boundary condition

180

power_boundary = utils.Boundary()

181

power_boundary.setcondition("pow")

182

power_boundary.setboundary(-1.5) # Power-law exponent

183

184

# Check boundary condition

185

print(power_boundary) # Shows condition type and value

186

187

# Access boundary properties

188

condition_type = power_boundary.condition # "pow"

189

exponent_value = power_boundary.value # -1.5

190

```

191

192

### Data Processing and Analysis

193

194

```python

195

from dustpy import utils

196

import numpy as np

197

198

# Extract data from simulation

199

sim = Simulation()

200

# ... run simulation ...

201

202

data = utils.read_data(sim)

203

204

# Access processed data

205

radial_grid = data.r # [cm]

206

particle_sizes = data.a # [cm]

207

gas_density = data.Sigma_gas # [g/cm²]

208

dust_density = data.Sigma_dust # [g/cm²]

209

210

# Perform analysis

211

total_gas_mass = np.trapz(gas_density * 2 * np.pi * radial_grid, radial_grid)

212

total_dust_mass = np.trapz(dust_density * 2 * np.pi * radial_grid, radial_grid)

213

dust_to_gas = total_dust_mass / total_gas_mass

214

215

print(f"Total gas mass: {total_gas_mass:.2e} g")

216

print(f"Total dust mass: {total_dust_mass:.2e} g")

217

print(f"Dust-to-gas ratio: {dust_to_gas:.3f}")

218

```

219

220

### Data File Processing

221

222

```python

223

# Process data from HDF5 file

224

data_from_file = utils.read_data(None,

225

filename="simulation_output",

226

extension="hdf5",

227

Na=100) # Higher resolution

228

229

# Process dump file

230

data_from_dump = utils.read_data(None,

231

filename="snapshot_001",

232

extension="dump")

233

234

# Access metadata

235

print(f"Simulation time: {data_from_file.t}")

236

print(f"Number of radial points: {len(data_from_file.r)}")

237

print(f"Number of size bins: {len(data_from_file.a)}")

238

```

239

240

### Namespace Usage

241

242

```python

243

# Create organized parameter groups

244

initial_conditions = utils.SimpleNamespace(

245

gas_mass=0.01,

246

dust_ratio=0.01,

247

temperature=100,

248

alpha_turb=1e-3

249

)

250

251

# Access parameters

252

print(f"Gas mass: {initial_conditions.gas_mass}")

253

print(f"Dust ratio: {initial_conditions.dust_ratio}")

254

255

# Namespace prevents accidental additions

256

# This would raise an AttributeError:

257

# initial_conditions.new_param = 5.0

258

```

259

260

### Version Checking

261

262

```python

263

from dustpy import utils

264

265

# Check for updates (called automatically on import)

266

utils.print_version_warning()

267

268

# With custom timeout

269

utils.print_version_warning(timeout=2.0) # 2 second timeout

270

```

271

272

### Integration with Simulation Workflow

273

274

```python

275

def setup_custom_boundaries(sim, inner_type="val", outer_type="grad"):

276

"""Helper function to set up standard boundary conditions."""

277

278

# Inner boundary

279

inner_bc = utils.Boundary()

280

inner_bc.setcondition(inner_type)

281

inner_bc.setboundary(0.0)

282

283

# Outer boundary

284

outer_bc = utils.Boundary()

285

outer_bc.setcondition(outer_type)

286

outer_bc.setboundary(0.0)

287

288

# Apply to simulation

289

sim.dust.boundary.inner = inner_bc

290

sim.dust.boundary.outer = outer_bc

291

sim.gas.boundary.inner = inner_bc

292

sim.gas.boundary.outer = outer_bc

293

294

# Usage

295

sim = Simulation()

296

sim.makegrids()

297

setup_custom_boundaries(sim)

298

sim.initialize()

299

```

300

301

### Data Analysis Pipeline

302

303

```python

304

def analyze_simulation(sim_or_file, filename=None):

305

"""Complete analysis pipeline for DustPy results."""

306

307

# Extract data

308

if filename:

309

data = utils.read_data(None, filename=filename, extension="hdf5")

310

else:

311

data = utils.read_data(sim_or_file)

312

313

# Calculate derived quantities

314

results = utils.SimpleNamespace(

315

total_gas_mass=np.trapz(data.Sigma_gas * 2 * np.pi * data.r, data.r),

316

total_dust_mass=np.trapz(data.Sigma_dust * 2 * np.pi * data.r, data.r),

317

max_particle_size=np.max(data.a),

318

drift_barrier_location=data.r[np.argmax(data.St)],

319

)

320

321

results.dust_to_gas_ratio = results.total_dust_mass / results.total_gas_mass

322

323

return results

324

325

# Use analysis pipeline

326

results = analyze_simulation(sim)

327

print(f"Dust-to-gas ratio: {results.dust_to_gas_ratio:.4f}")

328

print(f"Maximum particle size: {results.max_particle_size:.2e} cm")

329

```