def Run_ForceBalance(input_file, debug=False, continue_=False):
    """ Create instances of ForceBalance components and run the optimizer.

    The triumvirate, trifecta, or trinity of components are:
    - The force field
    - The objective function
    - The optimizer
    Cipher: "All I gotta do here is pull this plug... and there you have to watch Apoc die"
    Apoc: "TRINITY" *chunk*

    The force field is a class defined in forcefield.py.
    The objective function is a combination of target classes and a penalty function class.
    The optimizer is a class defined in this file.
    """
    try:
        ## The general options and target options that come from parsing the input file
        options, tgt_opts = parse_inputs(input_file)
        ## Set the continue_ option.
        if continue_: options['continue'] = True
        ## The force field component of the project
        forcefield = FF(options)
        ## The objective function
        objective = Objective(options, tgt_opts, forcefield)
        ## The optimizer component of the project
        optimizer = Optimizer(options, objective, forcefield)
        ## Actually run the optimizer.
        optimizer.Run()
    except:
        import traceback
        traceback.print_exc()
        if debug:
            import pdb
            pdb.post_mortem()
 def get_optimizer(self):
     """ Return the optimizer object """
     ## The general options and target options that come from parsing the input file
     self.logger.debug("Parsing inputs...\n")
     options, tgt_opts = parse_inputs(self.input_file)
     self.logger.debug("options:\n%s\n\ntgt_opts:\n%s\n\n" %
                       (str(options), str(tgt_opts)))
     assert isinstance(options,
                       dict), "Parser gave incorrect type for options"
     assert isinstance(tgt_opts,
                       list), "Parser gave incorrect type for tgt_opts"
     for target in tgt_opts:
         assert isinstance(
             target, dict), "Parser gave incorrect type for target dict"
     ## The force field component of the project
     forcefield = FF(options)
     assert isinstance(forcefield,
                       FF), "Expected forcebalance forcefield object"
     ## The objective function
     objective = Objective(options, tgt_opts, forcefield)
     assert isinstance(objective,
                       Objective), "Expected forcebalance objective object"
     ## The optimizer component of the project
     self.logger.debug("Creating optimizer: ")
     optimizer = Optimizer(options, objective, forcefield)
     assert isinstance(optimizer,
                       Optimizer), "Expected forcebalance optimizer object"
     self.logger.debug(str(optimizer) + "\n")
     return optimizer
    def test_liquid(self):
        """Check liquid target with existing simulation data"""
        # if not sys.version_info <= (2,7):
        #     self.skipTest("Existing pickle file only works with Python 3")

        print("Setting input file to 'single.in'")
        input_file = 'single.in'

        ## The general options and target options that come from parsing the input file
        print("Parsing inputs...")
        options, tgt_opts = parse_inputs(input_file)
        print("options:\n%s\n\ntgt_opts:\n%s\n\n" %
              (str(options), str(tgt_opts)))

        forcefield = FF(options)
        objective = Objective(options, tgt_opts, forcefield)
        ## The optimizer component of the project
        print("Creating optimizer: ")
        optimizer = Optimizer(options, objective, forcefield)
        assert isinstance(optimizer,
                          Optimizer), "Expected forcebalance optimizer object"
        print(str(optimizer))

        ## Actually run the optimizer.
        print("Done setting up! Running optimizer...")
        result = optimizer.Run()
        print("\nOptimizer finished. Final results:")
        print(str(result))

        liquid_obj_value = optimizer.Objective.ObjDict['Liquid']['x']
        assert liquid_obj_value < 20, "Liquid objective function should give < 20 (about 17.23) total value."
