0
# Core Functionality
1
2
This document covers the core functionality of MDAnalysis, focusing on the fundamental classes and operations that form the foundation of molecular dynamics analysis workflows.
3
4
## Universe Class
5
6
The `Universe` class is the central object in MDAnalysis, representing a complete molecular system with both topology and coordinate information.
7
8
### Class Definition
9
10
```python { .api }
11
class Universe:
12
"""
13
The MDAnalysis Universe class ties a topology and trajectory together.
14
15
A Universe combines topology information (atoms, bonds, residues) with
16
coordinate data from one or more trajectory files.
17
"""
18
19
def __init__(self, topology, *coordinates, **kwargs):
20
"""
21
Create a Universe from topology and coordinate files.
22
23
Parameters
24
----------
25
topology : str or file-like or None
26
Topology file path or file-like object. Supported formats include
27
PSF, PDB, GRO, TPR, PRMTOP, and many others. Can be None to create
28
an empty Universe.
29
*coordinates : str or file-like, optional
30
Trajectory file(s) containing coordinate time series. Multiple
31
files will be concatenated. Supported formats include DCD, XTC,
32
TRR, NetCDF, and many others.
33
all_coordinates : bool, optional
34
Try to load all coordinate files found in the same directory.
35
Default is False.
36
guess_bonds : bool, optional
37
Whether to guess bonds from inter-atomic distances. Default is True.
38
vdwradii : dict, optional
39
Dictionary of van der Waals radii for bond guessing.
40
fudge_factor : float, optional
41
Tolerance factor for bond guessing (default 0.55).
42
is_anchor : bool, optional
43
Whether this Universe should be considered an anchor for
44
inter-Universe operations.
45
anchor_name : str, optional
46
Name for anchor Universe.
47
transformations : callable or list, optional
48
Transformation functions to apply on-the-fly.
49
in_memory : bool, optional
50
Whether to load trajectory into memory for faster access.
51
in_memory_step : int, optional
52
Step size for in-memory loading (default 1).
53
continuous : bool, optional
54
Whether to make coordinates continuous across periodic boundaries.
55
dt : float, optional
56
Time step between frames if not present in trajectory.
57
**kwargs
58
Additional keyword arguments passed to format-specific readers.
59
60
Examples
61
--------
62
>>> u = Universe("topology.psf", "trajectory.dcd")
63
>>> u = Universe("system.pdb") # Single frame
64
>>> u = Universe("topol.tpr", "traj1.xtc", "traj2.xtc") # Multiple trajs
65
>>> u = Universe(None, n_atoms=1000) # Empty universe
66
"""
67
```
68
69
### Universe Properties
70
71
```python { .api }
72
class Universe:
73
@property
74
def atoms(self):
75
"""
76
All atoms in the Universe.
77
78
Returns
79
-------
80
AtomGroup
81
AtomGroup containing all atoms in the system.
82
"""
83
84
@property
85
def residues(self):
86
"""
87
All residues in the Universe.
88
89
Returns
90
-------
91
ResidueGroup
92
ResidueGroup containing all residues in the system.
93
"""
94
95
@property
96
def segments(self):
97
"""
98
All segments in the Universe.
99
100
Returns
101
-------
102
SegmentGroup
103
SegmentGroup containing all segments in the system.
104
"""
105
106
@property
107
def trajectory(self):
108
"""
109
Trajectory reader object associated with the Universe.
110
111
Returns
112
-------
113
ReaderBase
114
Trajectory reader providing access to coordinate frames.
115
"""
116
117
@property
118
def dimensions(self):
119
"""
120
Unit cell dimensions of the current frame.
121
122
Returns
123
-------
124
numpy.ndarray or None
125
Array of [a, b, c, alpha, beta, gamma] where a,b,c are box
126
lengths and alpha,beta,gamma are box angles. None if no
127
unit cell information is available.
128
"""
129
```
130
131
### Universe Methods
132
133
```python { .api }
134
class Universe:
135
def copy(self):
136
"""
137
Create an independent copy of the Universe.
138
139
Returns
140
-------
141
Universe
142
Deep copy of the Universe with independent trajectory.
143
144
Examples
145
--------
146
>>> u_copy = u.copy()
147
>>> u_copy.trajectory[10] # Navigate independently
148
"""
149
150
@classmethod
151
def empty(cls, n_atoms, n_residues=1, n_segments=1, atom_resindex=None,
152
residue_segindex=None, trajectory=False, velocities=False,
153
forces=False, **kwargs):
154
"""
155
Create an empty Universe with specified number of components.
156
157
Parameters
158
----------
159
n_atoms : int
160
Number of atoms to create.
161
n_residues : int, optional
162
Number of residues to create (default 1).
163
n_segments : int, optional
164
Number of segments to create (default 1).
165
atom_resindex : array-like, optional
166
Mapping of atoms to residues.
167
residue_segindex : array-like, optional
168
Mapping of residues to segments.
169
trajectory : bool, optional
170
Whether to create a trajectory (default False).
171
velocities : bool, optional
172
Whether to include velocity information (default False).
173
forces : bool, optional
174
Whether to include force information (default False).
175
176
Returns
177
-------
178
Universe
179
Empty Universe ready for data population.
180
181
Examples
182
--------
183
>>> u = Universe.empty(1000, n_residues=100)
184
>>> u.atoms.positions = np.random.random((1000, 3)) * 100
185
"""
186
187
def select_atoms(self, *args, **kwargs):
188
"""
189
Select atoms using the selection language.
190
191
Parameters
192
----------
193
*args : str
194
Selection string(s) in MDAnalysis selection language.
195
updating : bool, optional
196
Whether the selection should update when topology changes.
197
periodic : bool, optional
198
Whether to account for periodic boundary conditions in
199
geometric selections.
200
rtol : float, optional
201
Relative tolerance for geometric selections.
202
atol : float, optional
203
Absolute tolerance for geometric selections.
204
205
Returns
206
-------
207
AtomGroup
208
Selected atoms matching the criteria.
209
210
Examples
211
--------
212
>>> protein = u.select_atoms("protein")
213
>>> ca_atoms = u.select_atoms("name CA")
214
>>> near_ligand = u.select_atoms("around 5.0 resname LIG")
215
>>> complex_sel = u.select_atoms("protein and not backbone")
216
"""
217
218
def load_new(self, filename, format=None, in_memory=False, **kwargs):
219
"""
220
Load a new trajectory into the Universe.
221
222
Parameters
223
----------
224
filename : str or file-like
225
Path to trajectory file or file-like object.
226
format : str, optional
227
File format, guessed from extension if not provided.
228
in_memory : bool, optional
229
Whether to load trajectory into memory.
230
**kwargs
231
Additional arguments for trajectory reader.
232
233
Examples
234
--------
235
>>> u.load_new("new_trajectory.xtc")
236
>>> u.load_new("production.dcd", in_memory=True)
237
"""
238
239
def transfer_to_memory(self, start=None, stop=None, step=None,
240
verbose=False):
241
"""
242
Transfer trajectory frames to memory for faster access.
243
244
Parameters
245
----------
246
start : int, optional
247
First frame to transfer (default None for beginning).
248
stop : int, optional
249
Last frame to transfer (default None for end).
250
step : int, optional
251
Step size for frame transfer (default None for 1).
252
verbose : bool, optional
253
Whether to show progress (default False).
254
255
Examples
256
--------
257
>>> u.transfer_to_memory() # Load all frames
258
>>> u.transfer_to_memory(0, 1000, 10) # Every 10th frame
259
"""
260
261
@classmethod
262
def from_smiles(cls, smiles, sanitize=True, addHs=True,
263
generate_coordinates=True, numConfs=1,
264
rdkit_kwargs=None, **kwargs):
265
"""
266
Create a Universe from a SMILES string using RDKit.
267
268
Parameters
269
----------
270
smiles : str
271
SMILES string representation of the molecule.
272
sanitize : bool, optional
273
Whether to sanitize the molecule (default True).
274
addHs : bool, optional
275
Whether to add hydrogens to the molecule (default True).
276
generate_coordinates : bool, optional
277
Whether to generate 3D coordinates (default True).
278
numConfs : int, optional
279
Number of conformers to generate (default 1).
280
rdkit_kwargs : dict, optional
281
Additional arguments for RDKit conformer generation.
282
**kwargs
283
Additional arguments for Universe creation.
284
285
Returns
286
-------
287
Universe
288
Universe object with topology and coordinates from SMILES.
289
290
Examples
291
--------
292
>>> u = Universe.from_smiles('CCO') # Ethanol
293
>>> u = Universe.from_smiles('c1ccccc1', numConfs=10) # Benzene conformers
294
"""
295
296
def add_TopologyAttr(self, topologyattr, values=None):
297
"""
298
Add a new topology attribute to the Universe.
299
300
Parameters
301
----------
302
topologyattr : str or TopologyAttr
303
Name of topology attribute or TopologyAttr object.
304
values : array-like, optional
305
Initial values for the attribute. If None, empty/zero values used.
306
307
Examples
308
--------
309
>>> u.add_TopologyAttr('tempfactors')
310
>>> u.add_TopologyAttr('charges', [0.5, -0.5, 0.0])
311
>>> u.atoms.tempfactors # Now available
312
"""
313
314
def del_TopologyAttr(self, topologyattr):
315
"""
316
Remove a topology attribute from the Universe.
317
318
Parameters
319
----------
320
topologyattr : str
321
Name of topology attribute to remove.
322
323
Examples
324
--------
325
>>> u.del_TopologyAttr('tempfactors')
326
"""
327
```
328
329
## AtomGroup Class
330
331
The `AtomGroup` class represents a collection of atoms and provides the primary interface for molecular analysis operations.
332
333
### Class Definition
334
335
```python { .api }
336
class AtomGroup:
337
"""
338
A group of atoms that can be used for analysis and manipulation.
339
340
AtomGroups are created through atom selection or by combining existing
341
groups. They provide methods for geometric analysis, transformations,
342
and property access.
343
"""
344
345
def __init__(self, indices, universe):
346
"""
347
Create an AtomGroup from atom indices.
348
349
Parameters
350
----------
351
indices : array-like
352
Indices of atoms to include in the group.
353
universe : Universe
354
Universe object containing the atoms.
355
356
Note
357
----
358
AtomGroups are typically created through Universe.select_atoms()
359
rather than direct instantiation.
360
"""
361
```
362
363
### AtomGroup Properties
364
365
```python { .api }
366
class AtomGroup:
367
@property
368
def positions(self):
369
"""
370
Coordinates of atoms in the current frame.
371
372
Returns
373
-------
374
numpy.ndarray
375
Array of shape (n_atoms, 3) containing x,y,z coordinates
376
in Angstrom units.
377
378
Examples
379
--------
380
>>> coords = protein.positions
381
>>> protein.positions += [10.0, 0.0, 0.0] # Translate
382
"""
383
384
@property
385
def velocities(self):
386
"""
387
Velocities of atoms in the current frame.
388
389
Returns
390
-------
391
numpy.ndarray or None
392
Array of shape (n_atoms, 3) containing velocity components
393
in Angstrom/ps units. None if no velocity data available.
394
"""
395
396
@property
397
def forces(self):
398
"""
399
Forces on atoms in the current frame.
400
401
Returns
402
-------
403
numpy.ndarray or None
404
Array of shape (n_atoms, 3) containing force components.
405
None if no force data available.
406
"""
407
408
@property
409
def masses(self):
410
"""
411
Masses of atoms in the group.
412
413
Returns
414
-------
415
numpy.ndarray
416
Array of atomic masses in amu units.
417
"""
418
419
@property
420
def charges(self):
421
"""
422
Partial charges of atoms in the group.
423
424
Returns
425
-------
426
numpy.ndarray or None
427
Array of atomic charges in elementary charge units.
428
None if no charge data available.
429
"""
430
431
@property
432
def names(self):
433
"""
434
Atom names in the group.
435
436
Returns
437
-------
438
numpy.ndarray
439
Array of string atom names (e.g., 'CA', 'CB', 'N').
440
"""
441
442
@property
443
def n_atoms(self):
444
"""
445
Number of atoms in the group.
446
447
Returns
448
-------
449
int
450
Count of atoms in this AtomGroup.
451
"""
452
453
@property
454
def residues(self):
455
"""
456
Unique residues containing atoms from this group.
457
458
Returns
459
-------
460
ResidueGroup
461
ResidueGroup containing the unique residues.
462
"""
463
464
@property
465
def segments(self):
466
"""
467
Unique segments containing atoms from this group.
468
469
Returns
470
-------
471
SegmentGroup
472
SegmentGroup containing the unique segments.
473
"""
474
```
475
476
### Geometric Analysis Methods
477
478
```python { .api }
479
class AtomGroup:
480
def center_of_mass(self, wrap=False, unwrap=False, compound="group"):
481
"""
482
Calculate center of mass of the group.
483
484
Parameters
485
----------
486
wrap : bool, optional
487
Whether to wrap coordinates into primary unit cell.
488
unwrap : bool, optional
489
Whether to unwrap coordinates across periodic boundaries.
490
compound : {'group', 'segments', 'residues', 'molecules', 'fragments'}
491
How to treat the group for wrapping/unwrapping.
492
493
Returns
494
-------
495
numpy.ndarray
496
Center of mass coordinates as 3-element array.
497
498
Examples
499
--------
500
>>> com = protein.center_of_mass()
501
>>> com_wrapped = protein.center_of_mass(wrap=True)
502
"""
503
504
def center_of_geometry(self, wrap=False, unwrap=False, compound="group"):
505
"""
506
Calculate geometric center of the group.
507
508
Parameters
509
----------
510
wrap : bool, optional
511
Whether to wrap coordinates into primary unit cell.
512
unwrap : bool, optional
513
Whether to unwrap coordinates across periodic boundaries.
514
compound : {'group', 'segments', 'residues', 'molecules', 'fragments'}
515
How to treat the group for wrapping/unwrapping.
516
517
Returns
518
-------
519
numpy.ndarray
520
Geometric center coordinates as 3-element array.
521
"""
522
523
def radius_of_gyration(self, wrap=False, **kwargs):
524
"""
525
Calculate radius of gyration of the group.
526
527
Parameters
528
----------
529
wrap : bool, optional
530
Whether to wrap coordinates into primary unit cell.
531
**kwargs
532
Additional arguments for coordinate processing.
533
534
Returns
535
-------
536
float
537
Radius of gyration in Angstrom units.
538
539
Examples
540
--------
541
>>> rgyr = protein.radius_of_gyration()
542
>>> print(f"Radius of gyration: {rgyr:.2f} Å")
543
"""
544
545
def principal_axes(self, wrap=False):
546
"""
547
Calculate principal axes of the coordinate distribution.
548
549
Parameters
550
----------
551
wrap : bool, optional
552
Whether to wrap coordinates into primary unit cell.
553
554
Returns
555
-------
556
numpy.ndarray
557
Array of shape (3, 3) where rows are principal axes
558
ordered by decreasing eigenvalue.
559
"""
560
561
def moment_of_inertia(self, wrap=False):
562
"""
563
Calculate moment of inertia tensor.
564
565
Parameters
566
----------
567
wrap : bool, optional
568
Whether to wrap coordinates into primary unit cell.
569
570
Returns
571
-------
572
numpy.ndarray
573
3x3 moment of inertia tensor.
574
"""
575
576
def bbox(self, wrap=False):
577
"""
578
Calculate bounding box of atomic coordinates.
579
580
Parameters
581
----------
582
wrap : bool, optional
583
Whether to wrap coordinates into primary unit cell.
584
585
Returns
586
-------
587
numpy.ndarray
588
Array of shape (2, 3) containing minimum and maximum
589
coordinates: [[xmin, ymin, zmin], [xmax, ymax, zmax]].
590
"""
591
592
def bsphere(self, wrap=False):
593
"""
594
Calculate bounding sphere of atomic coordinates.
595
596
Parameters
597
----------
598
wrap : bool, optional
599
Whether to wrap coordinates into primary unit cell.
600
601
Returns
602
-------
603
tuple
604
(center, radius) where center is 3-element array of
605
sphere center and radius is the sphere radius.
606
"""
607
```
608
609
### Group Operations
610
611
```python { .api }
612
class AtomGroup:
613
def __add__(self, other):
614
"""
615
Concatenate with another AtomGroup.
616
617
Parameters
618
----------
619
other : AtomGroup
620
AtomGroup to concatenate with.
621
622
Returns
623
-------
624
AtomGroup
625
New AtomGroup containing atoms from both groups.
626
627
Examples
628
--------
629
>>> combined = group1 + group2
630
>>> all_ca = ca_chain_a + ca_chain_b
631
"""
632
633
def __sub__(self, other):
634
"""
635
Remove atoms present in another AtomGroup.
636
637
Parameters
638
----------
639
other : AtomGroup
640
AtomGroup whose atoms should be removed.
641
642
Returns
643
-------
644
AtomGroup
645
New AtomGroup with specified atoms removed.
646
"""
647
648
def union(self, other):
649
"""
650
Return union of this group with another.
651
652
Parameters
653
----------
654
other : AtomGroup
655
AtomGroup to form union with.
656
657
Returns
658
-------
659
AtomGroup
660
New AtomGroup containing unique atoms from both groups.
661
"""
662
663
def intersection(self, other):
664
"""
665
Return intersection of this group with another.
666
667
Parameters
668
----------
669
other : AtomGroup
670
AtomGroup to intersect with.
671
672
Returns
673
-------
674
AtomGroup
675
New AtomGroup containing atoms present in both groups.
676
"""
677
678
def select_atoms(self, selection, **kwargs):
679
"""
680
Select a subset of atoms from this group.
681
682
Parameters
683
----------
684
selection : str
685
Selection string in MDAnalysis selection language.
686
**kwargs
687
Additional arguments for selection.
688
689
Returns
690
-------
691
AtomGroup
692
Subset of atoms matching the selection criteria.
693
694
Examples
695
--------
696
>>> ca_atoms = protein.select_atoms("name CA")
697
>>> backbone = protein.select_atoms("backbone")
698
"""
699
700
def split(self, level):
701
"""
702
Split group by connectivity or hierarchy level.
703
704
Parameters
705
----------
706
level : {'atoms', 'residues', 'segments', 'molecules', 'fragments'}
707
Level at which to split the group.
708
709
Returns
710
-------
711
list
712
List of AtomGroup objects split at specified level.
713
714
Examples
715
--------
716
>>> chains = protein.split('segments')
717
>>> fragments = system.split('fragments')
718
"""
719
720
def groupby(self, topattrs):
721
"""
722
Group atoms by topology attributes.
723
724
Parameters
725
----------
726
topattrs : str or list
727
Topology attribute name(s) to group by.
728
729
Returns
730
-------
731
dict
732
Dictionary mapping attribute values to AtomGroups.
733
734
Examples
735
--------
736
>>> by_resname = protein.groupby('resnames')
737
>>> by_element = system.groupby(['elements', 'names'])
738
"""
739
```
740
741
### Transformation Methods
742
743
```python { .api }
744
class AtomGroup:
745
def translate(self, t):
746
"""
747
Translate atomic coordinates by a vector.
748
749
Parameters
750
----------
751
t : array-like
752
Translation vector as 3-element array.
753
754
Examples
755
--------
756
>>> protein.translate([10.0, 0.0, 0.0]) # Move 10 Å along x
757
>>> protein.translate(center_of_mass) # Translate by COM
758
"""
759
760
def rotate(self, R, point=(0, 0, 0)):
761
"""
762
Rotate coordinates using rotation matrix.
763
764
Parameters
765
----------
766
R : array-like
767
3x3 rotation matrix.
768
point : array-like, optional
769
Point about which to rotate (default origin).
770
771
Examples
772
--------
773
>>> import scipy.spatial.transform as st
774
>>> R = st.Rotation.from_euler('z', 90, degrees=True).as_matrix()
775
>>> protein.rotate(R)
776
"""
777
778
def rotateby(self, angle, axis, point=None):
779
"""
780
Rotate by angle around axis.
781
782
Parameters
783
----------
784
angle : float
785
Rotation angle in degrees.
786
axis : array-like
787
Rotation axis as 3-element unit vector.
788
point : array-like, optional
789
Point about which to rotate (default group center).
790
791
Examples
792
--------
793
>>> protein.rotateby(45.0, [0, 0, 1]) # 45° around z-axis
794
"""
795
796
def transform(self, M):
797
"""
798
Apply transformation matrix to coordinates.
799
800
Parameters
801
----------
802
M : array-like
803
4x4 transformation matrix or 3x3 rotation matrix.
804
805
Examples
806
--------
807
>>> # Apply combined rotation and translation
808
>>> M = np.eye(4)
809
>>> M[:3, :3] = rotation_matrix
810
>>> M[:3, 3] = translation_vector
811
>>> protein.transform(M)
812
"""
813
814
def wrap(self, compound="atoms", center="com", box=None, inplace=True):
815
"""
816
Wrap coordinates into primary unit cell.
817
818
Parameters
819
----------
820
compound : {'atoms', 'group', 'segments', 'residues', 'molecules', 'fragments'}
821
How to wrap the coordinates.
822
center : {'com', 'cog'} or array-like
823
Point around which to center the wrapping.
824
box : array-like, optional
825
Unit cell dimensions (default from trajectory).
826
inplace : bool, optional
827
Whether to modify coordinates in place (default True).
828
829
Returns
830
-------
831
numpy.ndarray or None
832
Wrapped coordinates if inplace=False, otherwise None.
833
"""
834
835
def unwrap(self, compound="fragments", reference="com", inplace=True):
836
"""
837
Unwrap coordinates across periodic boundaries.
838
839
Parameters
840
----------
841
compound : {'atoms', 'group', 'segments', 'residues', 'molecules', 'fragments'}
842
How to unwrap the coordinates.
843
reference : {'com', 'cog'} or array-like
844
Reference point for unwrapping.
845
inplace : bool, optional
846
Whether to modify coordinates in place (default True).
847
848
Returns
849
-------
850
numpy.ndarray or None
851
Unwrapped coordinates if inplace=False, otherwise None.
852
"""
853
854
def center_of_geometry(self, wrap=False, unwrap=False, compound="group"):
855
"""
856
Calculate geometric center (centroid) of atoms.
857
858
Parameters
859
----------
860
wrap : bool, optional
861
Whether to wrap coordinates before calculation (default False)
862
unwrap : bool, optional
863
Whether to unwrap coordinates before calculation (default False)
864
compound : str, optional
865
How to treat the AtomGroup as a compound ('group', 'segments', etc.)
866
867
Returns
868
-------
869
numpy.ndarray
870
Geometric center coordinates [x, y, z]
871
872
Examples
873
--------
874
>>> centroid = protein.center_of_geometry()
875
>>> centroid = ligand.center_of_geometry(wrap=True)
876
"""
877
878
def bbox(self, wrap=False):
879
"""
880
Calculate bounding box of atomic coordinates.
881
882
Parameters
883
----------
884
wrap : bool, optional
885
Whether to wrap coordinates before calculation (default False)
886
887
Returns
888
-------
889
numpy.ndarray
890
Bounding box as [[xmin, ymin, zmin], [xmax, ymax, zmax]]
891
892
Examples
893
--------
894
>>> box = protein.bbox()
895
>>> dimensions = box[1] - box[0] # Width, height, depth
896
"""
897
898
def bsphere(self, wrap=False):
899
"""
900
Calculate bounding sphere of atomic coordinates.
901
902
Parameters
903
----------
904
wrap : bool, optional
905
Whether to wrap coordinates before calculation (default False)
906
907
Returns
908
-------
909
tuple
910
(center, radius) where center is numpy.ndarray and radius is float
911
912
Examples
913
--------
914
>>> center, radius = protein.bsphere()
915
>>> volume = (4/3) * np.pi * radius**3
916
"""
917
918
def get_connections(self, typename, outside=True):
919
"""
920
Get connectivity information (bonds, angles, dihedrals) for the group.
921
922
Parameters
923
----------
924
typename : str
925
Type of connection ('bonds', 'angles', 'dihedrals', 'impropers')
926
outside : bool, optional
927
Whether to include connections to atoms outside the group (default True)
928
929
Returns
930
-------
931
TopologyGroup
932
Group of connections of the specified type
933
934
Examples
935
--------
936
>>> bonds = protein.get_connections('bonds')
937
>>> angles = residue.get_connections('angles', outside=False)
938
"""
939
```
940
941
## ResidueGroup and SegmentGroup
942
943
These classes provide similar interfaces to `AtomGroup` but operate at the residue and segment levels respectively.
944
945
### ResidueGroup
946
947
```python { .api }
948
class ResidueGroup:
949
"""
950
A group of residues with aggregate properties and analysis methods.
951
"""
952
953
@property
954
def atoms(self):
955
"""
956
All atoms belonging to residues in this group.
957
958
Returns
959
-------
960
AtomGroup
961
AtomGroup containing all atoms from these residues.
962
"""
963
964
@property
965
def n_atoms(self):
966
"""
967
Total number of atoms in all residues.
968
969
Returns
970
-------
971
int
972
Sum of atoms across all residues in the group.
973
"""
974
975
@property
976
def resnames(self):
977
"""
978
Residue names in the group.
979
980
Returns
981
-------
982
numpy.ndarray
983
Array of residue names (e.g., 'ALA', 'GLY', 'PRO').
984
"""
985
986
@property
987
def resids(self):
988
"""
989
Residue IDs in the group.
990
991
Returns
992
-------
993
numpy.ndarray
994
Array of residue ID numbers.
995
"""
996
```
997
998
### SegmentGroup
999
1000
```python { .api }
1001
class SegmentGroup:
1002
"""
1003
A group of segments (chains/molecules) with aggregate properties.
1004
"""
1005
1006
@property
1007
def atoms(self):
1008
"""
1009
All atoms belonging to segments in this group.
1010
1011
Returns
1012
-------
1013
AtomGroup
1014
AtomGroup containing all atoms from these segments.
1015
"""
1016
1017
@property
1018
def residues(self):
1019
"""
1020
All residues belonging to segments in this group.
1021
1022
Returns
1023
-------
1024
ResidueGroup
1025
ResidueGroup containing all residues from these segments.
1026
"""
1027
1028
@property
1029
def segids(self):
1030
"""
1031
Segment IDs in the group.
1032
1033
Returns
1034
-------
1035
numpy.ndarray
1036
Array of segment ID strings.
1037
"""
1038
```
1039
1040
## Merge Function
1041
1042
```python { .api }
1043
def Merge(*args, **kwargs):
1044
"""
1045
Create a new Universe by merging existing AtomGroups.
1046
1047
Parameters
1048
----------
1049
*args : AtomGroup
1050
AtomGroups to merge into new Universe.
1051
**kwargs
1052
Additional arguments for Universe creation.
1053
1054
Returns
1055
-------
1056
Universe
1057
New Universe containing merged atoms with combined topology.
1058
1059
Examples
1060
--------
1061
>>> u1 = Universe("protein.pdb")
1062
>>> u2 = Universe("ligand.mol2")
1063
>>> complex_u = Merge(u1.atoms, u2.atoms)
1064
1065
>>> # Merge specific selections
1066
>>> protein = u.select_atoms("protein")
1067
>>> waters = u.select_atoms("resname SOL")
1068
>>> new_u = Merge(protein, waters)
1069
"""
1070
```
1071
1072
## Usage Examples
1073
1074
### Basic Universe Operations
1075
1076
```python { .api }
1077
# Create universe and basic selections
1078
u = mda.Universe("topology.psf", "trajectory.dcd")
1079
protein = u.select_atoms("protein")
1080
waters = u.select_atoms("resname SOL")
1081
1082
# Trajectory iteration
1083
for ts in u.trajectory:
1084
# Calculate properties for current frame
1085
protein_com = protein.center_of_mass()
1086
protein_rgyr = protein.radius_of_gyration()
1087
1088
# Check if protein is compact
1089
if protein_rgyr < 15.0:
1090
print(f"Frame {ts.frame}: Compact conformation")
1091
```
1092
1093
### Group Analysis Workflow
1094
1095
```python { .api }
1096
# Select and analyze binding site
1097
binding_site = u.select_atoms("resid 23 45 67 89 120")
1098
ligand = u.select_atoms("resname LIG")
1099
1100
# Calculate distances
1101
distances = []
1102
for ts in u.trajectory:
1103
# Distance between binding site and ligand centers
1104
bs_center = binding_site.center_of_geometry()
1105
lig_center = ligand.center_of_geometry()
1106
dist = np.linalg.norm(bs_center - lig_center)
1107
distances.append(dist)
1108
1109
# Group manipulation
1110
ca_atoms = protein.select_atoms("name CA")
1111
backbone = protein.select_atoms("backbone")
1112
sidechain = protein - backbone # Remove backbone atoms
1113
1114
# Split into chains
1115
chains = protein.split('segments')
1116
for i, chain in enumerate(chains):
1117
print(f"Chain {i}: {chain.n_atoms} atoms")
1118
```
1119
1120
### Coordinate Transformations
1121
1122
```python { .api }
1123
# Center protein at origin
1124
protein_center = protein.center_of_mass()
1125
protein.translate(-protein_center)
1126
1127
# Align protein with reference
1128
reference = u.select_atoms("name CA")
1129
mobile = protein.select_atoms("name CA")
1130
1131
# Calculate optimal rotation matrix (requires additional imports)
1132
from MDAnalysis.analysis.align import rotation_matrix
1133
R, rmsd = rotation_matrix(mobile.positions, reference.positions)
1134
protein.rotate(R)
1135
1136
# Wrap coordinates for visualization
1137
system = u.atoms
1138
system.wrap(compound="residues", center="com")
1139
```