Coverage for ase/io/pov.py: 80.44%

363 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1""" 

2Module for povray file format support. 

3 

4See http://www.povray.org/ for details on the format. 

5""" 

6 

7from collections.abc import Sequence 

8from os import unlink 

9from pathlib import Path 

10from subprocess import DEVNULL, check_call 

11 

12import numpy as np 

13 

14from ase import Atoms 

15from ase.constraints import FixAtoms 

16from ase.io.utils import PlottingVariables 

17 

18 

19def pa(array): 

20 """Povray array syntax""" 

21 return '<' + ', '.join(f'{x:>6.2f}' for x in tuple(array)) + '>' 

22 

23 

24def pc(array): 

25 """Povray color syntax""" 

26 if isinstance(array, str): 

27 return 'color ' + array 

28 if isinstance(array, float): 

29 return f'rgb <{array:.2f}>*3'.format(array) 

30 L = len(array) 

31 if L > 2 and L < 6: 

32 return ( 

33 f'rgb{"" if L == 3 else "t" if L == 4 else "ft"} <' 

34 + ', '.join(f'{x:.2f}' for x in tuple(array)) 

35 + '>' 

36 ) 

37 

38 

39def get_bondpairs(atoms, radius=1.1): 

40 """Get all pairs of bonding atoms 

41 

42 Return all pairs of atoms which are closer than radius times the 

43 sum of their respective covalent radii. The pairs are returned as 

44 tuples:: 

45 

46 (a, b, (i1, i2, i3)) 

47 

48 so that atoms a bonds to atom b displaced by the vector:: 

49 

50 _ _ _ 

51 i c + i c + i c , 

52 1 1 2 2 3 3 

53 

54 where c1, c2 and c3 are the unit cell vectors and i1, i2, i3 are 

55 integers.""" 

56 

57 from ase.data import covalent_radii 

58 from ase.neighborlist import NeighborList 

59 

60 cutoffs = radius * covalent_radii[atoms.numbers] 

61 nl = NeighborList(cutoffs=cutoffs, self_interaction=False) 

62 nl.update(atoms) 

63 bondpairs = [] 

64 for a in range(len(atoms)): 

65 indices, offsets = nl.get_neighbors(a) 

66 bondpairs.extend( 

67 [(a, a2, offset) for a2, offset in zip(indices, offsets)] 

68 ) 

69 return bondpairs 

70 

71 

72def set_high_bondorder_pairs(bondpairs, high_bondorder_pairs=None): 

73 """Set high bondorder pairs 

74 

75 Modify bondpairs list (from get_bondpairs((atoms)) to include high 

76 bondorder pairs. 

77 

78 Parameters 

79 ----------- 

80 bondpairs: List of pairs, generated from get_bondpairs(atoms) 

81 high_bondorder_pairs: Dictionary of pairs with high bond orders 

82 using the following format: 

83 { ( a1, b1 ): ( offset1, bond_order1, bond_offset1), 

84 ( a2, b2 ): ( offset2, bond_order2, bond_offset2), 

85 ... 

86 } 

87 offset, bond_order, bond_offset are optional. 

88 However, if they are provided, the 1st value is 

89 offset, 2nd value is bond_order, 

90 3rd value is bond_offset""" 

91 

92 if high_bondorder_pairs is None: 

93 high_bondorder_pairs = {} 

94 bondpairs_ = [] 

95 for pair in bondpairs: 

96 (a, b) = (pair[0], pair[1]) 

97 if (a, b) in high_bondorder_pairs.keys(): 

98 bondpair = [a, b] + [item for item in high_bondorder_pairs[(a, b)]] 

99 bondpairs_.append(bondpair) 

100 elif (b, a) in high_bondorder_pairs.keys(): 

101 bondpair = [a, b] + [item for item in high_bondorder_pairs[(b, a)]] 

102 bondpairs_.append(bondpair) 

103 else: 

104 bondpairs_.append(pair) 

105 return bondpairs_ 

106 

107 

108class POVRAY: 

109 # These new styles were an attempt to port the old styles o the correct 

110 # gamma, many had or still have unphysical light properties inorder to 

111 # acheive a certain look. 