Exemple #4
0
    def energy_force_driver_all(self):
        """ Here we actually compute the interactions and return the
        energies and forces. I verified this to give the same answer
        as GROMACS. """

        M = []
        # Loop through the snapshots
        ThisFF = FF({'forcefield':['tip3p.xml'], 'ffdir':'', 'priors':{}},verbose=False)
        r_0   = ThisFF.pvals0[ThisFF.map['HarmonicBondForce.Bond/length/OW.HW']] * 10
        k_ij  = ThisFF.pvals0[ThisFF.map['HarmonicBondForce.Bond/k/OW.HW']]
        t_0   = ThisFF.pvals0[ThisFF.map['HarmonicAngleForce.Angle/angle/HW.OW.HW']] * 180 / np.pi
        k_ijk = ThisFF.pvals0[ThisFF.map['HarmonicAngleForce.Angle/k/HW.OW.HW']]
        q_o   = ThisFF.pvals0[ThisFF.map['NonbondedForce.Atom/charge/tip3p-O']]
        q_h   = ThisFF.pvals0[ThisFF.map['NonbondedForce.Atom/charge/tip3p-H']]
        sig   = ThisFF.pvals0[ThisFF.map['NonbondedForce.Atom/sigma/tip3p-O']]
        eps   = ThisFF.pvals0[ThisFF.map['NonbondedForce.Atom/epsilon/tip3p-O']]
        facel = 1389.35410

        for I in range(self.ns):
            xyz = self.mol.xyzs[I]
            Bond_Energy = 0.0
            Angle_Energy = 0.0
            VdW_Energy = 0.0
            Coulomb_Energy = 0.0
            for i in range(0,len(xyz),3):
                o = i
                h1 = i+1
                h2 = i+2
                # First O-H bond.
                r_1 = xyz[h1] - xyz[o]
                r_1n = np.linalg.norm(r_1)
                Bond_Energy += 0.5 * k_ij * ((r_1n - r_0) / 10)**2
                # Second O-H bond.
                r_2 = xyz[h2] - xyz[o]
                r_2n = np.linalg.norm(r_2)
                Bond_Energy += 0.5 * k_ij * ((r_2n - r_0) / 10)**2
                # Angle.
                theta = np.arccos(np.dot(r_1, r_2) / (r_1n * r_2n)) * 180 / np.pi
                Angle_Energy += 0.5 * k_ijk * ((theta - t_0) * np.pi / 180)**2
                for j in range(0, i, 3):
                    oo = j
                    hh1 = j+1
                    hh2 = j+2
                    # Lennard-Jones interaction.
                    r_o_oo = np.linalg.norm(xyz[oo] - xyz[o]) / 10
                    sroo = sig / r_o_oo
                    VdW_Energy += 4*eps*(sroo**12 - sroo**6)
                    # Coulomb interaction.
                    for k, l in itertools.product(*[[i,i+1,i+2],[j,j+1,j+2]]):
                        q1 = q_o if (k % 3 == 0) else q_h
                        q2 = q_o if (l % 3 == 0) else q_h
                        Coulomb_Energy += q1*q2 / np.linalg.norm(xyz[k]-xyz[l])
            Coulomb_Energy *= facel
            Energy = Bond_Energy + Angle_Energy + VdW_Energy + Coulomb_Energy
            Force = list(np.zeros(3*len(xyz)))
            M.append(np.array([Energy] + Force))
        return M
    def runTest(self):
        """Check continuation from a previous run"""
        self.logger.debug("\nSetting input file to 'test_continue.in'\n")
        input_file = 'test_continue.in'

        ## The general options and target options that come from parsing the input file
        self.logger.debug("Parsing inputs...\n")
        options, tgt_opts = parse_inputs(input_file)
        options['continue'] = True
        self.logger.debug("options:\n%s\n\ntgt_opts:\n%s\n\n" %
                          (str(options), str(tgt_opts)))

        self.assertEqual(dict,
                         type(options),
                         msg="\nParser gave incorrect type for options")
        self.assertEqual(list,
                         type(tgt_opts),
                         msg="\nParser gave incorrect type for tgt_opts")
        for target in tgt_opts:
            self.assertEqual(
                dict,
                type(target),
                msg="\nParser gave incorrect type for target dict")

        ## The force field component of the project
        forcefield = FF(options)
        self.assertEqual(FF,
                         type(forcefield),
                         msg="\nExpected forcebalance forcefield object")

        ## The objective function
        objective = Objective(options, tgt_opts, forcefield)
        self.assertEqual(Objective,
                         type(objective),
                         msg="\nExpected forcebalance objective object")

        ## The optimizer component of the project
        self.logger.debug("Creating optimizer: ")
        optimizer = Optimizer(options, objective, forcefield)
        self.assertEqual(Optimizer,
                         type(optimizer),
                         msg="\nExpected forcebalance optimizer object")
        self.logger.debug(str(optimizer) + "\n")

        ## Actually run the optimizer.
        self.logger.debug("Done setting up! Running optimizer...\n")
        result = optimizer.Run()
        self.logger.debug("\nOptimizer finished. Final results:\n")
        self.logger.debug(str(result) + '\n')

        self.assertEqual(optimizer.iterinit,
                         2,
                         msg="\nInitial iteration counter is incorrect")
        self.assertEqual(optimizer.iteration,
                         2,
                         msg="\nFinal iteration counter is incorrect")
    def runTest(self):
        """Check voelz study runs without errors"""
        self.logger.debug("\nSetting input file to 'options.in'\n")
        input_file = 'options.in'

        ## The general options and target options that come from parsing the input file
        self.logger.debug("Parsing inputs...\n")
        options, tgt_opts = parse_inputs(input_file)
        self.logger.debug("options:\n%s\n\ntgt_opts:\n%s\n\n" %
                          (str(options), str(tgt_opts)))

        self.assertEqual(dict,
                         type(options),
                         msg="\nParser gave incorrect type for options")
        self.assertEqual(list,
                         type(tgt_opts),
                         msg="\nParser gave incorrect type for tgt_opts")
        for target in tgt_opts:
            self.assertEqual(
                dict,
                type(target),
                msg="\nParser gave incorrect type for target dict")

        ## The force field component of the project
        self.logger.debug("Creating forcefield using loaded options: ")
        forcefield = FF(options)
        self.logger.debug(str(forcefield) + "\n")
        self.assertEqual(FF,
                         type(forcefield),
                         msg="\nExpected forcebalance forcefield object")

        ## The objective function
        self.logger.debug(
            "Creating object using loaded options and forcefield: ")
        objective = Objective(options, tgt_opts, forcefield)
        self.logger.debug(str(objective) + "\n")
        self.assertEqual(Objective,
                         type(objective),
                         msg="\nExpected forcebalance objective object")

        ## The optimizer component of the project
        self.logger.debug("Creating optimizer: ")
        optimizer = Optimizer(options, objective, forcefield)
        self.logger.debug(str(optimizer) + "\n")
        self.assertEqual(Optimizer,
                         type(optimizer),
                         msg="\nExpected forcebalance optimizer object")

        ## Actually run the optimizer.
        self.logger.debug("Done setting up! Running optimizer...\n")
        result = optimizer.Run()

        self.logger.debug("\nOptimizer finished. Final results:\n")
        self.logger.debug(str(result) + '\n')
