Ejemplo n.º 1
0
def bubbler(potential, backend="cosmotransitions", **kwargs):
    """
    :param potential: Potential object or string
    :param backend: Code with which to solve bounce
    :returns: Results from a particular code
    :rtype: namedtuple
    """
    try:

        # Call function

        module = globals()[backend]
        potential = Potential(potential) if isinstance(potential,
                                                       str) else potential
        action, trajectory_data, time, command = module.solve(
            potential, **kwargs)

        # Make interpolation function from output

        trajectory = [
            interp(trajectory_data[:, 0], trajectory_data[:, i + 1])
            for i in range(potential.n_fields)
        ] if trajectory_data is not None else None

        # Find maximum value of rho

        rho_end = trajectory_data[-1,
                                  0] if trajectory_data is not None else None

        return Solution(backend, action, trajectory, rho_end, time, command)

    except Exception as error:

        return Solution(backend, None, None, None, None, error.message)
Ejemplo n.º 2
0
def profiles(potential, backends=None, **kwargs):
    """
    :param potential: Potential object or string

    Plots field profiles for all codes.
    """
    potential = Potential(potential) if isinstance(potential,
                                                   str) else potential
    results = bubblers(potential, backends, **kwargs)

    # Make profile plot

    _, ax = plt.subplots()
    colors = cycle(["Brown", "Green", "Blue"])

    for result in results.itervalues():

        if not result.action:
            continue

        color = next(colors)
        lines = cycle(["-", "--", "-."])
        rho = np.linspace(0, result.rho_end, 1000)

        for name, trajectory in zip(potential.field_latex, result.trajectory):
            ax.plot(rho,
                    trajectory(rho),
                    ls=next(lines),
                    c=color,
                    lw=3,
                    label="{} from {}".format(name, result.backend),
                    alpha=0.8)

    # Plot true vacuum

    markers = cycle(["^", "p", "*"])

    for name, field in zip(potential.field_latex, potential.true_vacuum):
        ax.plot(0.,
                field,
                next(markers),
                c="Gold",
                label="True vacuum for {}".format(name),
                ms=10,
                clip_on=False,
                zorder=10)

    # Labels etc

    ax.set_xlabel(r"$\rho$")
    ax.set_ylabel(r"$\phi$")
    leg = ax.legend(numpoints=1, fontsize=12, loc='best')
    leg.get_frame().set_alpha(0.5)
    ax.set_title(potential.potential_latex)

    plt.show()
Ejemplo n.º 3
0
    def test_add_empty_potentials(self):
        """ Potential addition with empty potential """
        # first we test construction of empty potential
        p = Potential()
        self.assertEqual(p.labels, [])
        self.assertEqual(p.nsites, 0)
        self.assertEqual(p.npols, 0)

        p2 = p + p  # maybe we should just raise a value error instead?
        self.assertEqual(p2.nsites, 0)
        self.assertEqual(p2.npols, 0)
Ejemplo n.º 4
0
 def initalize_message(self):
     '''every node has a message dictionary
     self.message ={j: {nodek: mkj(xj), nodeh: mhj(xj), ...},
                    i: {nodek: mki(xi), nodeh: mhi(xi), ...},
                    }
     '''
     self.message = {}
     for node_idx, node_name in enumerate(self.graph.node_list):
         self.message[node_idx] = {}
         for neighbor_node in self.graph.neighbor(node_idx):
             self.message[node_idx][neighbor_node] = Potential(
                 [node_idx], np.array([self.graph.node_size[node_idx]]),
                 np.ones(self.graph.node_size[node_idx]))
Ejemplo n.º 5
0
def bubblers(potential, backends=None, **kwargs):
    """
    :param potential: Potential object or string
    :param backend: Code with which to solve bounce
    :returns: Results from all codes
    :rtype: list of namedtuple
    """
    potential = Potential(potential) if isinstance(potential,
                                                   str) else potential
    backends = backends if backends else BACKENDS
    return Solutions(
        {b: bubbler(potential, backend=b, **kwargs)
         for b in backends})