112 material_styles_dict = dict( 

113 simple='finish {phong 0.7 ambient 0.4 diffuse 0.55}', 

114 # In general, 'pale' doesn't conserve energy and can look 

115 # strange in many cases. 

116 pale=( 

117 'finish {ambient 0.9 diffuse 0.30 roughness 0.001 specular 0.2 }' 

118 ), 

119 intermediate=( 

120 'finish {ambient 0.4 diffuse 0.6 specular 0.1 roughness 0.04}' 

121 ), 

122 vmd=( 

123 'finish {ambient 0.2 diffuse 0.80 phong 0.25 phong_size 10.0 ' 

124 'specular 0.2 roughness 0.1}' 

125 ), 

126 jmol=( 

127 'finish {ambient 0.4 diffuse 0.6 specular 1 roughness 0.001 ' 

128 'metallic}' 

129 ), 

130 ase2=( 

131 'finish {ambient 0.2 brilliance 3 diffuse 0.6 metallic ' 

132 'specular 0.7 roughness 0.04 reflection 0.15}' 

133 ), 

134 ase3=( 

135 'finish {ambient 0.4 brilliance 2 diffuse 0.6 metallic ' 

136 'specular 1.0 roughness 0.001 reflection 0.0}' 

137 ), 

138 glass=( 

139 'finish {ambient 0.4 diffuse 0.35 specular 1.0 roughness 0.001}' 

140 ), 

141 glass2=( 

142 'finish {ambient 0.3 diffuse 0.3 specular 1.0 ' 

143 'reflection 0.25 roughness 0.001}' 

144 ), 

145 ) 

146 

147 # These styles were made when assumed_gamma was 1.0 which gives poor color 

148 # reproduction, the correct gamma is 2.2 for the sRGB standard. 

149 material_styles_dict_old = dict( 

150 simple='finish {phong 0.7}', 

151 pale=( 

152 'finish {ambient 0.5 diffuse 0.85 roughness 0.001 specular 0.200 }' 

153 ), 

154 intermediate=( 

155 'finish {ambient 0.3 diffuse 0.6 specular 0.1 roughness 0.04}' 

156 ), 

157 vmd=( 

158 'finish {ambient 0.0 diffuse 0.65 phong 0.1 phong_size 40.0 ' 

159 'specular 0.5 }' 

160 ), 

161 jmol=( 

162 'finish {ambient 0.2 diffuse 0.6 specular 1 roughness 0.001 ' 

163 'metallic}' 

164 ), 

165 ase2=( 

166 'finish {ambient 0.05 brilliance 3 diffuse 0.6 metallic ' 

167 'specular 0.7 roughness 0.04 reflection 0.15}' 

168 ), 

169 ase3=( 

170 'finish {ambient 0.15 brilliance 2 diffuse 0.6 metallic ' 

171 'specular 1.0 roughness 0.001 reflection 0.0}' 

172 ), 

173 glass=( 

174 'finish {ambient 0.05 diffuse 0.3 specular 1.0 roughness 0.001}' 

175 ), 

176 glass2=( 

177 'finish {ambient 0.01 diffuse 0.3 specular 1.0 ' 

178 'reflection 0.25 roughness 0.001}' 

179 ), 

180 ) 

181 

182 def __init__( 

183 self, 

184 cell, 

185 cell_vertices, 

186 positions, 

187 diameters, 

188 colors, 

189 image_width, 

190 image_height, 

191 constraints=(), 

192 isosurfaces=None, 

193 display=False, 

194 pause=True, 

195 transparent=True, 

196 canvas_width=None, 

197 canvas_height=None, 

198 camera_dist=50.0, 

199 image_plane=None, 

200 camera_type='orthographic', 

201 point_lights=None, 

202 area_light=None, 

203 background='White', 

204 textures=None, 

205 transmittances=None, 

206 depth_cueing=False, 

207 cue_density=5e-3, 

208 celllinewidth=0.05, 

209 bondlinewidth=0.10, 

210 bondatoms=None, 

211 exportconstraints=False, 

212 ): 

