Example #1
0
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()
Example #2
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.")
Example #3
0
    def runTest(self):
        """Check water tutorial study runs without errors"""
        input_file='very_simple.in'

        ## The general options and target options that come from parsing the input file
        options, tgt_opts = parse_inputs(input_file)

        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
        optimizer   = Optimizer(options, objective, forcefield)
        self.assertEqual(Optimizer, type(optimizer), msg="\nExpected forcebalance optimizer object")

        ## Actually run the optimizer.
        result = optimizer.Run()

        self.assertEqual(EXPECTED_WATER_RESULTS,result,
        msg="\nCalculation results have changed from previously calculated values.\nIf this seems reasonable, update EXPECTED_WATER_RESULTS in test_system.py with these values:\n%s"\
        % repr(result))

        # 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()))
Example #4
0
    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')
Example #5
0
 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
Example #6
0
    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."
Example #7
0
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()
Example #8
0
    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")
Example #9
0
def main():
    options, tgt_opts = parse_inputs(sys.argv[1])
    """ Instantiate a ForceBalance project and call the optimizer. """
    print "\x1b[1;97m Welcome to ForceBalance version 0.12! =D\x1b[0m"
    if len(sys.argv) != 2:
        print "Please call this program with only one argument - the name of the input file."
        sys.exit(1)

    for S in tgt_opts:
        print os.getcwd()
        Generate(S)
Example #10
0
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)
Example #11
0
    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')
Example #12
0
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)
Example #13
0
def main():
    options, tgt_opts = parse_inputs(sys.argv[1])
    
    """ Instantiate a ForceBalance project and call the optimizer. """
    print("\x1b[1;97m Welcome to ForceBalance version 0.12! =D\x1b[0m")
    if len(sys.argv) != 2:
        print("Please call this program with only one argument - the name of the input file.")
        sys.exit(1)

    for S in tgt_opts:
        print(os.getcwd())
        Generate(S)
Example #14
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"
Example #15
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])
Example #16
0
    def runTest(self):
        """Check liquid bromine study (Thermo target) converges to expected results"""
        self.logger.debug("\nSetting input file to 'options.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_BROMINE_RESULTS,result,delta=0.02,
                                msg="\nCalculation results have changed from previously calculated values.\n"
                                "If this seems reasonable, update EXPECTED_BROMINE_RESULTS in test_system.py with these values")
Example #17
0
    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()))
Example #18
0
    def runTest(self):
        """Check continuation from a previous run"""
        if not sys.version_info <= (2,7):
            self.skipTest("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)))

        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")
Example #19
0
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
Example #20
0
def main():
    """ Print out all of the options available to ForceBalance. """
    options = None
    tgt_opts = [None]
    if len(sys.argv) == 2:
        options, tgt_opts = parser.parse_inputs(sys.argv[1])
    out = []
    out.append("# ForceBalance input file generated by MakeInputFile.py")
    out.append("# The octothorpe '#' is a comment symbol")
    out.append("# There are two sections, the main options ($options) and the target options ($target)")
    out.append("# A ForceBalance calculation will have one $options section and as one $target section per optimization target")
    out.append("# The most important options are listed at the top; options are also roughly grouped by their application")
    out.append("# Note: If the specified value is 'None' then the option will truly be set to None - not the string 'None'")
    out.append("# Note: Section option types are more complicated and may require you to read the documentation")
    out.append("# Note: Boolean option types require no value, the key being present implies 'True'")
    out.append("# Note: List option types are specified using spaces as the delimiter - i.e. forcefield ff1.itp ff2.itp ; delete empty brackets before use [] ")
    out.append("")
    out += parser.printsection("$options",options,parser.gen_opts_types)
    for tgt_opt in tgt_opts:
        out.append("\n")
        out += parser.printsection("$target",tgt_opt,parser.tgt_opts_types)
    for line in out:
        print(line)
Example #21
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."
        )
Example #22
0
def Run_ForceBalance(input_file):
    """ 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.
    """
    ## The general options and target options that come from parsing the input file
    options, tgt_opts = parse_inputs(input_file)
    ## 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()
Example #23
0
    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()))
Example #24
0
    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"
        )
Example #25
0
 def __init__(self):
     self.Mao = 0
     self.root = os.getcwd()
     options, tgt_opts = parse_inputs(input_file)
     self.forcefield  = FF(options)