Coverage for ase/constraints/fixed_line.py: 100.00%

17 statements  

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

1from ase.constraints.constraint import ( 

2 IndexedConstraint, 

3 _normalize, 

4 _projection, 

5) 

6 

7 

8class FixedLine(IndexedConstraint): 

9 """ 

10 Constrain an atom index or a list of atom indices to move on a line only. 

11 

12 The line is defined by its vector *direction* 

13 """ 

14 

15 def __init__(self, indices, direction): 

16 """Constrain chosen atoms. 

17 

18 Parameters 

19 ---------- 

20 indices : int or list of int 

21 Index or indices for atoms that should be constrained 

22 direction : list of 3 int 

23 Direction of the vector defining the line 

24 

25 Examples 

26 -------- 

27 Fix all Copper atoms to only move in the x-direction: 

28 

29 >>> from ase.build import bulk 

30 >>> atoms = bulk('Cu', 'fcc', a=3.6, cubic = True) 

31 >>> from ase.constraints import FixedLine 

32 >>> c = FixedLine( 

33 ... indices=[atom.index for atom in atoms if atom.symbol == 'Cu'], 

34 ... direction=[1, 0, 0], 

35 ... ) 

36 >>> atoms.set_constraint(c) 

37 

38 or constrain a single atom with the index 0 to move in the z-direction: 

39 

40 >>> c = FixedLine(indices=0, direction=[0, 0, 1]) 

41 >>> atoms.set_constraint(c) 

42 """ 

43 super().__init__(indices) 

44 self.dir = _normalize(direction) 

45 

46 def adjust_positions(self, atoms, newpositions): 

47 step = newpositions[self.index] - atoms.positions[self.index] 

48 projection = _projection(step, self.dir) 

49 newpositions[self.index] = atoms.positions[self.index] + projection 

50 

51 def adjust_forces(self, atoms, forces): 

52 forces[self.index] = _projection(forces[self.index], self.dir) 

53 

54 def get_removed_dof(self, atoms): 

55 return 2 * len(self.index) 

56 

57 def __repr__(self): 

58 return f'FixedLine(indices={self.index}, {self.dir.tolist()})' 

59 

60 def todict(self): 

61 return { 

62 'name': 'FixedLine', 

63 'kwargs': { 

64 'indices': self.index.tolist(), 

65 'direction': self.dir.tolist(), 

66 }, 

67 }