213 """ 

214 # x, y is the image plane, z is *out* of the screen 

215 cell: ase.cell 

216 cell object 

217 cell_vertices: 2-d numpy array 

218 contains the 8 vertices of the cell, each with three coordinates 

219 positions: 2-d numpy array 

220 number of atoms length array with three coordinates for positions 

221 diameters: 1-d numpy array 

222 diameter of atoms (in order with positions) 

223 colors: list of str 

224 colors of atoms (in order with positions) 

225 image_width: float 

226 image width in pixels 

227 image_height: float 

228 image height in pixels 

229 constraints: Atoms.constraints 

230 constraints to be visualized 

231 isosurfaces: list of POVRAYIsosurface 

232 composite object to write/render POVRAY isosurfaces 

233 display: bool 

234 display while rendering 

235 pause: bool 

236 pause when done rendering (only if display) 

237 transparent: bool 

238 make background transparent 

239 canvas_width: int 

240 width of canvas in pixels 

241 canvas_height: int 

242 height of canvas in pixels 

243 camera_dist: float 

244 distance from camera to front atom 

245 image_plane: float 

246 distance from front atom to image plane 

247 camera_type: str 

248 if 'orthographic' perspective, ultra_wide_angle 

249 point_lights: list of 2-element sequences 

250 like [[loc1, color1], [loc2, color2],...] 

251 area_light: 3-element sequence of location (3-tuple), color (str), 

252 width (float), height (float), 

253 Nlamps_x (int), Nlamps_y (int) 

254 example [(2., 3., 40.), 'White', .7, .7, 3, 3] 

255 background: str 

256 color specification, e.g., 'White' 

257 textures: list of str 

258 length of atoms list of texture names 

259 transmittances: list of floats 

260 length of atoms list of transmittances of the atoms 

261 depth_cueing: bool 

262 whether or not to use depth cueing a.k.a. fog 

263 use with care - adjust the camera_distance to be closer 

264 cue_density: float 

265 if there is depth_cueing, how dense is it (how dense is the fog) 

266 celllinewidth: float 

267 radius of the cylinders representing the cell (Ang.) 

268 bondlinewidth: float 

269 radius of the cylinders representing bonds (Ang.) 

270 bondatoms: list of lists (polymorphic) 

271 [[atom1, atom2], ... ] pairs of bonding atoms 

272 For bond order > 1 = [[atom1, atom2, offset, 

273 bond_order, bond_offset], 

274 ... ] 

275 bond_order: 1, 2, 3 for single, double, 

276 and triple bond 

277 bond_offset: vector for shifting bonds from 

278 original position. Coordinates are 

279 in Angstrom unit. 

280 exportconstraints: bool 

281 honour FixAtoms and mark?""" 

282 

283 # attributes from initialization 

284 if bondatoms is None: 

285 bondatoms = [] 

286 if area_light is None: 

287 area_light = [(2.0, 3.0, 40.0), 'White', 0.7, 0.7, 3, 3] 

288 if point_lights is None: 

289 point_lights = [] 

290 if isosurfaces is None: 

291 isosurfaces = [] 

292 self.area_light = area_light 

293 self.background = background 

294 self.bondatoms = bondatoms 

295 self.bondlinewidth = bondlinewidth 

296 self.camera_dist = camera_dist 

297 self.camera_type = camera_type 

298 self.celllinewidth = celllinewidth 

299 self.cue_density = cue_density 

300 self.depth_cueing = depth_cueing 

301 self.display = display 

302 self.exportconstraints = exportconstraints 

303 self.isosurfaces = isosurfaces 

304 self.pause = pause 

305 self.point_lights = point_lights 

306 self.textures = textures 

307 self.transmittances = transmittances 

308 self.transparent = transparent 

309 

310 self.image_width = image_width 

311 self.image_height = image_height 

312 self.colors = colors 

313 self.cell = cell 

314 self.diameters = diameters 

315 

316 # calculations based on passed inputs 

317 

318 z0 = positions[:, 2].max() 

319 self.offset = (image_width / 2, image_height / 2, z0) 

320 self.positions = positions - self.offset 

321 

322 if cell_vertices is not None: 

323 cell_vertices = (cell_vertices - self.offset).reshape((2, 2, 2, 3)) 

324 

325 self.cell_vertices = cell_vertices 

326 

327 ratio = float(self.image_width) / self.image_height 

328 if canvas_width is None: 

329 if canvas_height is None: 

330 self.canvas_width = min(self.image_width * 15, 640) 

331 # a guess should respect the aspect ratio 

332 self.canvas_height = self.canvas_width / ratio 

333 else: 

334 self.canvas_width = canvas_height * ratio 

335 self.canvas_height = canvas_height 

336 elif canvas_height is None: 

337 self.canvas_width = canvas_width 

338 self.canvas_height = self.canvas_width / ratio 

339 else: 

340 raise RuntimeError("Can't set *both* width and height!") 

341 

342 # Distance to image plane from camera 

343 if image_plane is None: 

344 if self.camera_type == 'orthographic': 

345 self.image_plane = 1 - self.camera_dist 

346 else: 

347 self.image_plane = 0 

348 self.image_plane += self.camera_dist 

349 

350 self.constrainatoms = [] 

351 for c in constraints: 

352 if isinstance(c, FixAtoms): 

353 # self.constrainatoms.extend(c.index) # is this list-like? 

354 for n, i in enumerate(c.index): 

355 self.constrainatoms += [i] 

356 

357 @classmethod 

358 def from_PlottingVariables(cls, pvars, **kwargs): 

359 cell = pvars.cell 

360 cell_vertices = pvars.cell_vertices 

361 if 'colors' in kwargs: 

362 colors = kwargs.pop('colors') 

363 else: 

364 colors = pvars.colors 

365 diameters = pvars.d 

366 image_height = pvars.h 

367 image_width = pvars.w 

368 positions = pvars.positions 