Ejemplo n.º 6
0
    def __pb_train_click(self):
        try:
            class_0_point_0_x = int(self.ui.le_class_0_point_0_x.text())
            class_0_point_0_y = int(self.ui.le_class_0_point_0_y.text())
            point_0 = Point(class_0_point_0_x, class_0_point_0_y)

            class_0_point_1_x = int(self.ui.le_class_0_point_1_x.text())
            class_0_point_1_y = int(self.ui.le_class_0_point_1_y.text())
            point_1 = Point(class_0_point_1_x, class_0_point_1_y)

            self.__training_vectors[0] = [point_0, point_1]
        except ValueError:
            self.__training_vectors[0] = [Point(3, 2), Point(-5, 0)]

        try:
            class_1_point_0_x = int(self.ui.le_class_1_point_0_x.text())
            class_1_point_0_y = int(self.ui.le_class_1_point_0_y.text())
            point_0 = Point(class_1_point_0_x, class_1_point_0_y)

            class_1_point_1_x = int(self.ui.le_class_1_point_1_x.text())
            class_1_point_1_y = int(self.ui.le_class_1_point_1_y.text())
            point_1 = Point(class_1_point_1_x, class_1_point_1_y)

            self.__training_vectors[1] = [point_0, point_1]
        except ValueError:
            self.__training_vectors[1] = [Point(4, -7), Point(1, 1)]

        potential = Potential(self.__amount_of_classes)
        self.__func, isSuccess = potential.train(self.__training_vectors)

        if not isSuccess:
            self.__msgbox_message(
                'Error',
                'An error occurred while training. \nEnter another training data.'
            )
        else:
            self.scene.clear()
            self.__draw_axes()
            self.__draw_graphic()
            self.__draw_training_points()

        try:
            self.ui.le_separated_function.setText(str(self.__func))
        except ValueError:
            self.__msgbox_message(
                'Error',
                'An error occurred while training. \nEnter another training data.'
            )
Ejemplo n.º 7
0
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import MDAnalysis as md

from density import Density
from potential import Potential


u = md.Universe('trj/md128_280k.tpr',
                'trj/md128_280k.xtc')

h2o = u.select_atoms('name OW or name HW1 or name HW2')
pot = Potential(u)

for _ in tqdm(u.trajectory, total=len(u_trajectory)):
    pot.potential_matrix()


'''
plt.plot(t, np.mean(rot, axis=1), 'o')
plt.plot(ref[:,0], ref[:,2]/512, '-')
plt.xlim((0, 0.2))
plt.show()
'''
Ejemplo n.º 8
0
    pot_surface3 = Surface_1D_analytic(np.cos, relative=True)

    complete_interaction = [{
        'function': pot_surface3,
        'coordinates': [0, 1]
    }, {
        'function': pot_surface3,
        'coordinates': [1, 2]
    }, {
        'function': pot_surface3,
        'coordinates': [2, 3]
    }, {
        'function': pot_surface3,
        'coordinates': [3, 4]
    }]

    pot_obj = Potential(complete_interaction)

    initial_conditions = {
        'coordinates': np.array([4, 0, 0, 0, 0]),
        'velocity': np.array([3, 0, 0, 0, 0]),
        'masses': np.array([300.0, 1.0, 1.0, 1.0, 1.0])
    }

    md = MolecularDynamics(initial_conditions=initial_conditions,
                           potential=pot_obj)

    md.calculate_nve()
    md.calculate_nvt()
Ejemplo n.º 9
0
 def __init__(self, id, nodes, sizes, values=None):
     self.id = id
     self.potential = Potential(nodes, sizes, values)
Ejemplo n.º 10
0
import numpy as np
from potential import Potential
#

pot_x1 = Potential([0], np.array([2]), np.array([0.9, 0.1]))
pot_x2 = Potential([1], np.array([2]), np.array([1.0, 1.0]))

pot_x2x1 = Potential([1, 0], np.array([2, 2]),
                     np.array([[0.9, 0.2], [0.1, 0.8]]))
pot_x1x2 = Potential([0, 1], np.array([2, 2]),
                     np.array([[0.9, 0.1], [0.2, 0.8]]))

pot_m12_x2 = Potential([1], np.array([2]), np.array([0.83, 0.17]))

