View Javadoc
1   // ******************************************************************************
2   //
3   // Title:       Force Field X.
4   // Description: Force Field X - Software for Molecular Biophysics.
5   // Copyright:   Copyright (c) Michael J. Schnieders 2001-2025.
6   //
7   // This file is part of Force Field X.
8   //
9   // Force Field X is free software; you can redistribute it and/or modify it
10  // under the terms of the GNU General Public License version 3 as published by
11  // the Free Software Foundation.
12  //
13  // Force Field X is distributed in the hope that it will be useful, but WITHOUT
14  // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
16  // details.
17  //
18  // You should have received a copy of the GNU General Public License along with
19  // Force Field X; if not, write to the Free Software Foundation, Inc., 59 Temple
20  // Place, Suite 330, Boston, MA 02111-1307 USA
21  //
22  // Linking this library statically or dynamically with other modules is making a
23  // combined work based on this library. Thus, the terms and conditions of the
24  // GNU General Public License cover the whole combination.
25  //
26  // As a special exception, the copyright holders of this library give you
27  // permission to link this library with independent modules to produce an
28  // executable, regardless of the license terms of these independent modules, and
29  // to copy and distribute the resulting executable under terms of your choice,
30  // provided that you also meet, for each linked independent module, the terms
31  // and conditions of the license of that module. An independent module is a
32  // module which is not derived from or based on this library. If you modify this
33  // library, you may extend this exception to your version of the library, but
34  // you are not obligated to do so. If you do not wish to do so, delete this
35  // exception statement from your version.
36  //
37  // ******************************************************************************
38  package ffx.potential.cli;
39  
40  import ffx.potential.MolecularAssembly;
41  import ffx.potential.bonded.Atom;
42  import ffx.potential.bonded.Residue;
43  import picocli.CommandLine.ArgGroup;
44  import picocli.CommandLine.Option;
45  
46  import javax.annotation.Nonnull;
47  import javax.annotation.Nullable;
48  import java.util.ArrayList;
49  import java.util.List;
50  import java.util.function.BiConsumer;
51  import java.util.logging.Logger;
52  
53  import static ffx.utilities.StringUtils.parseAtomRanges;
54  import static ffx.utilities.StringUtils.parseResidueString;
55  
56  /**
57   * Represents command line options for scripts that support atom selections.
58   *
59   * @author Michael J. Schnieders
60   * @since 1.0
61   */
62  public class AtomSelectionOptions {
63  
64    private static final Logger logger = Logger.getLogger(AtomSelectionOptions.class.getName());
65  
66    /**
67     * The ArgGroup keeps the Atom Selection Options together when printing help.
68     */
69    @ArgGroup(heading = "%n Atom Selection Options%n", validate = false)
70    private final AtomSelectionOptionGroup group = new AtomSelectionOptionGroup();
71  
72    public static void actOnAtoms(@Nonnull MolecularAssembly assembly, @Nullable String selection,
73                                  @Nonnull BiConsumer<Atom, Boolean> action, @Nonnull String description) {
74      if (selection == null || selection.equalsIgnoreCase("")) {
75        // Empty or null string -- no changes.
76        return;
77      }
78  
79      Atom[] atoms = assembly.getAtomArray();
80  
81      // No atoms selected.
82      if (selection.equalsIgnoreCase("NONE")) {
83        for (Atom atom : atoms) {
84          action.accept(atom, false);
85        }
86        logger.info(" No atoms are " + description + ".\n");
87        return;
88      }
89  
90      // All atoms selected
91      if (selection.equalsIgnoreCase("ALL")) {
92        for (Atom atom : atoms) {
93          action.accept(atom, true);
94        }
95        logger.info(" All atoms are " + description + ".\n");
96        return;
97      }
98  
99      // A range(s) of atoms are active.
100     int nAtoms = atoms.length;
101     for (Atom atom : atoms) {
102       action.accept(atom, false);
103     }
104 
105     List<Integer> atomRanges = parseAtomRanges(description, selection, nAtoms);
106     for (int i : atomRanges) {
107       action.accept(atoms[i], true);
108     }
109     logger.info("\n " + description + " atoms set to: " + selection);
110 
111   }
112 
113   public static void actOnResidueAtoms(@Nonnull MolecularAssembly assembly, @Nullable String selection,
114                                 @Nonnull BiConsumer<Atom, Boolean> action, String description) {
115     if (selection == null || selection.equalsIgnoreCase("")) {
116       // Empty or null string -- no changes.
117       return;
118     }
119 
120     Atom[] atoms = assembly.getAtomArray();
121 
122     // No atoms selected.
123     if (selection.equalsIgnoreCase("NONE")) {
124       for (Atom atom : atoms) {
125         action.accept(atom, false);
126       }
127       logger.info(" No residues are " + description + ".\n");
128       return;
129     }
130 
131     // All atoms selected
132     if (selection.equalsIgnoreCase("ALL")) {
133       for (Atom atom : atoms) {
134         action.accept(atom, true);
135       }
136       logger.info(" All residues (and atoms) are " + description + ".\n");
137       return;
138     }
139 
140     // A subset of atoms is active.
141     for (Atom atom : atoms) {
142       action.accept(atom, false);
143     }
144 
145     // String for logging the selected residues and atoms
146     StringBuilder seleRes = new StringBuilder();
147     StringBuilder seleAtoms = new StringBuilder();
148 
149     int nResidues = assembly.getResidueList().size();
150     List<String> resList = parseResidueString(description, selection, nResidues);
151     assert resList.size() % 2 == 0;
152 
153     for (int i=0; i < resList.size(); i=i+2) {
154       String chain = resList.get(i);
155       int resid = Integer.parseInt(resList.get(i+1));
156 
157       List<Atom> atomList = new ArrayList<>();
158 
159       Residue res = assembly.getChain(chain).getResidue(resid);
160       seleRes.append(res.toFormattedString(true, true)).append(",");
161       if (res.getResidueType() == Residue.ResidueType.AA) {
162         atomList = res.getSideChainAtoms(); // use side chain atoms if for amino acids
163       } else if (res.getResidueType() == Residue.ResidueType.NA) {
164         atomList = res.getBackboneAtoms(); // use 'backbone' atoms which correspond to the nucleobase for nucleic acids
165       }
166 
167       // Apply desired function for selected atoms in the selected residues
168       for (Atom atom : atomList) {
169         seleAtoms.append(atom.getIndex()).append(",");
170         action.accept(atom, true);
171       }
172     }
173 
174     logger.info("\n " + description + " residues are: " + seleRes.substring(0, seleRes.length()-1));
175     logger.info(" " + description + " atoms set to: " + seleAtoms.substring(0, seleAtoms.length()-1));
176   }
177 
178   /**
179    * --aa or --activeAtoms Ranges of active atoms [NONE, ALL, Range(s): 1-3,6-N].
180    *
181    * @return Returns active atoms.
182    */
183   public String getActiveAtoms() {
184     return group.activeAtoms;
185   }
186 
187   /**
188    * Set active atoms for a MolecularAssembly.
189    *
190    * @param molecularAssembly a {@link ffx.potential.MolecularAssembly} object.
191    */
192   public void setActiveAtoms(MolecularAssembly molecularAssembly) {
193     // First, evaluate the inactive atom selection.
194     setInactive(molecularAssembly);
195 
196     // Second, evaluate the active atom selection, which takes precedence over the inactive flag.
197     setActive(molecularAssembly);
198   }
199 
200   /**
201    * --ia or --inactiveAtoms Ranges of inactive atoms [NONE, ALL, Range(s): 1-3,6-N].
202    *
203    * @return Returns inactive atoms.
204    */
205   public String getInactiveAtoms() {
206     return group.inactiveAtoms;
207   }
208 
209   /**
210    * Check if either the active or inactive atom selection is set.
211    *
212    * @return True if one of the fields is not empty.
213    */
214   public boolean isAtomSelectionSet() {
215     if (group.activeAtoms != null && !group.activeAtoms.isEmpty()) {
216       return true;
217     }
218     return group.inactiveAtoms != null && !group.inactiveAtoms.isEmpty();
219   }
220 
221   private void setInactive(MolecularAssembly assembly) {
222     actOnAtoms(assembly, getInactiveAtoms(), (Atom a, Boolean b) -> a.setActive(!b), "Inactive");
223   }
224 
225   private void setActive(MolecularAssembly assembly) {
226     actOnAtoms(assembly, getActiveAtoms(), Atom::setActive, "Active");
227   }
228 
229   /**
230    * Collection of Atom Selection Options.
231    */
232   private static class AtomSelectionOptionGroup {
233 
234     /**
235      * --aa or --activeAtoms Ranges of active atoms [NONE, ALL, Range(s): 1-3,6-N].
236      */
237     @Option(names = {"--aa",
238         "--active"}, paramLabel = "<selection>", defaultValue = "",
239         description = "Ranges of active atoms [NONE, ALL, Range(s): 1-3,6-N].")
240     public String activeAtoms = "";
241 
242     /**
243      * --ia or --inactiveAtoms Ranges of inactive atoms [NONE, ALL, Range(s): 1-3,6-N].
244      */
245     @Option(names = {"--ia",
246         "--inactive"}, paramLabel = "<selection>", defaultValue = "",
247         description = "Ranges of inactive atoms [NONE, ALL, Range(s): 1-3,6-N].")
248     public String inactiveAtoms = "";
249   }
250 }