369 constraints = pvars.constraints 

370 return cls( 

371 cell=cell, 

372 cell_vertices=cell_vertices, 

373 colors=colors, 

374 constraints=constraints, 

375 diameters=diameters, 

376 image_height=image_height, 

377 image_width=image_width, 

378 positions=positions, 

379 **kwargs, 

380 ) 

381 

382 @classmethod 

383 def from_atoms(cls, atoms, **kwargs): 

384 return cls.from_plotting_variables( 

385 PlottingVariables(atoms, scale=1.0), **kwargs 

386 ) 

387 

388 def write_ini(self, path): 

389 """Write ini file.""" 

390 

391 ini_str = f"""\ 

392Input_File_Name={path.with_suffix('.pov').name} 

393Output_to_File=True 

394Output_File_Type=N 

395Output_Alpha={'on' if self.transparent else 'off'} 

396; if you adjust Height, and width, you must preserve the ratio 

397; Width / Height = {self.canvas_width / self.canvas_height:f} 

398Width={self.canvas_width} 

399Height={self.canvas_height} 

400Antialias=True 

401Antialias_Threshold=0.1 

402Display={self.display} 

403Display_Gamma=sRGB 

404Pause_When_Done={self.pause} 

405Verbose=False 

406""" 

407 with open(path, 'w') as fd: 

408 fd.write(ini_str) 

409 return path 

410 

411 def write_pov(self, path): 

412 """Write pov file.""" 

413 

414 point_lights = '\n'.join( 

415 f'light_source {{{pa(loc)} {pc(rgb)}}}' 

416 for loc, rgb in self.point_lights 

417 ) 

418 

419 area_light = '' 

420 if self.area_light is not None: 

421 loc, color, width, height, nx, ny = self.area_light 

422 area_light += f"""\nlight_source {{{pa(loc)} {pc(color)} 

423 area_light <{width:.2f}, 0, 0>, <0, {height:.2f}, 0>, {nx:n}, {ny:n} 

424 adaptive 1 jitter}}""" 

425 

426 fog = '' 

427 if self.depth_cueing and (self.cue_density >= 1e-4): 

428 # same way vmd does it 

429 if self.cue_density > 1e4: 

430 # larger does not make any sense 

431 dist = 1e-4 

432 else: 

433 dist = 1.0 / self.cue_density 

434 fog += ( 

435 f'fog {{fog_type 1 distance {dist:.4f} ' 

436 f'color {pc(self.background)}}}' 

437 ) 

438 

439 mat_style_keys = ( 

440 f'#declare {k} = {v}' for k, v in self.material_styles_dict.items() 

441 ) 

442 mat_style_keys = '\n'.join(mat_style_keys) 

443 

444 # Draw unit cell 

445 cell_vertices = '' 

446 if self.cell_vertices is not None: 

447 for c in range(3): 

448 for j in ([0, 0], [1, 0], [1, 1], [0, 1]): 

449 p1 = self.cell_vertices[tuple(j[:c]) + (0,) + tuple(j[c:])] 

450 p2 = self.cell_vertices[tuple(j[:c]) + (1,) + tuple(j[c:])] 

451 

452 distance = np.linalg.norm(p2 - p1) 

453 if distance < 1e-12: 

454 continue 

455 

456 cell_vertices += ( 

457 f'cylinder {{{pa(p1)}, {pa(p2)}, ' 

458 'Rcell pigment {Black}}\n' 

459 ) 

460 # all strings are f-strings for consistency 

461 cell_vertices = cell_vertices.strip('\n') 

462 

463 # Draw atoms 

464 a = 0 

465 atoms = '' 

466 for loc, dia, col in zip(self.positions, self.diameters, self.colors): 

467 tex = 'ase3' 

468 trans = 0.0 

469 if self.textures is not None: 

470 tex = self.textures[a] 

471 if self.transmittances is not None: 

472 trans = self.transmittances[a] 

473 atoms += ( 

474 f'atom({pa(loc)}, {dia / 2.0:.2f}, {pc(col)}, ' 

475 f'{trans}, {tex}) // #{a:n}\n' 

476 ) 

477 a += 1 

478 atoms = atoms.strip('\n') 

479 

480 # Draw atom bonds 

481 bondatoms = '' 

482 for pair in self.bondatoms: 

483 # Make sure that each pair has 4 componets: a, b, offset, 

484 # bond_order, bond_offset 

485 # a, b: atom index to draw bond 

486 # offset: original meaning to make offset for mid-point. 

487 # bond_oder: if not supplied, set it to 1 (single bond). 

488 # It can be 1, 2, 3, corresponding to single, 

489 # double, triple bond 

490 # bond_offset: displacement from original bond position. 