res1 = pot_x2x1.multiply(pot_x1)

res1_ver = Potential([1, 0], np.array([2, 2]),
                     np.array([[0.81, 0.02], [0.09, 0.08]]))
print res1
assert res1 == res1_ver

res2 = pot_x1x2.multiply(pot_x1)
res2_ver = Potential([0, 1], np.array([2, 2]),
                     np.array([[0.81, 0.09], [0.02, 0.08]]))
print res2
assert res2 == res2_ver

res3 = pot_x2.multiply(pot_m12_x2)
res3_ver = Potential([1], np.array([2]), np.array([0.83, 0.17]))
assert res3 == res3_ver
print res3
Ejemplo n.º 11
0
def run_test(configData):
    # Example with config Data
    if not configData:
        print("Using configuration file: ", configData)

    # Set up our potential class
    # TODO: Convert potential from config file

    # We will pass a dictionary that we will get from the config file. For now we construct it manually

    potential_parameters = {}

    # define fields and constants for the time being
    # define constants
    const_2, const_3, const_4 = sympy.symbols('c2,c3,c4')
    constants = (const_2, const_3, const_4)
    # define fields
    field_1, field_2 = sympy.symbols('f1,f2')
    fields = (field_1, field_2)
    # Define the potential
    potential_form = const_2 * field_1**2 + const_3 * field_1**3 + const_4 * field_1**4 + field_2**4
    # Vevs and masses
    vevs = (246., 0.)
    masses = (0., 125.
              )  # some ordering may be required to match diagonalisation

    # TODO: Are minimization bounds going to be derivived or inputs?. If inputs, put here and feed into potential parameters
    # Bounds and Initial Points

    # Build the dictionary
    potential_parameters['fields'] = fields
    potential_parameters['constants'] = constants
    potential_parameters['potential_form'] = potential_form
    potential_parameters['vevs'] = vevs
    potential_parameters['masses'] = masses
    potential_parameters['unknown_constants'] = (const_2, const_4)
    potential_parameters['known_constants'] = (const_3, )
    potential_parameters['known_constants_vals'] = (-1.5 * 125.**2 / 246. /
                                                    3, )

    # Create our potential class
    # This stores all info about the potential - See the class
    potential = Potential(potential_parameters)
    # potential currently cannot handle pure mass terms

    # solve the constants from 1st derivative and hessian of potential
    # This will be private function - But for testing lets run it
    # TODO: Make sure there are no more free constants after reduction
    print("==============coupling constants reduction============")
    print(potential._constant_reduction)
    print("======================================================")

    # ####working out the free-parameters######

    print("===============printing free constants================")
    print(potential.remaining_vars())
    print("======================================================")

    # print("=====================test outputs=====================")
    # # Only printing for testing. Private member
    # print("Constrained Potential :", potential._constrained_potential)
    #
    # # Set some constants
    # constant_val = {'c3': -1.5 * 125. ** 2 / 246. / 3}
    # print("Potential with c3 Fixed :", potential.set_constants(constant_val))
    #
    # # Get Numeric Values of Constants given fixed unknown variables
    # print("Numeric Values for Constants with c3 fixed :", potential.numeric_const_values(constant_val))
    # print("======================================================")

    # define the bounds of the minimisation, where the c20vals etc are set to fix the value
    # define initial point for minimisation
    # Initial point for finding minima

    # Bounds for the minimization
    # TODO: Implement minimization with bounds and initial point.
    # TODO: Implementation is done in the class not here!
    # TODO: Bounds can be class members and set up from config. Or dervived in the constructor
    # bnds = ((-400., 400.), (-400., 400.), (c20val, c20val), (c30val, c30val), (c40val, c40val))
    # bounds = < insert some points >
    #bounds=((-400.,400),)

    # run minimisation
    # TODO: for each field add the range (-400.,400.)
    (bounds, initial_point) = (((-400., 400), (-400., 400.)), [0., 0.])

    print("=========printing solutions from minimisation=========")
    #print(potential.func_to_minimise())
    print(potential.minimise(bounds, initial_point))
    #print(Potential.out)
    print("======================================================")

    # Plotting
    """ Leave for Now... will fix soon