def main():
    ## Set some basic options.  Note that 'forcefield' requires 'ffdir'
    ## which indicates the relative path of the force field.
    options, tgt_opts = parse_inputs(argv[1])
    MyFF = FF(options)
    Prec = int(argv[2])
    if 'read_mvals' in options:
        mvals = np.array(options['read_mvals'])
    else:
        mvals = np.zeros(len(MyFF.pvals0))
    MyFF.make(mvals, False, 'NewFF', precision=Prec)
Exemple #8
0
    def test_continue(self):
        """Check continuation from a previous run"""
        if sys.version_info < (3, 0):
            pytest.skip("Existing pickle file only works with Python 3")
        self.logger.debug("\nSetting input file to 'test_continue.in'\n")
        input_file = 'test_continue.in'

        ## The general options and target options that come from parsing the input file
        self.logger.debug("Parsing inputs...\n")
        options, tgt_opts = parse_inputs(input_file)
        options['continue'] = True
        self.logger.debug("options:\n%s\n\ntgt_opts:\n%s\n\n" %
                          (str(options), str(tgt_opts)))

        assert isinstance(options,
                          dict), "Parser gave incorrect type for options"
        assert isinstance(tgt_opts,
                          list), "Parser gave incorrect type for tgt_opts"
        for target in tgt_opts:
            assert isinstance(
                target, dict), "Parser gave incorrect type for target dict"

        ## The force field component of the project
        forcefield = FF(options)
        assert isinstance(forcefield,
                          FF), "Expected forcebalance forcefield object"

        ## The objective function
        objective = Objective(options, tgt_opts, forcefield)
        assert isinstance(objective,
                          Objective), "Expected forcebalance objective object"

        ## The optimizer component of the project
        self.logger.debug("Creating optimizer: ")
        optimizer = Optimizer(options, objective, forcefield)
        assert isinstance(optimizer,
                          Optimizer), "Expected forcebalance optimizer object"
        self.logger.debug(str(optimizer) + '\n')

        ## Actually run the optimizer.
        self.logger.debug("Done setting up! Running optimizer...\n")
        result = optimizer.Run()
        self.logger.debug("\nOptimizer finished. Final results:\n")
        self.logger.debug(str(result) + '\n')

        assert optimizer.iterinit == 2, "Initial iteration counter is incorrect"
        assert optimizer.iteration == 2, "Final iteration counter is incorrect"