491 # Default is (bondlinewidth, bondlinewidth, 0) 

492 # for bond_order > 1. 

493 if len(pair) == 2: 

494 a, b = pair 

495 offset = (0, 0, 0) 

496 bond_order = 1 

497 bond_offset = (0, 0, 0) 

498 elif len(pair) == 3: 

499 a, b, offset = pair 

500 bond_order = 1 

501 bond_offset = (0, 0, 0) 

502 elif len(pair) == 4: 

503 a, b, offset, bond_order = pair 

504 bond_offset = (self.bondlinewidth, self.bondlinewidth, 0) 

505 elif len(pair) > 4: 

506 a, b, offset, bond_order, bond_offset = pair 

507 else: 

508 raise RuntimeError( 

509 'Each list in bondatom must have at least ' 

510 '2 entries. Error at %s' % pair 

511 ) 

512 

513 if len(offset) != 3: 

514 raise ValueError( 

515 'offset must have 3 elements. Error at %s' % pair 

516 ) 

517 if len(bond_offset) != 3: 

518 raise ValueError( 

519 'bond_offset must have 3 elements. Error at %s' % pair 

520 ) 

521 if bond_order not in [0, 1, 2, 3]: 

522 raise ValueError( 

523 'bond_order must be either 0, 1, 2, or 3. ' 

524 'Error at %s' % pair 

525 ) 

526 

527 # Up to here, we should have all a, b, offset, bond_order, 

528 # bond_offset for all bonds. 

529 

530 # Rotate bond_offset so that its direction is 90 deg. off the bond 

531 # Utilize Atoms object to rotate 

532 if bond_order > 1 and np.linalg.norm(bond_offset) > 1.0e-9: 

533 tmp_atoms = Atoms('H3') 

534 tmp_atoms.set_cell(self.cell) 

535 tmp_atoms.set_positions( 

536 [ 

537 self.positions[a], 

538 self.positions[b], 

539 self.positions[b] + np.array(bond_offset), 

540 ] 

541 ) 

542 tmp_atoms.center() 

543 tmp_atoms.set_angle(0, 1, 2, 90) 

544 bond_offset = tmp_atoms[2].position - tmp_atoms[1].position 

545 

546 R = np.dot(offset, self.cell) 

547 mida = 0.5 * (self.positions[a] + self.positions[b] + R) 

548 midb = 0.5 * (self.positions[a] + self.positions[b] - R) 

549 if self.textures is not None: 

550 texa = self.textures[a] 

551 texb = self.textures[b] 

552 else: 

553 texa = texb = 'ase3' 

554 

555 if self.transmittances is not None: 

556 transa = self.transmittances[a] 

557 transb = self.transmittances[b] 

558 else: 

559 transa = transb = 0.0 

560 

561 # draw bond, according to its bond_order. 

562 # bond_order == 0: No bond is plotted 

563 # bond_order == 1: use original code 

564 # bond_order == 2: draw two bonds, one is shifted by bond_offset/2, 

565 # and another is shifted by -bond_offset/2. 

566 # bond_order == 3: draw two bonds, one is shifted by bond_offset, 

567 # and one is shifted by -bond_offset, and the 

568 # other has no shift. 

569 # To shift the bond, add the shift to the first two coordinate in 

570 # write statement. 

571 

572 posa = self.positions[a] 

573 posb = self.positions[b] 

574 cola = self.colors[a] 

575 colb = self.colors[b] 

576 

577 if bond_order == 1: 

578 draw_tuples = ( 

579 (posa, mida, cola, transa, texa), 

580 (posb, midb, colb, transb, texb), 

581 ) 

582 

583 elif bond_order == 2: 

584 bs = [x / 2 for x in bond_offset] 

585 draw_tuples = ( 

586 (posa - bs, mida - bs, cola, transa, texa), 

587 (posb - bs, midb - bs, colb, transb, texb), 

588 (posa + bs, mida + bs, cola, transa, texa), 

589 (posb + bs, midb + bs, colb, transb, texb), 

590 ) 

591 

592 elif bond_order == 3: 

593 bs = bond_offset 

594 draw_tuples = ( 

595 (posa, mida, cola, transa, texa), 

596 (posb, midb, colb, transb, texb), 

597 (posa + bs, mida + bs, cola, transa, texa), 

598 (posb + bs, midb + bs, colb, transb, texb), 

599 (posa - bs, mida - bs, cola, transa, texa), 

600 (posb - bs, midb - bs, colb, transb, texb), 

601 ) 

602 

603 bondatoms += ''.join( 

604 f'cylinder {{{pa(p)}, ' 

605 f'{pa(m)}, Rbond texture{{pigment ' 

606 f'{{color {pc(c)} ' 

607 f'transmit {tr}}} finish{{{tx}}}}}}}\n' 

608 for p, m, c, tr, tx in draw_tuples 

609 ) 

