Coverage for ase/io/xsd.py: 68.90%
164 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1import xml.etree.ElementTree as ET
2from xml.dom import minidom
4import numpy as np
6from ase import Atoms
7from ase.io.utils import connectivity2bonds
8from ase.utils import writer
11def read_xsd(fd):
12 tree = ET.parse(fd)
13 root = tree.getroot()
15 atomtreeroot = root.find('AtomisticTreeRoot')
16 # if periodic system
17 if atomtreeroot.find('SymmetrySystem') is not None:
18 symmetrysystem = atomtreeroot.find('SymmetrySystem')
19 mappingset = symmetrysystem.find('MappingSet')
20 mappingfamily = mappingset.find('MappingFamily')
21 system = mappingfamily.find('IdentityMapping')
23 coords = []
24 cell = []
25 formula = ''
27 for atom in system:
28 if atom.tag == 'Atom3d':
29 symbol = atom.get('Components')
30 formula += symbol
32 xyz = atom.get('XYZ')
33 if xyz:
34 coord = [float(coord) for coord in xyz.split(',')]
35 else:
36 coord = [0.0, 0.0, 0.0]
37 coords.append(coord)
38 elif atom.tag == 'SpaceGroup':
39 avec = [float(vec) for vec in atom.get('AVector').split(',')]
40 bvec = [float(vec) for vec in atom.get('BVector').split(',')]
41 cvec = [float(vec) for vec in atom.get('CVector').split(',')]
43 cell.append(avec)
44 cell.append(bvec)
45 cell.append(cvec)
47 atoms = Atoms(formula, cell=cell, pbc=True)
48 atoms.set_scaled_positions(coords)
49 return atoms
50 # if non-periodic system
51 elif atomtreeroot.find('Molecule') is not None:
52 system = atomtreeroot.find('Molecule')
54 coords = []
55 formula = ''
57 for atom in system:
58 if atom.tag == 'Atom3d':
59 symbol = atom.get('Components')
60 formula += symbol
62 xyz = atom.get('XYZ')
63 coord = [float(coord) for coord in xyz.split(',')]
64 coords.append(coord)
66 atoms = Atoms(formula, pbc=False)
67 atoms.set_scaled_positions(coords)
68 return atoms
71def CPK_or_BnS(element):
72 """Determine how atom is visualized"""
73 if element in ['C', 'H', 'O', 'S', 'N']:
74 visualization_choice = 'Ball and Stick'
75 else:
76 visualization_choice = 'CPK'
77 return visualization_choice
80def SetChild(parent, childname, props):
81 Child = ET.SubElement(parent, childname)
82 for key in props:
83 Child.set(key, props[key])
84 return Child
87def SetBasicChilds():
88 """
89 Basic property setup for Material Studio File
90 """
91 XSD = ET.Element('XSD')
92 XSD.set('Version', '6.0')
94 ATR = SetChild(
95 XSD,
96 'AtomisticTreeRoot',
97 dict(
98 ID='1',
99 NumProperties='40',
100 NumChildren='1',
101 ),
102 )
103 SetChild(
104 ATR,
105 'Property',
106 dict(
107 DefinedOn='ClassicalEnergyHolder',
108 Name='AngleEnergy',
109 Type='Double',
110 ),
111 )
112 SetChild(
113 ATR,
114 'Property',
115 dict(
116 DefinedOn='ClassicalEnergyHolder',
117 Name='BendBendEnergy',
118 Type='Double',
119 ),
120 )
121 SetChild(
122 ATR,
123 'Property',
124 dict(
125 DefinedOn='ClassicalEnergyHolder',
126 Name='BendTorsionBendEnergy',
127 Type='Double',
128 ),
129 )
130 SetChild(
131 ATR,
132 'Property',
133 dict(
134 DefinedOn='ClassicalEnergyHolder',
135 Name='BondEnergy',
136 Type='Double',
137 ),
138 )
139 SetChild(
140 ATR,
141 'Property',
142 dict(
143 DefinedOn='Atom',
144 Name='EFGAsymmetry',
145 Type='Double',
146 ),
147 )
148 SetChild(
149 ATR,
150 'Property',
151 dict(
152 DefinedOn='Atom',
153 Name='EFGQuadrupolarCoupling',
154 Type='Double',
155 ),
156 )
157 SetChild(
158 ATR,
159 'Property',
160 dict(
161 DefinedOn='ClassicalEnergyHolder',
162 Name='ElectrostaticEnergy',
163 Type='Double',
164 ),
165 )
166 SetChild(
167 ATR,
168 'Property',
169 dict(
170 DefinedOn='GrowthFace',
171 Name='FaceMillerIndex',
172 Type='MillerIndex',
173 ),
174 )
175 SetChild(
176 ATR,
177 'Property',
178 dict(
179 DefinedOn='GrowthFace',
180 Name='FacetTransparency',
181 Type='Float',
182 ),
183 )
184 SetChild(
185 ATR,
186 'Property',
187 dict(
188 DefinedOn='Bondable',
189 Name='Force',
190 Type='CoDirection',
191 ),
192 )
193 SetChild(
194 ATR,
195 'Property',
196 dict(
197 DefinedOn='ClassicalEnergyHolder',
198 Name='HydrogenBondEnergy',
199 Type='Double',
200 ),
201 )
202 SetChild(
203 ATR,
204 'Property',
205 dict(
206 DefinedOn='Bondable',
207 Name='ImportOrder',
208 Type='UnsignedInteger',
209 ),
210 )
211 SetChild(
212 ATR,
213 'Property',
214 dict(
215 DefinedOn='ClassicalEnergyHolder',
216 Name='InversionEnergy',
217 Type='Double',
218 ),
219 )
220 SetChild(
221 ATR,
222 'Property',
223 dict(
224 DefinedOn='Atom',
225 Name='IsBackboneAtom',
226 Type='Boolean',
227 ),
228 )
229 SetChild(
230 ATR,
231 'Property',
232 dict(
233 DefinedOn='Atom',
234 Name='IsChiralCenter',
235 Type='Boolean',
236 ),
237 )
238 SetChild(
239 ATR,
240 'Property',
241 dict(
242 DefinedOn='Atom',
243 Name='IsOutOfPlane',
244 Type='Boolean',
245 ),
246 )
247 SetChild(
248 ATR,
249 'Property',
250 dict(
251 DefinedOn='BestFitLineMonitor',
252 Name='LineExtentPadding',
253 Type='Double',
254 ),
255 )
256 SetChild(
257 ATR,
258 'Property',
259 dict(
260 DefinedOn='Linkage',
261 Name='LinkageGroupName',
262 Type='String',
263 ),
264 )
265 SetChild(
266 ATR,
267 'Property',
268 dict(
269 DefinedOn='PropertyList',
270 Name='ListIdentifier',
271 Type='String',
272 ),
273 )
274 SetChild(
275 ATR,
276 'Property',
277 dict(
278 DefinedOn='Atom',
279 Name='NMRShielding',
280 Type='Double',
281 ),
282 )
283 SetChild(
284 ATR,
285 'Property',
286 dict(
287 DefinedOn='ClassicalEnergyHolder',
288 Name='NonBondEnergy',
289 Type='Double',
290 ),
291 )
292 SetChild(
293 ATR,
294 'Property',
295 dict(
296 DefinedOn='Bondable',
297 Name='NormalMode',
298 Type='Direction',
299 ),
300 )
301 SetChild(
302 ATR,
303 'Property',
304 dict(
305 DefinedOn='Bondable',
306 Name='NormalModeFrequency',
307 Type='Double',
308 ),
309 )
310 SetChild(
311 ATR,
312 'Property',
313 dict(
314 DefinedOn='Bondable',
315 Name='OrbitalCutoffRadius',
316 Type='Double',
317 ),
318 )
319 SetChild(
320 ATR,
321 'Property',
322 dict(
323 DefinedOn='BestFitPlaneMonitor',
324 Name='PlaneExtentPadding',
325 Type='Double',
326 ),
327 )
328 SetChild(
329 ATR,
330 'Property',
331 dict(
332 DefinedOn='ClassicalEnergyHolder',
333 Name='PotentialEnergy',
334 Type='Double',
335 ),
336 )
337 SetChild(
338 ATR,
339 'Property',
340 dict(
341 DefinedOn='ScalarFieldBase',
342 Name='QuantizationValue',
343 Type='Double',
344 ),
345 )
346 SetChild(
347 ATR,
348 'Property',
349 dict(
350 DefinedOn='ClassicalEnergyHolder',
351 Name='RestraintEnergy',
352 Type='Double',
353 ),
354 )
355 SetChild(
356 ATR,
357 'Property',
358 dict(
359 DefinedOn='ClassicalEnergyHolder',
360 Name='SeparatedStretchStretchEnergy',
361 Type='Double',
362 ),
363 )
364 SetChild(
365 ATR,
366 'Property',
367 dict(
368 DefinedOn='Trajectory',
369 Name='SimulationStep',
370 Type='Integer',
371 ),
372 )
373 SetChild(
374 ATR,
375 'Property',
376 dict(
377 DefinedOn='ClassicalEnergyHolder',
378 Name='StretchBendStretchEnergy',
379 Type='Double',
380 ),
381 )
382 SetChild(
383 ATR,
384 'Property',
385 dict(
386 DefinedOn='ClassicalEnergyHolder',
387 Name='StretchStretchEnergy',
388 Type='Double',
389 ),
390 )
391 SetChild(
392 ATR,
393 'Property',
394 dict(
395 DefinedOn='ClassicalEnergyHolder',
396 Name='StretchTorsionStretchEnergy',
397 Type='Double',
398 ),
399 )
400 SetChild(
401 ATR,
402 'Property',
403 dict(
404 DefinedOn='ClassicalEnergyHolder',
405 Name='TorsionBendBendEnergy',
406 Type='Double',
407 ),
408 )
409 SetChild(
410 ATR,
411 'Property',
412 dict(
413 DefinedOn='ClassicalEnergyHolder',
414 Name='TorsionEnergy',
415 Type='Double',
416 ),
417 )
418 SetChild(
419 ATR,
420 'Property',
421 dict(
422 DefinedOn='ClassicalEnergyHolder',
423 Name='TorsionStretchEnergy',
424 Type='Double',
425 ),
426 )
427 SetChild(
428 ATR,
429 'Property',
430 dict(
431 DefinedOn='ClassicalEnergyHolder',
432 Name='ValenceCrossTermEnergy',
433 Type='Double',
434 ),
435 )
436 SetChild(
437 ATR,
438 'Property',
439 dict(
440 DefinedOn='ClassicalEnergyHolder',
441 Name='ValenceDiagonalEnergy',
442 Type='Double',
443 ),
444 )
445 SetChild(
446 ATR,
447 'Property',
448 dict(
449 DefinedOn='ClassicalEnergyHolder',
450 Name='VanDerWaalsEnergy',
451 Type='Double',
452 ),
453 )
454 SetChild(
455 ATR,
456 'Property',
457 dict(
458 DefinedOn='SymmetrySystem',
459 Name='_Stress',
460 Type='Matrix',
461 ),
462 )
463 return ATR, XSD
466def _write_xsd_html(images, connectivity=None):
467 ATR, XSD = SetBasicChilds()
468 natoms = len(images[0])
469 atom_element = images[0].get_chemical_symbols()
470 atom_cell = images[0].get_cell()
471 atom_positions = images[0].get_positions()
472 # Set up bonds
473 if connectivity is not None:
474 bonds = connectivity2bonds(connectivity)
475 else:
476 bonds = []
478 nbonds = len(bonds)
480 # non-periodic system
481 if not images[0].pbc.all():
482 Molecule = SetChild(
483 ATR,
484 'Molecule',
485 dict(
486 ID='2',
487 NumChildren=str(natoms + nbonds),
488 Name='Lattice="1.0',
489 ),
490 )
491 # writing images[0]
492 for x in range(natoms):
493 Props = dict(
494 ID=str(x + 3),
495 Name=(atom_element[x] + str(x + 1)),
496 UserID=str(x + 1),
497 DisplayStyle=CPK_or_BnS(atom_element[x]),
498 XYZ=','.join('%1.16f' % xi for xi in atom_positions[x]),
499 Components=atom_element[x],
500 )
501 bondstr = []
502 for i, bond in enumerate(bonds):
503 if x in bond:
504 bondstr.append(str(i + 3 + natoms))
505 if bondstr:
506 Props['Connections'] = ','.join(bondstr)
507 SetChild(Molecule, 'Atom3d', Props)
508 for x in range(nbonds):
509 SetChild(
510 Molecule,
511 'Bond',
512 dict(
513 ID=str(x + 3 + natoms),
514 Connects='%i,%i' % (bonds[x][0] + 3, bonds[x][1] + 3),
515 ),
516 )
517 # periodic system
518 else:
519 atom_positions = np.dot(atom_positions, np.linalg.inv(atom_cell))
520 Props = dict(
521 ID='2',
522 Mapping='3',
523 Children=','.join(map(str, range(4, natoms + nbonds + 5))),
524 Normalized='1',
525 Name='SymmSys',
526 UserID=str(natoms + 18),
527 XYZ='0.00000000000000,0.00000000000000,0.000000000000000',
528 OverspecificationTolerance='0.05',
529 PeriodicDisplayType='Original',
530 )
531 SymmSys = SetChild(ATR, 'SymmetrySystem', Props)
533 Props = dict(
534 ID=str(natoms + nbonds + 5),
535 SymmetryDefinition=str(natoms + 4),
536 ActiveSystem='2',
537 NumFamilies='1',
538 OwnsTotalConstraintMapping='1',
539 TotalConstraintMapping='3',
540 )
541 MappngSet = SetChild(SymmSys, 'MappingSet', Props)
543 Props = dict(ID=str(natoms + nbonds + 6), NumImageMappings='0')
544 MappngFamily = SetChild(MappngSet, 'MappingFamily', Props)
546 Props = dict(
547 ID=str(natoms + len(bonds) + 7),
548 Element='1,0,0,0,0,1,0,0,0,0,1,0',
549 Constraint='1,0,0,0,0,1,0,0,0,0,1,0',
550 MappedObjects=','.join(map(str, range(4, natoms + len(bonds) + 4))),
551 DefectObjects='%i,%i' % (natoms + nbonds + 4, natoms + nbonds + 8),
552 NumImages=str(natoms + len(bonds)),
553 NumDefects='2',
554 )
555 IdentMappng = SetChild(MappngFamily, 'IdentityMapping', Props)
557 SetChild(MappngFamily, 'MappingRepairs', {'NumRepairs': '0'})
559 # writing atoms
560 for x in range(natoms):
561 Props = dict(
562 ID=str(x + 4),
563 Mapping=str(natoms + len(bonds) + 7),
564 Parent='2',
565 Name=(atom_element[x] + str(x + 1)),
566 UserID=str(x + 1),
567 DisplayStyle=CPK_or_BnS(atom_element[x]),
568 Components=atom_element[x],
569 XYZ=','.join(['%1.16f' % xi for xi in atom_positions[x]]),
570 )
571 bondstr = []
572 for i, bond in enumerate(bonds):
573 if x in bond:
574 bondstr.append(str(i + 4 * natoms + 1))
575 if bondstr:
576 Props['Connections'] = ','.join(bondstr)
577 SetChild(IdentMappng, 'Atom3d', Props)
579 for x in range(len(bonds)):
580 SetChild(
581 IdentMappng,
582 'Bond',
583 dict(
584 ID=str(x + 4 + natoms + 1),
585 Mapping=str(natoms + len(bonds) + 7),
586 Parent='2',
587 Connects='%i,%i' % (bonds[x][0] + 4, bonds[x][1] + 4),
588 ),
589 )
591 Props = dict(
592 ID=str(natoms + 4),
593 Parent='2',
594 Children=str(natoms + len(bonds) + 8),
595 DisplayStyle='Solid',
596 XYZ='0.00,0.00,0.00',
597 Color='0,0,0,0',
598 AVector=','.join(['%1.16f' % atom_cell[0, x] for x in range(3)]),
599 BVector=','.join(['%1.16f' % atom_cell[1, x] for x in range(3)]),
600 CVector=','.join(['%1.16f' % atom_cell[2, x] for x in range(3)]),
601 OrientationBase='C along Z, B in YZ plane',
602 Centering='3D Primitive-Centered',
603 Lattice='3D Triclinic',
604 GroupName='GroupName',
605 Operators='1,0,0,0,0,1,0,0,0,0,1,0',
606 DisplayRange='0,1,0,1,0,1',
607 LineThickness='2',
608 CylinderRadius='0.2',
609 LabelAxes='1',
610 ActiveSystem='2',
611 ITNumber='1',
612 LongName='P 1',
613 Qualifier='Origin-1',
614 SchoenfliesName='C1-1',
615 System='Triclinic',
616 Class='1',
617 )
618 SetChild(IdentMappng, 'SpaceGroup', Props)
620 SetChild(
621 IdentMappng,
622 'ReciprocalLattice3D',
623 dict(
624 ID=str(natoms + len(bonds) + 8),
625 Parent=str(natoms + 4),
626 ),
627 )
629 SetChild(
630 MappngSet,
631 'InfiniteMapping',
632 dict(
633 ID='3',
634 Element='1,0,0,0,0,1,0,0,0,0,1,0',
635 MappedObjects='2',
636 ),
637 )
639 return XSD, ATR
642@writer
643def write_xsd(fd, images, connectivity=None):
644 """Takes Atoms object, and write materials studio file
645 atoms: Atoms object
646 filename: path of the output file
647 connectivity: number of atoms by number of atoms matrix for connectivity
648 between atoms (0 not connected, 1 connected)
650 note: material studio file cannot use a partial periodic system. If partial
651 perodic system was inputted, full periodicity was assumed.
652 """
653 if hasattr(images, 'get_positions'):
654 images = [images]
656 XSD, _ATR = _write_xsd_html(images, connectivity)
658 # Return a pretty-printed XML string for the Element.
659 rough_string = ET.tostring(XSD, 'utf-8')
660 reparsed = minidom.parseString(rough_string)
661 Document = reparsed.toprettyxml(indent='\t')
663 fd.write(Document)