Exemple #9
0
    def parseFBInput(self):
        """
        This reads through the provided ForceBalance input file using the 
        standard FB parse_inputs. It removes any non-AbInitio targets and 
        removes any AbInitio targets that are previously MMOpt targets.
        This forms a dictionary (self.unique_res) containing targets belonging
        to the same residue based off of the target prefix.
        """
        printcool("Reading Grids")

        #Parse FB input file
        self.options, self.tgt_opts = parse_inputs(self.fbinput)

        #Get force field in FB result directory
        ff_path = os.path.join("result",
                               os.path.splitext(self.options["input_file"])[0])
        self.options["ffdir"] = ff_path
        self.ff = FF(self.options)

        #Retain AbInitio targets that are not mmopt targets
        self.tgt_opts = [
            l for l in self.tgt_opts
            if "ABINITIO" in l.get("type") and "mmopt" not in l.get("name")
        ]

        self.root = self.options["root"]

        self.options["input_file"] = "reopt"

        #Assemble targets from ImplementedTargets dictionary
        self.targets = []
        for opts in self.tgt_opts:
            Tgt = Implemented_Targets[opts["type"]](self.options, opts,
                                                    self.ff)
            self.targets.append(Tgt)

        #Combine targets that belong to one residue, splits on - or _ in target name (may not be completely sufficient...)
        self.unique_res = {}
        for i in range(len(self.tgt_opts)):
            name = re.split(r"_|-", self.tgt_opts[i]["name"])[0]
            if name in self.unique_res:
                self.unique_res[name].append(self.targets[i])
            else:
                self.unique_res[name] = []
                self.unique_res[name].append(self.targets[i])
def load_fb_force_field(root_directory: str) -> "FF":
    """Attempts to load the force field being refit from a force balance optimization
    directory.

    Parameters
    ----------
    root_directory
        The directory containing the force balance input files.

    Returns
    -------
        The loaded force balance force field object.
    """

    from forcebalance.forcefield import FF
    from forcebalance.parser import parse_inputs

    with temporary_cd(root_directory):
        fb_options, _ = parse_inputs("optimize.in")
        fb_force_field = FF(fb_options)

    return fb_force_field