610 

611 bondatoms = bondatoms.strip('\n') 

612 

613 # Draw constraints if requested 

614 constraints = '' 

615 if self.exportconstraints: 

616 for a in self.constrainatoms: 

617 dia = self.diameters[a] 

618 loc = self.positions[a] 

619 trans = 0.0 

620 if self.transmittances is not None: 

621 trans = self.transmittances[a] 

622 constraints += ( 

623 f'constrain({pa(loc)}, {dia / 2.0:.2f}, Black, ' 

624 f'{trans}, {tex}) // #{a:n} \n' 

625 ) 

626 constraints = constraints.strip('\n') 

627 

628 pov = f"""#version 3.6; 

629#include "colors.inc" 

630#include "finish.inc" 

631 

632global_settings {{assumed_gamma 2.2 max_trace_level 6}} 

633background {{{pc(self.background)}{' transmit 1.0' if self.transparent else ''}}} 

634camera {{{self.camera_type} 

635 right -{self.image_width:.2f}*x up {self.image_height:.2f}*y 

636 direction {self.image_plane:.2f}*z 

637 location <0,0,{self.camera_dist:.2f}> look_at <0,0,0>}} 

638{point_lights} 

639{area_light if area_light != '' else '// no area light'} 

640{fog if fog != '' else '// no fog'} 

641{mat_style_keys} 

642#declare Rcell = {self.celllinewidth:.3f}; 

643#declare Rbond = {self.bondlinewidth:.3f}; 

644 

645#macro atom(LOC, R, COL, TRANS, FIN) 

646 sphere{{LOC, R texture{{pigment{{color COL transmit TRANS}} finish{{FIN}}}}}} 

647#end 

648#macro constrain(LOC, R, COL, TRANS FIN) 

649union{{torus{{R, Rcell rotate 45*z texture{{pigment{{color COL transmit TRANS}} finish{{FIN}}}}}} 

650 torus{{R, Rcell rotate -45*z texture{{pigment{{color COL transmit TRANS}} finish{{FIN}}}}}} 

651 translate LOC}} 

652#end 

653 

654{cell_vertices if cell_vertices != '' else '// no cell vertices'} 

655{atoms} 

656{bondatoms} 

657{constraints if constraints != '' else '// no constraints'} 

658""" # noqa: E501 

659 

660 with open(path, 'w') as fd: 

661 fd.write(pov) 

662 

663 return path 

664 

665 def write(self, pov_path): 

666 pov_path = require_pov(pov_path) 

667 ini_path = pov_path.with_suffix('.ini') 

668 self.write_ini(ini_path) 

669 self.write_pov(pov_path) 

670 if self.isosurfaces is not None: 

671 with open(pov_path, 'a') as fd: 

672 for iso in self.isosurfaces: 

673 fd.write(iso.format_mesh()) 

674 return POVRAYInputs(ini_path) 

675 

676 

677def require_pov(path): 

678 path = Path(path) 

679 if path.suffix != '.pov': 

680 raise ValueError(f'Expected .pov path, got {path}') 

681 return path 

682 

683 

684class POVRAYInputs: 

685 def __init__(self, path): 

686 self.path = path 

687 

688 def render( 

689 self, povray_executable='povray', stderr=DEVNULL, clean_up=False 

690 ): 

691 cmd = [povray_executable, str(self.path)] 

692 

693 check_call(cmd, stderr=stderr) 

694 png_path = self.path.with_suffix('.png').absolute() 

695 if not png_path.is_file(): 

696 raise RuntimeError(f'Povray left no output PNG file "{png_path}"') 

697 

698 if clean_up: 

699 unlink(self.path) 

700 unlink(self.path.with_suffix('.pov')) 

701 

702 return png_path 

703 

704 

705class POVRAYIsosurface: 

706 def __init__( 

707 self, 

708 density_grid, 

709 cut_off, 

710 cell, 

711 cell_origin, 

712 closed_edges=False, 

713 gradient_ascending=False, 

714 color=(0.85, 0.80, 0.25, 0.2), 

715 material='ase3', 

716 ): 

717 """ 

718 density_grid: 3D float ndarray 

719 A regular grid on that spans the cell. The first dimension 

720 corresponds to the first cell vector and so on. 

721 cut_off: float 

722 The density value of the isosurface. 

723 cell: 2D float ndarray or ASE cell object 

724 The 3 vectors which give the cell's repetition 

725 cell_origin: 4 float tuple 

726 The cell origin as used by POVRAY object 

727 closed_edges: bool 

728 Setting this will fill in isosurface edges at the cell boundaries. 

729 Filling in the edges can help with visualizing 

730 highly porous structures. 

731 gradient_ascending: bool 

732 Lets you pick the area you want to enclose, i.e., should the denser 

733 or less dense area be filled in. 

734 color: povray color string, float, or float tuple 

735 1 float is interpreted as grey scale, a 3 float tuple is rgb, 

736 4 float tuple is rgbt, and 5 float tuple is rgbft, where 

737 t is transmission fraction and f is filter fraction. 

738 Named Povray colors are set in colors.inc 

739 (http://wiki.povray.org/content/Reference:Colors.inc) 

740 material: string 

741 Can be a finish macro defined by POVRAY.material_styles 

742 or a full Povray material {...} specification. Using a 

743 full material specification willoverride the color parameter. 

744 """ 

745 

746 self.gradient_direction = 'ascent' if gradient_ascending else 'descent' 

747 self.color = color 

748 self.material = material 

749 self.closed_edges = closed_edges 

750 self._cut_off = cut_off 

751 

752 if self.gradient_direction == 'ascent': 

753 cv = 2 * cut_off 

754 else: 

755 cv = 0 

756 

757 if closed_edges: 

758 shape_old = density_grid.shape 

759 # since well be padding, we need to keep the data at origin 

760 cell_origin += -(1.0 / np.array(shape_old)) @ cell 

761 density_grid = np.pad( 

762 density_grid, 

763 pad_width=(1,), 

764 mode='constant', 

765 constant_values=cv, 

766 ) 

767 shape_new = density_grid.shape 

768 s = np.array(shape_new) / np.array(shape_old) 

769 cell = cell @ np.diag(s) 

770 

771 self.cell = cell 

772 self.cell_origin = cell_origin 

773 self.density_grid = density_grid 

774 self.spacing = tuple(1.0 / np.array(self.density_grid.shape)) 

775 

776 scaled_verts, faces, _normals, _values = self.compute_mesh( 

777 self.density_grid, 

778 self.cut_off, 

779 self.spacing, 

780 self.gradient_direction, 

781 ) 

782 

783 # The verts are scaled by default, this is the super easy way of 

784 # distributing them in real space but it's easier to do affine 

785 # transformations/rotations on a unit cube so I leave it like that 

786 # verts = scaled_verts.dot(self.cell) 

787 self.verts = scaled_verts 

788 self.faces = faces 

789 

790 @property 

791 def cut_off(self): 

792 return self._cut_off 

793 

794 @cut_off.setter 

795 def cut_off(self, value): 

796 raise Exception('Use the set_cut_off method') 

797 

798 def set_cut_off(self, value): 

799 self._cut_off = value 

800 

801 if self.gradient_direction == 'ascent': 

802 cv = 2 * self.cut_off 

803 else: 

804 cv = 0 

805 

806 if self.closed_edges: 

807 shape_old = self.density_grid.shape 

808 # since well be padding, we need to keep the data at origin 

809 self.cell_origin += -(1.0 / np.array(shape_old)) @ self.cell 

810 self.density_grid = np.pad( 

811 self.density_grid, 

812 pad_width=(1,), 

813 mode='constant', 

814 constant_values=cv, 

815 ) 

816 shape_new = self.density_grid.shape 

817 s = np.array(shape_new) / np.array(shape_old) 

818 self.cell = self.cell @ np.diag(s) 

819 

820 self.spacing = tuple(1.0 / np.array(self.density_grid.shape)) 

821 

822 scaled_verts, faces, _, _ = self.compute_mesh( 

823 self.density_grid, 

824 self.cut_off, 

825 self.spacing, 

826 self.gradient_direction, 

827 ) 

828 

829 self.verts = scaled_verts 

830 self.faces = faces 

831 

832 @classmethod 

833 def from_POVRAY(cls, povray, density_grid, cut_off, **kwargs): 

834 return cls( 

835 cell=povray.cell, 

836 cell_origin=povray.cell_vertices[0, 0, 0], 

837 density_grid=density_grid, 

838 cut_off=cut_off, 

839 **kwargs, 

840 ) 

841 

842 @staticmethod 

843 def wrapped_triples_section( 

844 triple_list, 

845 triple_format='<{:f}, {:f}, {:f}>'.format, 

846 triples_per_line=4, 

847 ): 

848 

849 triples = [triple_format(*x) for x in triple_list] 

850 n = len(triples) 

851 s = '' 

852 tpl = triples_per_line 

853 c = 0 

854 

855 while c < n - tpl: 

856 c += tpl 

857 s += '\n ' 

858 s += ', '.join(triples[c - tpl : c]) 

859 s += '\n ' 

860 s += ', '.join(triples[c:]) 

861 return s 

862 

863 @staticmethod 