Exemple #11
0
    def runTest(self):
        """Check liquid target with existing simulation data"""
        if not sys.version_info <= (2, 7):
            self.skipTest("Existing pickle file only works with Python 3")

        self.logger.debug("\nSetting input file to 'single.in'\n")
        input_file = 'single.in'

        ## The general options and target options that come from parsing the input file
        self.logger.debug("Parsing inputs...\n")
        options, tgt_opts = parse_inputs(input_file)
        self.logger.debug("options:\n%s\n\ntgt_opts:\n%s\n\n" %
                          (str(options), str(tgt_opts)))

        forcefield = FF(options)
        objective = Objective(options, tgt_opts, forcefield)
        ## The optimizer component of the project
        self.logger.debug("Creating optimizer: ")
        optimizer = Optimizer(options, objective, forcefield)
        self.assertEqual(Optimizer,
                         type(optimizer),
                         msg="\nExpected forcebalance optimizer object")
        self.logger.debug(str(optimizer) + "\n")

        ## Actually run the optimizer.
        self.logger.debug("Done setting up! Running optimizer...\n")
        result = optimizer.Run()
        self.logger.debug("\nOptimizer finished. Final results:\n")
        self.logger.debug(str(result) + '\n')

        liquid_obj_value = optimizer.Objective.ObjDict['Liquid']['x']
        self.assertTrue(
            liquid_obj_value < 20,
            msg=
            "\nLiquid objective function should give < 20 (about 17.23) total value."
        )
    def runTest(self):
        """Check water tutorial study runs without errors"""
        self.logger.debug("\nSetting input file to 'very_simple.in'\n")
        input_file = 'very_simple.in'

        ## The general options and target options that come from parsing the input file
        self.logger.debug("Parsing inputs...\n")
        options, tgt_opts = parse_inputs(input_file)
        self.logger.debug("options:\n%s\n\ntgt_opts:\n%s\n\n" %
                          (str(options), str(tgt_opts)))

        self.assertEqual(dict,
                         type(options),
                         msg="\nParser gave incorrect type for options")
        self.assertEqual(list,
                         type(tgt_opts),
                         msg="\nParser gave incorrect type for tgt_opts")
        for target in tgt_opts:
            self.assertEqual(
                dict,
                type(target),
                msg="\nParser gave incorrect type for target dict")

        ## The force field component of the project
        forcefield = FF(options)
        self.assertEqual(FF,
                         type(forcefield),
                         msg="\nExpected forcebalance forcefield object")

        ## The objective function
        objective = Objective(options, tgt_opts, forcefield)
        self.assertEqual(Objective,
                         type(objective),
                         msg="\nExpected forcebalance objective object")

        ## The optimizer component of the project
        self.logger.debug("Creating optimizer: ")
        optimizer = Optimizer(options, objective, forcefield)
        self.assertEqual(Optimizer,
                         type(optimizer),
                         msg="\nExpected forcebalance optimizer object")
        self.logger.debug(str(optimizer) + "\n")

        ## Actually run the optimizer.
        self.logger.debug("Done setting up! Running optimizer...\n")
        result = optimizer.Run()
        self.logger.debug("\nOptimizer finished. Final results:\n")
        self.logger.debug(str(result) + '\n')

        self.assertNdArrayEqual(
            EXPECTED_WATER_RESULTS,
            result,
            delta=0.001,
            msg=
            "\nCalculation results have changed from previously calculated values.\n"
            "If this seems reasonable, update EXPECTED_WATER_RESULTS in test_system.py with these values"
        )

        # Fail if calculation takes longer than previously to converge
        self.assertGreaterEqual(ITERATIONS_TO_CONVERGE, Counter(), msg="\nCalculation took longer than expected to converge (%d iterations vs previous of %d)" %\
        (ITERATIONS_TO_CONVERGE, Counter()))
    def runTest(self):
        """Check implicit hydration free energy study (Hydration target) converges to expected results"""
        self.logger.debug("\nSetting input file to 'optimize.in'\n")
        input_file = 'optimize.in'

        ## The general options and target options that come from parsing the input file
        self.logger.debug("Parsing inputs...\n")
        options, tgt_opts = parse_inputs(input_file)
        self.logger.debug("options:\n%s\n\ntgt_opts:\n%s\n\n" %
                          (str(options), str(tgt_opts)))

        self.assertEqual(dict,
                         type(options),
                         msg="\nParser gave incorrect type for options")
        self.assertEqual(list,
                         type(tgt_opts),
                         msg="\nParser gave incorrect type for tgt_opts")
        for target in tgt_opts:
            self.assertEqual(
                dict,
                type(target),
                msg="\nParser gave incorrect type for target dict")

        ## The force field component of the project
        self.logger.debug("Creating forcefield using loaded options: ")
        forcefield = FF(options)
        self.logger.debug(str(forcefield) + "\n")
        self.assertEqual(FF,
                         type(forcefield),
                         msg="\nExpected forcebalance forcefield object")

        ## The objective function
        self.logger.debug(
            "Creating object using loaded options and forcefield: ")
        objective = Objective(options, tgt_opts, forcefield)
        self.logger.debug(str(objective) + "\n")
        self.assertEqual(Objective,
                         type(objective),
                         msg="\nExpected forcebalance objective object")

        ## The optimizer component of the project
        self.logger.debug("Creating optimizer: ")
        optimizer = Optimizer(options, objective, forcefield)
        self.logger.debug(str(optimizer) + "\n")
        self.assertEqual(Optimizer,
                         type(optimizer),
                         msg="\nExpected forcebalance optimizer object")

        ## Actually run the optimizer.
        self.logger.debug("Done setting up! Running optimizer...\n")
        result = optimizer.Run()

        self.logger.debug("\nOptimizer finished. Final results:\n")
        self.logger.debug(str(result) + '\n')

        self.assertNdArrayEqual(
            EXPECTED_ETHANOL_RESULTS,
            forcefield.create_pvals(result),
            delta=0.02,
            msg=
            "\nCalculation results have changed from previously calculated values.\n"
            "If this seems reasonable, update EXPECTED_ETHANOL_RESULTS in test_system.py with these values"
        )
Exemple #14
0
 def __init__(self):
     self.Mao = 0
     self.root = os.getcwd()
     options, tgt_opts = parse_inputs(input_file)
     self.forcefield  = FF(options)