864 def compute_mesh(density_grid, cut_off, spacing, gradient_direction): 

865 """ 

866 

867 Import statement is in this method and not file header 

868 since few users will use isosurface rendering. 

869 

870 Returns scaled_verts, faces, normals, values. See skimage docs. 

871 

872 """ 

873 

874 # marching_cubes name was changed in skimage v0.19 

875 try: 

876 # New skimage 

877 from skimage.measure import marching_cubes 

878 except ImportError: 

879 # Old skimage (remove at some point) 

880 from skimage.measure import marching_cubes_lewiner as marching_cubes 

881 

882 return marching_cubes( 

883 density_grid, 

884 level=cut_off, 

885 spacing=spacing, 

886 gradient_direction=gradient_direction, 

887 allow_degenerate=False, 

888 ) 

889 

890 def format_mesh(self): 

891 """Returns a formatted data output for POVRAY files 

892 

893 Example: 

894 material = ''' 

895 material { // This material looks like pink jelly 

896 texture { 

897 pigment { rgbt <0.8, 0.25, 0.25, 0.5> } 

898 finish{ diffuse 0.85 ambient 0.99 brilliance 3 specular 0.5 roughness 0.001 

899 reflection { 0.05, 0.98 fresnel on exponent 1.5 } 

900 conserve_energy 

901 } 

902 } 

903 interior { ior 1.3 } 

904 } 

905 photons { 

906 target 

907 refraction on 

908 reflection on 

909 collect on 

910 }''' 

911 """ # noqa: E501 

912 

913 if self.material in POVRAY.material_styles_dict: 

914 material = f"""material {{ 

915 texture {{ 

916 pigment {{ {pc(self.color)} }} 

917 finish {{ {self.material} }} 

918 }} 

919 }}""" 

920 else: 

921 material = self.material 

922 

923 # Start writing the mesh2 

924 vertex_vectors = self.wrapped_triples_section( 

925 triple_list=self.verts, 

926 triple_format='<{:f}, {:f}, {:f}>'.format, 

927 triples_per_line=4, 

928 ) 

929 

930 face_indices = self.wrapped_triples_section( 

931 triple_list=self.faces, 

932 triple_format='<{:n}, {:n}, {:n}>'.format, 

933 triples_per_line=5, 

934 ) 

935 

936 cell = self.cell 

937 cell_or = self.cell_origin 

938 mesh2 = f"""\n\nmesh2 {{ 

939 vertex_vectors {{ {len(self.verts):n}, 

940 {vertex_vectors} 

941 }} 

942 face_indices {{ {len(self.faces):n}, 

943 {face_indices} 

944 }} 

945{material if material != '' else '// no material'} 

946 matrix < {cell[0][0]:f}, {cell[0][1]:f}, {cell[0][2]:f}, 

947 {cell[1][0]:f}, {cell[1][1]:f}, {cell[1][2]:f}, 

948 {cell[2][0]:f}, {cell[2][1]:f}, {cell[2][2]:f}, 

949 {cell_or[0]:f}, {cell_or[1]:f}, {cell_or[2]:f}> 

950 }} 

951 """ 

952 return mesh2 

953 

954 

955def pop_deprecated(dct, name): 

956 import warnings 

957 

958 if name in dct: 

959 del dct[name] 

960 warnings.warn( 

961 f'The "{name}" keyword of write_pov() is deprecated ' 

962 'and has no effect; this will raise an error in the ' 

963 'future.', 

964 FutureWarning, 

965 ) 

966 

967 

968def write_pov( 

969 filename, 

970 atoms, 

971 *, 

972 povray_settings=None, 

973 isosurface_data=None, 

974 **generic_projection_settings, 

975): 

976 

977 for name in ['run_povray', 'povray_path', 'stderr', 'extras']: 

978 pop_deprecated(generic_projection_settings, name) 

979 

980 if povray_settings is None: 

981 povray_settings = {} 

982 

983 pvars = PlottingVariables(atoms, scale=1.0, **generic_projection_settings) 

984 pov_obj = POVRAY.from_PlottingVariables(pvars, **povray_settings) 

985 

986 if isosurface_data is None: 

987 isosurface_data = [] 

988 elif not isinstance(isosurface_data, Sequence): 

989 isosurface_data = [isosurface_data] 

990 

991 isosurfaces = [] 

992 for isodata in isosurface_data: 

993 if isinstance(isodata, POVRAYIsosurface): 

994 iso = isodata 

995 else: 

996 iso = POVRAYIsosurface.from_POVRAY(pov_obj, **isodata) 

997 isosurfaces.append(iso) 

998 pov_obj.isosurfaces = isosurfaces 

999 

1000 return pov_obj.write(filename)