Exemple #1
0
def _parse_yaml(adjacency, hopping, positions, nt=0, name="", comment=""):
    "Parse a !lattice YAML node."

    # turn hopping into a list if it isn't already
    if not isinstance(hopping, list):
        hopping = [hopping] * len(adjacency)
    elif len(adjacency) != len(hopping):
        raise RuntimeError(
            "Lengths of adjacency matrix and list of hopping strengths do not match"
        )

    # create the lattice with partly empty sites
    lat = Lattice(name=name, comment=comment, nt=nt)
    lat.sites = [
        Site(i, np.array(pos), [], []) for i, pos in enumerate(positions)
    ]

    # fill in neighour and hopping lists
    for (i, j), hop in zip(adjacency, hopping):
        if i > len(hopping) or j > len(hopping):
            raise RuntimeError("Site index out of range: [{}, {}]".format(
                i, j))

        _append_adj_hop(lat.sites[i], j, hop)
        _append_adj_hop(lat.sites[j], i, hop)

    return lat
class LatticeRunner(Thread):

    def __init__(self, args):
        Thread.__init__(self)
        self.args = args
        self.lattice = Lattice(size=args.size,
                               slider=args.slider,
                               onlyRedBlue=not args.any,
                               defKillers=args.defKillers,
                               density=args.density,
                               numRatio=args.numRatio,
                               redAdvantage=args.redAdvantage,
                               blueAdvantage=args.blueAdvantage,
                               redGrowth=args.redGrowth,
                               blueGrowth=args.blueGrowth,
                               deathRate=100000)

        self.args = args
        self.quit = False

    def stop(self):
        self.quit = True

    def run(self):
        for iteration in range(0, self.args.evolutions):
            self.lattice.evolve(1)
            if self.quit:
                print("Aborting")
                break
        print("Generations: %d" % self.lattice.generation)
Exemple #3
0
def _wnd_to_lattice(graph):
    "Turn a graph read from a w3d or w2d file into a Lattice object."
    lat = Lattice()
    lat.sites = [
        Site(idx, pos, neigh, [1] * len(neigh)) for idx, pos, neigh in graph
    ]
    return lat
Exemple #4
0
 def __init__(self,datasetfilename):
     "some codes, reserved rules, and average lift so far"
     self.latt = Lattice(datasetfilename)
     self.count = 0
     self.DISCARD = -1
     self.reserved = []
     self.sumlifts = 0.0
     self.numlifts = 0
Exemple #5
0
 def cleanup(self, preserve_last: bool = False):
     'Delete all run directories'
     n_lats = len(self.rholist) - 1
     if preserve_last:
         n_lats -= 1  # Save the last run
     for i in range(n_lats):
         mylat = Lattice(self.salt, self.sf, self.l, self.rholist[i][1])
         mylat.cleanup()
Exemple #6
0
 def minimal_lattice(self, test, verbose=False, exclude=True):
     print test
     extent = copy.deepcopy(self.dataset)
     for v in extent:
         v.intent = v.intent & test.intent
         if exclude and v.intent == test.intent:
             v.intent = set()
     lattice = Lattice(extent)
     return lattice.score_lattice(verbose=verbose)
Exemple #7
0
    def __init__(self,
                 lattice,
                 positions,
                 atoms,
                 is_cartesian=False,
                 name=None):
        """
        Create a Structure object.

        Args:
            lattice(Lattice or 3x3 Array): The lattice either as a Lattice object or as a 3x3 array of which each raw corresponds to a lattice vector.
            frac_positions (List): A List of fractional coordinates of each atom.
            atoms (List): A List of atoms either as atomic symbols or as atomic numbers or Element objects.
            name (str): The name of the system. Default is None.

        """
        if isinstance(lattice, Lattice):
            self.__lattice = lattice
        else:
            self.__lattice = Lattice(lattice)

        if is_cartesian:
            self.__cart_positions = np.array(positions)
            self.__frac_positions = self.__lattice.get_frac_coords(positions)
        else:
            self.__frac_positions = np.array(positions)
            self.__cart_positions = self.__lattice.get_cart_coords(positions)

        self.__atoms = []
        for atom in atoms:
            if isinstance(atom, Element):
                element = atom
            else:
                element = Element(atom)
            self.__atoms.append(element)

        self.__element_species = []
        self.__num_per_species = []

        for species, atoms in itertools.groupby(self.__atoms):
            self.__element_species.append(species)
            self.__num_per_species.append(len(list(atoms)))

        # tempt = None
        # for atom in self.__atoms:
        # if tempt != atom:
        # self.__element_species.append(atom)
        # self.__num_per_species.append(1)
        # tempt = atom
        # else:
        # self.__num_per_species[-1] += 1

        if name is None:
            name = ''.join('{:s}{:d} '.format(element.atomic_symbol, num)
                           for element, num in zip(self.__element_species,
                                                   self.__num_per_species))
        self.__name = name
def replace_QD_with_QDth_lattice(slices,k0,length,label,particle,aperture):
    lattice = Lattice()
    thinlen = length/slices
    for nb in range(slices):
        if FLAGS['express']:
            instance = ELM.QDthx(k0=k0,length=thinlen,label=label,particle=particle,aperture=aperture)
        else:
            instance = ELM.QDth(k0=k0,length=thinlen,label=label,particle=particle,aperture=aperture)
        lattice.add_element(instance)
    return lattice
def main():
    # Initialize lattice object:
    l = Lattice(50)

    # Initializing ojbect in the lattice (bacteria) and empty lattice:
    x = int(0.99 * l.N)
    x = l.N - 1
    y = int(0.49 * l.N)

    l.initial_lattice(int(x), y, 1, 1)  # Top row = 1, object in lattice

    epsilon = 10**-3
    num_iterations = 0
    start_time = time.time()

    # Question 2.1
    while (l.delta > epsilon):
        l.SOR(omega=1)
        l.grow_object(eta=1)
        num_iterations += 1

    print("--- %s seconds ---" % (time.time() - start_time))
    print(">>>>", len(np.where(l.objects == 1)[0]))
    print("Number of iterations needed to get here = ", num_iterations)
    l.print_lattice()
Exemple #10
0
    def __init__(self, scale=0, depth=0):
        """
        Initializes the instance with a DMERA with identity gates.

        Args:
            scales (int): Number of qubits = 2 ** scales
            depth (int): Depth per scale
        """
        self.D = depth
        self.n = scale
        self.lattice = Lattice()
Exemple #11
0
 def tagger_lattice(self, test):
     extent = copy.deepcopy(self.dataset)
     flag = False
     for v in extent:
         v.intent = v.intent & test.intent
         if v.intent: flag = True
     if flag:
         lattice = Lattice(extent)
         lattice.score_lattice()
         return lattice.get_highest_outcome()
     else:
         return False
Exemple #12
0
class MainWindow():
    """
    Defines the main window for the envelope tool GUI
    """
    def __init__(self):
        """Initialise the main window"""
        self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable=E1101
                             ROOT.gClient.GetRoot(), # pylint: disable=E1101
                             SHARE_DIR+"main_frame.json")
        self.lattice = Lattice()
        self.beam_setup = None
        self.magnet_setup = None
        self.plot_setup = None
        self.plot_setup_options = [{"variable_type":0,
                                    "first_var":0,
                                    "plot_apertures":True}]
        self.window.set_button_action("&Beam Setup", self.beam_button_action)
        self.window.set_button_action("&Magnet Setup",
                                                      self.magnet_button_action)
        self.window.set_button_action("&Plot Setup", self.plot_button_action)
        self.window.set_button_action("E&xit", self.exit_button_action)
        self.update_plot()

    def beam_button_action(self):
        """Handle a Beam Setup button press"""
        if self.beam_setup == None:
            self.beam_setup = BeamSetup(self, self.window.main_frame)
            ref, ellipse = self.lattice.get_beam()
            self.beam_setup.set_reference(ref)
            self.beam_setup.set_matrix(ellipse)

    def magnet_button_action(self):
        """Handle a Magnet Setup button press"""
        if self.magnet_setup == None:
            self.magnet_setup = MagnetSetup(self, self.window.main_frame)

    def plot_button_action(self):
        """Handle a Plot Setup button press"""
        if self.plot_setup == None:
            self.plot_setup = PlotSetup(self, self.window.main_frame,
                                        self.plot_setup_options)

    def exit_button_action(self):
        """Handle a Exit button press"""
        self.window.close_window()

    def update_plot(self):
        """Update the plot"""
        canvas_frame = self.window.get_frame("main_canvas", "canvas")
        canvas = canvas_frame.GetCanvas()
        Plotter(self.plot_setup_options, canvas, self.lattice.ref_list,
                self.lattice.ellipse_list, self.lattice.get_field_list())
Exemple #13
0
 def test_degree(self, test, verbose=False):
     extent = copy.deepcopy(self.dataset)
     for v in extent:
         v.intent = v.intent & test.intent
     lattice = Lattice(extent)
     '''
     try:
         lattice = self.lattice
     except AttributeError:
         self.lattice = Lattice(copy.deepcopy(self.dataset), verbose)
         lattice = self.lattice
     '''
     return lattice.score_similarity(verbose)
Exemple #14
0
def getNodeEdgeList():
    # Given the nodeDic, compute node list and edge list in Lattice.py, then return them as JS vars.
    if str(request.form["jsonClean"]) == "true":
        nodeDic = literal_eval(
            json.loads(request.form['nodeDic'].replace(
                '\n', '').decode('string_escape')))
    else:
        nodeDic = json.loads(request.form['nodeDic'])

    G = Lattice()

    node = G.generateNode(nodeDic)
    edge = G.generateEdge(nodeDic)
    return jsonify(edge, node)
Exemple #15
0
 def set_spec_G(self, G, preparsed=False):
     """
     Take the spec G array for the psic geometry
     and set all the relevant orientation info...
     """
     if not preparsed:
         (cell, or0, or1, n) = spec_psic_G(G)
     else:
         (cell, or0, or1, n) = G
     self.n = n
     self.or0 = or0
     self.or1 = or1
     self.lattice = Lattice(*cell)
     self._calc_UB()
Exemple #16
0
def main():
    # begin_time = time.time()

    parser = argparse.ArgumentParser()
    parser.add_argument('--dict',
                        type=str,
                        default='./models/ipadic-vocab.txt.dict',
                        metavar='PATH',
                        help='double-array dictionary')
    parser.add_argument('-q', '--query', type=str, help='query')
    args = parser.parse_args()

    da = DoubleArray()
    print('Loading dic...')
    da.load(args.dict)
    print('Loaded!')

    query = args.query
    lattice = Lattice(query)

    for idx in range(len(query)):
        cps_q = query[idx:]
        print('=====Search {}======'.format(cps_q))
        cp_list = da.commonPrefixSearch(cps_q)
        print('commonPrefixSearch("{}"): {}'.format(cps_q, cp_list))
        for cp in cp_list:
            lattice.insert(idx, idx + len(cp), cp)

    # print('Process time: {:.1f}s'.format(time.time() - begin_time))
    lattice.pprint()
    lattice.plot()
Exemple #17
0
def make_kagome(Lx, Ly, periodic, spacing, name, comment):

    lat = Lattice(name, comment)
    size = Lx * Ly
    num_sites = size * 3

    # translation vector
    trans = list(np.array([1.0, np.sqrt(3)]) * spacing)
    a, b, c, sites = position(Lx, Ly, trans)
    site_pos = nearest_neighbours(size, a, b, c)

    # boundary sites
    boundary_sites_a = sites[0:Ly * 3:3] + sites[0::Ly * 3]
    boundary_sites_b = sites[1::Ly * 3] + sites[Ly * 3 * (Lx - 1) + 1::3]
    boundary_sites_c = sites[2:Ly * 3:3] + sites[(Ly * 3) - 1::(Ly * 3)]

    boundary_ind_a = _finding_index(boundary_sites_a, sites)
    boundary_ind_b = _finding_index(boundary_sites_b, sites)
    boundary_ind_c = _finding_index(boundary_sites_c, sites)

    neighbour_index, adjacency = adjacencyList(Lx, Ly, site_pos, sites,
                                               boundary_ind_a, boundary_ind_b,
                                               boundary_ind_c, periodic)

    #hopping_matrix = np.ones(len(adjacency))
    positions = np.zeros((num_sites, 3))
    positions[:, :-1] = sites  # making 3-dim
    for i in range(len(sites)):
        # hopping matrix of equal amplitude
        hoppings = [1] * len(neighbour_index[i])
        lat.sites.append(Site(i, positions[i], neighbour_index[i], hoppings))

    return lat
Exemple #18
0
 def process_word(word):
     lattice = Lattice(base_decompounder.get_decompound_lattice(word))
     viterbi_path = vit.viterbi_decode(Compound(word, None, lattice))
     return [
         word.encode('utf-8'),
         print_path(viterbi_path).encode('utf-8')
     ]
Exemple #19
0
 def test_generate_simple_exact_cover_solution2(self):
     col_names = ['a', 'b', 'c', 'd']
     matrix = [['0', '1', '1', '0'], ['1', '0', '0', '0'],
               ['1', '0', '1', '0'], ['0', '1', '0', '0']]
     lattice = Lattice(matrix, col_names, delete_zeros=True)
     solutions = generate_exact_cover_solutions(lattice)
     self.assertEqual(0, len(solutions))
Exemple #20
0
class DMERA1(Circuit):
    """
    This is a DMERA circuit ansatz for quantum many-body systems in
    one spatial dimension.
    """
    def __init__(self, scale=0, depth=0):
        """
        Initializes the instance with a DMERA with identity gates.

        Args:
            scales (int): Number of qubits = 2 ** scales
            depth (int): Depth per scale
        """
        self.D = depth
        self.n = scale
        self.lattice = Lattice()

    def expand(self, factor):
        """
        Expands the underlying lattice by a factor. Add preparation
        gates for the newly introduced qubits.
        """
        new_lattice = self.lattice.expand(factor)
        pts_new = list(set(new_lattice.pts) - set(self.lattice.pts))
        self.extend([Prepare(self.qubits[v]) for v in pts_new])

    def entangle(self):
        """
Exemple #21
0
def getJsonFromLattice():
    # set up the tree example
    G = Lattice()
    v1 = vizObj(x=["Clinton", "Trump", "Others"],y="% of vote",filters=["All"],\
                agg_func="SUM",tablename="election")
    v1.setData([48, 46, 6])
    root = vizNode(viz=v1, parents=None)

    v2 = vizObj(x=["Clinton", "Trump", "Others"],y="% of vote",filters=["Race = White"],\
                agg_func="SUM",tablename="election")
    v2.setData([31, 62, 7])
    W = vizNode(viz=v2, parents=[root])

    v3 = vizObj(x=["Clinton", "Trump", "Others"],y="% of vote",filters=["Gender = F"],\
                agg_func="SUM",tablename="election")
    v3.setData([21, 70, 9])
    F = vizNode(viz=v3, parents=[root])

    v4 = vizObj(x=["Clinton", "Trump", "Others"], y="% of vote", filters=["Color = Blue"], \
                agg_func="SUM", tablename="election")
    v4.setData([21, 52, 27])
    B = vizNode(viz=v4, parents=[W])

    v5 = vizObj(x=["Clinton", "Trump", "Others"], y="% of vote", filters=["Job = Student"], \
                agg_func="SUM", tablename="election")
    v5.setData([20, 30, 50])
    J = vizNode(viz=v5, parents=[W, B])
    # set up the tree example
    for nodes in G.getNodes():
        for child in nodes.get_child():
            G.addEdge(nodes, child)
    G.addMultiNodes([root, W, F, B, J])
    root.set_children([W, F])
    W.set_children([B])
    W.set_children([J])
    B.set_children([J])

    nodeDic = G.generateNodeDic()
    #nodeDic = "{\"1\": [{ \"xAxis\": \"0\", \"yAxis\":43.40789274938343},{ \"xAxis\": \"1\", \"yAxis\":56.59210725061657},{\"childrenIndex\":[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], \"populationSize\":492526704188, \"filter\":\"#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"2\": [{ \"xAxis\": \"0\", \"yAxis\":99.09927735409117},{ \"xAxis\": \"1\", \"yAxis\":0.9007226459088256},{\"childrenIndex\":[13, 28, 30, 34], \"populationSize\":65236316603, \"filter\":\"#is_profile_query$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"3\": [{ \"xAxis\": \"0\", \"yAxis\":99.09927735409117},{ \"xAxis\": \"1\", \"yAxis\":0.9007226459088256},{\"childrenIndex\":[17, 28, 38, 43], \"populationSize\":65236316603, \"filter\":\"#is_event_query$1#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"4\": [{ \"xAxis\": \"0\", \"yAxis\":98.84352038584385},{ \"xAxis\": \"1\", \"yAxis\":1.156479614156162},{\"childrenIndex\":[30, 38, 48], \"populationSize\":55050620539, \"filter\":\"#has_impressions_tbl$1#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"5\": [{ \"xAxis\": \"0\", \"yAxis\":87.72514337314605},{ \"xAxis\": \"1\", \"yAxis\":12.27485662685395},{\"childrenIndex\":[25, 35, 41, 46, 50, 52], \"populationSize\":115838325255, \"filter\":\"#has_distinct$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"6\": [{ \"xAxis\": \"0\", \"yAxis\":73.54175531539768},{ \"xAxis\": \"1\", \"yAxis\":26.458244684602324},{\"childrenIndex\":[64, 97, 102, 105, 107], \"populationSize\":53156154309, \"filter\":\"#is_profile_query$1#has_distinct$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"7\": [{ \"xAxis\": \"0\", \"yAxis\":73.54175531539768},{ \"xAxis\": \"1\", \"yAxis\":26.458244684602324},{\"childrenIndex\":[73, 97, 111, 115, 117], \"populationSize\":53156154309, \"filter\":\"#is_event_query$0#has_distinct$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"8\": [{ \"xAxis\": \"0\", \"yAxis\":29.77955596154781},{ \"xAxis\": \"1\", \"yAxis\":70.22044403845219},{\"childrenIndex\":[26, 27, 36, 42, 47, 51, 53], \"populationSize\":376688378933, \"filter\":\"#has_distinct$1#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"9\": [{ \"xAxis\": \"0\", \"yAxis\":30.47638712866313},{ \"xAxis\": \"1\", \"yAxis\":69.52361287133687},{\"childrenIndex\":[15, 18, 20, 22, 24, 27], \"populationSize\":82477942992, \"filter\":\"#is_multi_query$1#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"10\": [{ \"xAxis\": \"0\", \"yAxis\":19.748564939482314},{ \"xAxis\": \"1\", \"yAxis\":80.25143506051768},{\"childrenIndex\":[66, 76, 83, 88, 91], \"populationSize\":68383077780, \"filter\":\"#is_multi_query$1#has_distinct$1#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"11\": [{ \"xAxis\": \"0\", \"yAxis\":77.05061337960112},{ \"xAxis\": \"1\", \"yAxis\":22.949386620398883},{\"childrenIndex\":[81, 120, 122], \"populationSize\":61495053848, \"filter\":\"#has_impressions_tbl$0#has_distinct$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"12\": [{ \"xAxis\": \"0\", \"yAxis\":20.596887099254975},{ \"xAxis\": \"1\", \"yAxis\":79.40311290074501},{\"childrenIndex\":[56, 58, 60, 62], \"populationSize\":71779638383, \"filter\":\"#is_multi_query$1#is_profile_query$1#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"13\": [{ \"xAxis\": \"0\", \"yAxis\":20.596887099254975},{ \"xAxis\": \"1\", \"yAxis\":79.40311290074501},{\"childrenIndex\":[56, 68, 70, 72], \"populationSize\":71779638383, \"filter\":\"#is_multi_query$1#is_event_query$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"14\": [{ \"xAxis\": \"0\", \"yAxis\":21.13295807883538},{ \"xAxis\": \"1\", \"yAxis\":78.86704192116461},{\"childrenIndex\":[78, 80], \"populationSize\":72696207193, \"filter\":\"#is_multi_query$1#has_impressions_tbl$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"15\": [{ \"xAxis\": \"0\", \"yAxis\":21.933813158690548},{ \"xAxis\": \"1\", \"yAxis\":78.06618684130945},{\"childrenIndex\":[85], \"populationSize\":73168015971, \"filter\":\"#is_multi_query$1#has_clicks_tbl$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"16\": [{ \"xAxis\": \"0\", \"yAxis\":34.90524231845271},{ \"xAxis\": \"1\", \"yAxis\":65.09475768154729},{\"childrenIndex\":[14, 15, 29, 31, 32, 33], \"populationSize\":427290387585, \"filter\":\"#is_profile_query$1#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"17\": [{ \"xAxis\": \"0\", \"yAxis\":34.90524231845271},{ \"xAxis\": \"1\", \"yAxis\":65.09475768154729},{\"childrenIndex\":[16, 18, 29, 37, 39, 40], \"populationSize\":427290387585, \"filter\":\"#is_event_query$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"18\": [{ \"xAxis\": \"0\", \"yAxis\":79.8957702319091},{ \"xAxis\": \"1\", \"yAxis\":20.10422976809091},{\"childrenIndex\":[86, 124], \"populationSize\":70437357911, \"filter\":\"#has_clicks_tbl$0#has_distinct$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"19\": [{ \"xAxis\": \"0\", \"yAxis\":22.863232070479246},{ \"xAxis\": \"1\", \"yAxis\":77.13676792952076},{\"childrenIndex\":[], \"populationSize\":74047346293, \"filter\":\"#is_multi_query$1#has_actions_tbl$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}],\"20\": [{ \"xAxis\": \"0\", \"yAxis\":36.43204694793704},{ \"xAxis\": \"1\", \"yAxis\":63.56795305206296},{\"childrenIndex\":[19, 20, 44, 45], \"populationSize\":437476083649, \"filter\":\"#has_impressions_tbl$0#\",\"yName\":\"SUM(slots_millis_reduces)\"}]}"
    #nodeDic = json.loads(nodeDic.replace('\n', '').decode('string_escape'))
    print "nodeDic:"
    print nodeDic
    node = G.generateNode(nodeDic)
    edge = G.generateEdge(nodeDic)
    #print(ret)
    ret2 = '<svg xmlns="http://www.w3.org/2000/svg" width="480" height="260"><g transform="translate(50,30)"><rect x="0" y="0" width="100%" height="100%" fill="#ffffff"></rect><rect x="14" y="0" width="105" height="200" fill="steelblue" class="Clinton" id="48"></rect><rect x="139" y="8.333333333333343" width="105" height="191.66666666666666" fill="steelblue" class="Trump" id="46"></rect><rect x="264" y="175" width="105" height="25" fill="steelblue" class="Others" id="6"></rect><g class="axis" transform="translate(-10, 0)"><g transform="translate(0,200)" style="opacity: 1;"><line class="tick" x2="-6" y2="0"></line><text x="-9" y="0" dy=".32em" style="text-anchor: end;">0</text></g><g transform="translate(0,158.33333333333334)" style="opacity: 1;"><line class="tick" x2="-6" y2="0"></line><text x="-9" y="0" dy=".32em" style="text-anchor: end;">10</text></g><g transform="translate(0,116.66666666666667)" style="opacity: 1;"><line class="tick" x2="-6" y2="0"></line><text x="-9" y="0" dy=".32em" style="text-anchor: end;">20</text></g><g transform="translate(0,75)" style="opacity: 1;"><line class="tick" x2="-6" y2="0"></line><text x="-9" y="0" dy=".32em" style="text-anchor: end;">30</text></g><g transform="translate(0,33.33333333333334)" style="opacity: 1;"><line class="tick" x2="-6" y2="0"></line><text x="-9" y="0" dy=".32em" style="text-anchor: end;">40</text></g><path class="domain" d="M-6,0H0V200H-6"></path></g><g class="axis" transform="translate(0,210)"><g transform="translate(70.5,0)" style="opacity: 1;"><line class="tick" y2="6" x2="0"></line><text y="9" x="0" dy=".71em" style="text-anchor: middle;">Clinton</text></g><g transform="translate(195.5,0)" style="opacity: 1;"><line class="tick" y2="6" x2="0"></line><text y="9" x="0" dy=".71em" style="text-anchor: middle;">Trump</text></g><g transform="translate(320.5,0)" style="opacity: 1;"><line class="tick" y2="6" x2="0"></line><text y="9" x="0" dy=".71em" style="text-anchor: middle;">Others</text></g><path class="domain" d="M0,6V0H390V6"></path></g><text transform="translate(-30, -20)">% of vote</text><text x="195" y="-8px" text-anchor="middle" style="font-size: 16px; text-decoration: underline;">All</text></g></svg>'
    return (nodeDic, node, edge)
Exemple #22
0
        def getRSS(params, Na, Nb, blobs_by_point):
            """Return the sum of squared distances between all blobs and their lattice point"""
            vax, vay, vbx, vby, ox, oy = params
            lattice = Lattice(Na, Nb, [vax, vay], [vbx, vby], [ox, oy])

            lattice_points = lattice.getLatticePoints()
            sum = 0

            for i, point in enumerate(blobs_by_point):
                point_x, point_y = lattice_points[i]
                for blob in point:
                    blob_y, blob_x, r = blob
                    square_dist = (point_x - blob_x)**2 + (point_y - blob_y)**2

                    sum += square_dist

            return sum
    def __init__(self, args):
        Thread.__init__(self)
        self.args = args
        self.lattice = Lattice(size=args.size,
                               slider=args.slider,
                               onlyRedBlue=not args.any,
                               defKillers=args.defKillers,
                               density=args.density,
                               numRatio=args.numRatio,
                               redAdvantage=args.redAdvantage,
                               blueAdvantage=args.blueAdvantage,
                               redGrowth=args.redGrowth,
                               blueGrowth=args.blueGrowth,
                               deathRate=100000)

        self.args = args
        self.quit = False
def test_lattice_number_neigbors():
    ''' Test the number of neighbors in the lattice.'''

    lattice = Lattice(3, 3)

    for place in [(0, 0), (0, 1), (1, 1)]:
        answer = lattice.find_neighbors(place)
        assert len(answer) == 4, "Wrong number of neighbors"

    assert (2, 1) in lattice.find_neighbors((1, 1))

    try:
        fail = True
        lattice2 = Lattice(5, 1)
    except AssertionError:
        fail = False
    assert not fail
Exemple #25
0
def read_trj(trj_file):
    """
    return: Simulation
    parameters:
        trj_file: string | name of trj file
    """
    simulation = Simulation()
    with open(trj_file, 'r') as trj:

        while True:

            line = trj.readline()
            if not line:
                break
            lattice = Lattice()
            lattice.set_a(np.array(line.split(), dtype=float))
            lattice.set_b(np.array(trj.readline().split(), dtype=float))
            lattice.set_c(np.array(trj.readline().split(), dtype=float))

            configuration = Configuration(lattice=lattice)

            atom_types = trj.readline().split()
            atom_counts = np.array(trj.readline().split(), dtype=int)
            natom = np.sum(atom_counts)

            for i in xrange(natom):
                atom_record = trj.readline().split()
                atom_name = atom_record[0]
                atom_position = np.array(atom_record[1:], dtype=float)
                configuration.insert_atom(Atom(atom_name, atom_position))

            simulation.insert_configuration(configuration)

    return simulation
Exemple #26
0
 def add_bitext(self, src, tgt):
     '''
     Adds a training bitext.
     Input:
     src_data: filepath containing n-best list of src_data hypotheses
     tgt_data: string containing translation
     
     Postcondition:
     A source word lattice is constructed from src_data, compiled into a weighted FSA.
     A bitext containing the weighted source FSA and string tgt_data is stored.
     '''
     src_lattice = Lattice(syms=self.src_syms)
     src_lattice.load_delimited(src)
     # Weight the edges
     src_lattice.forward_backward_weights()
     # Add the NULL token at the front
     src_lattice.prepend_epsilon()
     
     self.src_data.append(src_lattice.fsa)
     # TODO: Figure out how to extract vocabulary from FSA (src_lattice.sigma)
     for arc in common.arcs(src_lattice.fsa):
         self.src_vocab.add(arc.ilabel)
     
     self.tgt_data.append(tgt)
     self.tgt_vocab = self.tgt_vocab.union(set(tgt.split()))
Exemple #27
0
def main():
	time_size = int(os.getenv("TIME_SIZE"))
	space_size = int(os.getenv("SPACE_SIZE"))
	dimension = int(os.getenv("DIMENSION"))
	beta = float(os.getenv("BETA"))

	lattice = Lattice(
		time_size, 
		space_size, 
		dimension, 
		beta,
		SU3,
	)
	print "Lattice initialization complete! Beginning simulation..."
	t0 = time.time()
	for i in range(1000):
		lattice.metropolisUpdate()
	print time.time() - t0
Exemple #28
0
 def __init__(self):
     """Initialise the main window"""
     self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable=E1101
                          ROOT.gClient.GetRoot(), # pylint: disable=E1101
                          SHARE_DIR+"main_frame.json")
     self.lattice = Lattice()
     self.beam_setup = None
     self.magnet_setup = None
     self.plot_setup = None
     self.plot_setup_options = [{"variable_type":0,
                                 "first_var":0,
                                 "plot_apertures":True}]
     self.window.set_button_action("&Beam Setup", self.beam_button_action)
     self.window.set_button_action("&Magnet Setup",
                                                   self.magnet_button_action)
     self.window.set_button_action("&Plot Setup", self.plot_button_action)
     self.window.set_button_action("E&xit", self.exit_button_action)
     self.update_plot()
Exemple #29
0
    def test_entropy_equalsSumOfParts(self):
        J = 1
        gJ = 1
        Tc = 123
        Nm = 1
        theta_D = 123
        N = 1
        F0 = 1
        mc = Magnetocaloric(J, gJ, Tc, Nm, theta_D, N, F0)
        mag = Magnetization(J, gJ, Tc, Nm)
        lat = Lattice(theta_D, N)
        temperature = 300
        magnetic_field = 0
        expected = mag.magnetic_entropy(
            temperature, magnetic_field) + lat.lattice_entropy(temperature)

        result = mc.entropy(temperature, magnetic_field)

        assert result == expected
Exemple #30
0
def main(opts):
    opts = opts if opts is not None else argv
    g = read_graph(opts[1:3])
    levels_to_build = int(opts[opts.index('-l') + 1]) if '-l' in opts else None
    start = time()
    lattice = Lattice(g, levels_to_build)
    elapsed = time() - start
    lattice.save('lattice.txt')
    print('Количество построенных уровней =', lattice.levels_count)
    print('Построение заняло время =', elapsed)
    print('Количество элементов решетки =', lattice.number_of_nodes())
    if '-i' in opts:
        filename = opts[opts.index('-fn') + 1] if '-fn' in opts else 'diagram.png'
        draw_lattice(lattice, filename)
        print(f'Диаграмма построена и сохранена в файл {filename}')
    if '-it' in opts:
        filename = opts[opts.index('-tfn') + 1] if '-fn' in opts else 'tree.png'
        draw_tree(g, filename)
        print(f'Изображение дерева построено и сохранено в файл {filename}')
Exemple #31
0
def train(args):
    # n_feature = 1 + (NUMBER_OF_POS + 2) ** (args.pos_lorder + args.pos_rorder + 1)
    n_feature = (HIDDEN + NUMBER_OF_POS) * NUMBER_OF_POS
    print('building CRF...')
    model = HigherOrderCRF.build(n_feature, args.pos_lorder, args.pos_rorder,
                                 args.posmodel, args.hoposmodel, args.lr,
                                 args.train_alpha, args.l2, args.test_alpha)
    model.init_weight()
    print('build lattice')
    l = Lattice(args.pos_lorder, args.pos_rorder, model)
    print('done')
    for epoch in range(args.epoch):
        print('Start epoch {}'.format(epoch + 1))
        s = time.time()
        n_word = 0
        n_corr = 0
        sum_log_ll = 0
        for [words, postags] in sent_tag_iter(args.train_data):
            postags = [pos2id[pos] for pos in postags]
            sufs = [sufvocab[suf] for suf in check_sufvocab(words)]
            caps = [word2capf(word) for word in words]
            words = [vocab[word] for word in check_vocab(words)]
            features = [words, sufs, caps]
            predtags = l.viterbe_decode_hocrf(features, train_flg=True)
            assert len(postags) == len(predtags)
            n_corr += sum(1 for i in range(len(postags))
                          if postags[i] == predtags[i])
            n_word += len(words)
            log_ll = l.update_hocrf(features, postags)
            sum_log_ll += log_ll
        print('Train accuracy : {} / {} = {}'.format(n_corr, n_word,
                                                     float(n_corr / n_word)))
        print('Train Log Likelifood : {}'.format(sum_log_ll))
        print('Running Time in this epoch : {} sec'.format(time.time() - s))

        if args.valid_data:
            valid_accuracy = validation(l, args.valid_data)
            print('Valid accuracy : {}'.format(valid_accuracy))

        if args.test_data:
            test_accuracy = validation(l, args.test_data)
            print('Test accuracy : {}'.format(test_accuracy))
Exemple #32
0
 def test_exact_cover(self):
     base_shapes = get_base_shapes()
     col_names = []
     for shape in base_shapes:
         col_names.append(shape.name)
     for i in range(1, 60 + 1):
         col_names.append(i)
     binary_matrix = generate_all_orientations_with_encodings(base_shapes)
     lattice = Lattice(binary_matrix, col_names)
     c = lattice.head.east
     while c is not lattice.head:
         r = c.south
         while r is not c:
             if r.key is not None and r.key is 0:
                 lattice.delete(r)
             r = r.south
         c = c.east
     solutions = generate_exact_cover_solutions(lattice)
     print("Len solution: ", len(solutions))
     self.assertIsNotNone(solutions)
 def make_lattice(latticeList,in_data):
     """ instanciate all elements from flattened node list"""
     lattice = Lattice()
     DEBUG_OFF('make_lattice for sollteilchen\n'+PARAMS['sollteilchen'].string())
     elements = read_elements(in_data)
     for ID in lattice_list:
         element      = elements[ID]
         element      = liofd2d(element)
         elementClass = element['type']
         elmItem      = (elementClass,element)
         # !!INSTANCIATE!!
         (label,instance) = instanciate_element(elmItem)
         section = instance.section if FLAGS['sections'] else '*'
         DEBUG_MODULE('instance {} {} {}'.format(label,instance,section))
         # add element instance to lattice
         if isinstance(instance,ELM._Node):
             lattice.add_element(instance)
     #     elif isinstance(instance,Lattice):
     #         lattice.concat(instance)       # concatenate partial with lattice
     return lattice   # the complete lattice
Exemple #34
0
 def test_cover_col2(self):
     col_names = ['a', 'b', 'c']
     matrix = [['0', '1', '1'], ['1', '0', '0'], ['1', '1', '1']]
     lattice = Lattice(matrix, col_names)
     c = lattice.head.east
     while c is not lattice.head:
         r = c.south
         while r is not c:
             if r.key is not None and r.key is '0':
                 lattice.delete(r)
                 print("Deleting lattice node")
             r = r.south
         c = c.east
     a = lattice.head.east
     lattice = cover_col(lattice, a)
     b = a.east
     lattice = cover_col(lattice, b)
     c = b.east
     lattice = cover_col(lattice, c)
     print(lattice)
Exemple #35
0
def test__init__default():
    lattice = Lattice()
    assert isinstance(lattice.a0, float)
    assert isinstance(lattice.H, np.ndarray)
    assert isinstance(lattice.a1, np.ndarray)
    assert isinstance(lattice.a2, np.ndarray)
    assert isinstance(lattice.a3, np.ndarray)

    assert lattice.H.shape == (3, 3)
    assert lattice.a1.shape == (3, )
    assert lattice.a2.shape == (3, )
    assert lattice.a3.shape == (3, )
Exemple #36
0
    def import_from_vasp(filename):
        """
        Import structure data from a VASP POSCAR or CONTCAR file.

        Args:
            filename (str): The file to import from.

        Returns:
            A Structure object.
        """
        with open(filename) as f:
            lines = f.readlines()

            name = lines[0].strip('\n')
            scale = float(lines[1])

            vectors = []
            for i in range(2, 5):
                vector = [
                    float(coord) * scale for coord in lines[i].split()[:3]
                ]
                vectors.append(vector)

            lattice = Lattice(vectors)

            num_per_species = []
            for x in lines[6].split():
                try:
                    num = int(x)
                    num_per_species.append(num)
                except ValueError:
                    pass
            element_species_symbols = lines[5].split()[:len(num_per_species)]
            atoms = []
            for symbol, num in zip(element_species_symbols, num_per_species):
                atoms += [symbol] * num

            if lines[7][0].lower() == 's':
                index = 8
            else:
                index = 7

            if (lines[index][0].lower() == 'c'
                    or lines[index][0].lower() == 'k'):
                is_cartesian = True
            else:
                is_cartesian = False
            index += 1
            positions = []
            for i in range(index, index + sum(num_per_species)):
                position = [float(coord) for coord in lines[i].split()[:3]]
                positions.append(position)
        return Structure(lattice, positions, atoms, is_cartesian, name)
Exemple #37
0
def test_energy_ferro():
    ''' Check the energy of the ferromagnetic state.'''

    size = 4
    coupling = 1.0

    lattice = Lattice(size, size)
    ham = Hamiltonian(lattice, coupling)

    assert ham.energy(
        ones((size, size), dtype=bool)
    ) == 2 * coupling * size * size, "Energy of ferromagnetic state is incorrect."
	def __init__(\
			self, dimX, dimY, energyScale, rate1, rate2, cat, \
			monomerAppear, monomerVanish, dimerVanish, dimerBreak, \
			monomerInitNum, dimer1InitNum, dimer2InitNum):
			
		MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 =  self.MOL_MONOMER,  self.MOL_DIMER1,  self.MOL_DIMER2
		
		self.lat 			= Lattice(dimX, dimY)
		self.energyScale	= energyScale
		self.rate1			= rate1
		self.rate2			= rate2
		self.cat			= cat
		
		self.monomerNum 	= monomerInitNum
		self.dimer1Num 		= dimer1InitNum
		self.dimer2Num 		= dimer2InitNum
		
		self.monomerAppear	= monomerAppear
		self.monomerVanish	= monomerVanish
		self.dimerVanish	= dimerVanish
		self.dimerBreak		= dimerBreak
				
		self.__initVars()
		
		self.lat.setAtomTypeNum(4)
		self.lat.setEnergyMatrix(array([\
			[ 2,  2,  2,  0],\
			[ 2,  2,  2,  0],\
			[ 2,  2,  2,  0],\
			[ 0,  0,  0,  0]]) * self.energyScale)
											
		self.lat.bindingEnergy = -1.0 * self.energyScale;
		
		mNum = monomerInitNum + dimer1InitNum + dimer2InitNum
		self.moleculeNum = mNum
		
#		initX = zeros(mNum)
#		initY = zeros(mNum)
		initX1 = randint(0, self.lat.dimX, self.monomerNum)
		initY1 = randint(0, self.lat.dimY, self.monomerNum)
		initX2 = randint(int(0.2*self.lat.dimX), int(0.4*self.lat.dimX), self.dimer1Num)
		initY2 = randint(int(0.2*self.lat.dimY), int(0.4*self.lat.dimY), self.dimer1Num)
		initX3 = randint(int(0.6*self.lat.dimX), int(0.8*self.lat.dimX), self.dimer2Num)
		initY3 = randint(int(0.6*self.lat.dimY), int(0.8*self.lat.dimY), self.dimer2Num)
		for n in range(self.monomerNum):
			self.lat.addMolecule(Molecule(MOL_MONOMER, initX1[n], initY1[n], self.moleculeTemp1))
		for n in range(self.dimer1Num):
			self.lat.addMolecule(Molecule(MOL_DIMER1,   initX2[n], initY2[n], self.moleculeTemp2))
		for n in range(self.dimer2Num):
			self.lat.addMolecule(Molecule(MOL_DIMER2,   initX3[n], initY3[n], self.moleculeTemp3))
Exemple #39
0
def m_fodo(params):
    kq       = params['kq [1/m^2]']
    lq       = params['quad [m]']
    ld       = params['drift [m]']
    particle = params['particle']
    qf = elm.QF(k0=kq, length=lq/2., label='QF/2', particle=particle)
    qd = elm.QD(k0=kq, length=lq,    label='QD',   particle=particle)
    dr = elm.D(        length=ld,    label='D',    particle=particle)
    
    cell = Lattice()
    cell.add_element(qf)
    cell.add_element(dr)
    cell.add_element(qd)
    cell.add_element(dr)
    cell.add_element(qf)
    return cell
	def __init__(\
			self, dimX, dimY, energyScale, rate, \
			monomerAppear, monomerVanish, dimerVanish, dimerBreak, \
			monomerInitNum, dimer1InitNum, dimer2InitNum):
			
		MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 =  self.MOL_MONOMER,  self.MOL_DIMER1,  self.MOL_DIMER2
		
		self.lat 			= Lattice(dimX, dimY)
		self.energyScale	= energyScale
		self.rate			= rate
		
		self.monomerNum 	= monomerInitNum
		self.dimer1Num 		= dimer1InitNum
		self.dimer2Num 		= dimer2InitNum
		
		self.monomerAppear	= monomerAppear
		self.monomerVanish	= monomerVanish
		self.dimerVanish	= dimerVanish
		self.dimerBreak		= dimerBreak
				
		self.__initVars()
		
		self.lat.setAtomTypeNum(6)
		self.lat.setEnergyMatrix(array([\
			[ 5,  5,  5, -3,  0,  0],\
			[ 5,  5,  5,  0,  3, -3],\
			[ 5,  5,  5,  0,  3, -3],\
			[-3,  0,  0,  0,  0,  0],\
			[ 0,  3,  3,  0,  0,  0],\
			[ 0, -3, -3,  0,  0,  0]]) * self.energyScale)
											
		self.lat.bindingEnergy = -5.0 * self.energyScale;
		
		mNum = monomerInitNum + dimer1InitNum + dimer2InitNum
		self.moleculeNum = mNum
		
		initX = randint(0, self.lat.dimX, mNum)
		initY = randint(0, self.lat.dimY, mNum)
		
		for n in range(self.monomerNum):
			self.lat.addMolecule(Molecule(MOL_MONOMER, initX[n], initY[n], self.moleculeTemp1))
		for n in range(self.dimer1Num):
			self.lat.addMolecule(Molecule(MOL_DIMER1,   initX[n], initY[n], self.moleculeTemp2))
		for n in range(self.dimer2Num):
			self.lat.addMolecule(Molecule(MOL_DIMER2,   initX[n], initY[n], self.moleculeTemp3))
Exemple #41
0
def make_thin (kf1,kf2,ld,anz=1,verbose=False):
    kd1 = kf1       # k1 for qf1 & qd1
    ld1 = lf1 = 0.4 # len qf1 & qd1
    ff1 = kf1*lf1   # focal length qf1
    fd1 = kd1*ld1   # focal length qd1

    kf2 = kf2
    kd2 = kf2       # same as above for qf2 & qd2
    lf2 = ld2 = lf1
    ff2 = kf2*lf2
    fd2 = kd2*ld2

    slices = 1      # present the quad by 1 thin-quads   (bad!)
    slices = 3      # present the quad by 3 thin-quads   (better!)
    slices = 6      # present the quad by 6 thin-quads   (near perfect!)
    
    DL  = D(length=ld,label='L')
    QF1 = QFth(k0=kf1,length=0.5*lf1/slices,label='QF1')
    QF2 = QFth(k0=kf2,length=0.5*lf2/slices,label='QF2')
    QD1 = QDth(k0=kd1,length=0.5*ld1/slices,label='QD1')
    QD2 = QDth(k0=kd2,length=0.5*ld2/slices,label='QD2')

    cell = Lattice()
    for i in range(slices): cell.add_element(QD1)
    for i in range(slices): cell.add_element(QF1)
    cell.add_element(DL)
    for i in range(slices): cell.add_element(QD2)
    for i in range(slices): cell.add_element(QF2)
    for i in range(slices): cell.add_element(QF2)
    for i in range(slices): cell.add_element(QD2)
    cell.add_element(DL)
    for i in range(slices): cell.add_element(QF1)
    for i in range(slices): cell.add_element(QD1)

    lat = Lattice()
    for i in range(anz):
        lat.concat(cell)
    lat.cell()
    mcell = lat.accel
    betax = lat.betax0
    betay = lat.betay0

    if verbose:
        # {:.3f}
        print('L= {:.3f}'.format(ld),end=' ')
        print('triplet 1: kf= {:.3f}, kd={:.3f}'.format(kf1,kd1),end=' | ')
        print('triplet 2: kf= {:.3f}, kd={:.3f}'.format(kf2,kd2),end=' | ')
        print('betax= {:.3f}, betay= {:.3f}'.format(betax,betay))
    return lat,betax,betay
Exemple #42
0
from matplotlib import pyplot as plt
from lattice import Lattice
from matplotlib.patches import FancyBboxPatch
from matplotlib.transforms import Bbox
from mpl_toolkits.mplot3d import Axes3D
from numpy import sqrt, array
from numpy.linalg import norm
from fancyArrows import Arrow3D

lv = [[1, 0, 0],[.5, .5 * sqrt(3), 0],[.5, .5 * 1/sqrt(3), sqrt(2. / 3)]]
lb = [[0, 0, 0], [.5, 0, 0], [0, .5, 0], [0, 0, .5]]
pyro = Lattice(lv, lb)
h = {(1, 0, 0): array([[ 0., -1.,  0.,  0.],
                       [ 0.,  0.,  0.,  0.],
                       [ 0.,  0.,  0.,  0.],
                       [ 0.,  0.,  0.,  0.]]), 
     (0, 0, 1): array([[ 0.,  0.,  0., -1.],
                       [ 0.,  0.,  0.,  0.],
                       [ 0.,  0.,  0.,  0.],
                       [ 0.,  0.,  0.,  0.]]), 
     (0, -1, 1): array([[ 0.,  0.,  0.,  0.],
                        [ 0.,  0.,  0.,  0.],
                        [ 0.,  0.,  0., -1.],
                        [ 0.,  0.,  0.,  0.]]), 
     (0, 0, 0): array([[ 0., -1., -1., -1.],
                       [-1.,  0., -1., -1.],
                       [-1., -1.,  0., -1.],
                       [-1., -1., -1.,  0.]]), 
     (-1, 1, 0): array([[ 0.,  0.,  0.,  0.],
                        [ 0.,  0., -1.,  0.],
                        [ 0.,  0.,  0.,  0.],
Exemple #43
0
 def complete_lattice(self):
     lattice = Lattice(self.dataset)
     lattice.build_lattice()
     return lattice
class Experiment:

	ATOM_MONOMER, ATOM_DIMER1, ATOM_DIMER2, ATOM_SITE = 0, 1, 2, 3
	MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 = 0, 1, 2
	
	# Monomer Temp
	moleculeTemp1 = map(Atom.fromTuple, [\
		(ATOM_MONOMER,0,0)])
	# I Dimer
	moleculeTemp2 = map(Atom.fromTuple, [\
		(ATOM_DIMER1,	0,	0),		(ATOM_DIMER1,	0,	1), \
		(ATOM_SITE,		1,	0),		(ATOM_SITE,		1,	1), \
		(ATOM_SITE,		-1,	0),		(ATOM_SITE,		-1,	1)])
	# L Dimer
	moleculeTemp3 = map(Atom.fromTuple, [\
		(ATOM_DIMER2,	0,	-1),	(ATOM_DIMER2,	-1,	0), \
		(ATOM_SITE,		1,	-1),	(ATOM_SITE,		-1,	1), \
		(ATOM_SITE,		0,	0,	2)])
	
	def __init__(\
			self, dimX, dimY, energyScale, rate1, rate2, cat, \
			monomerAppear, monomerVanish, dimerVanish, dimerBreak, \
			monomerInitNum, dimer1InitNum, dimer2InitNum):
			
		MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 =  self.MOL_MONOMER,  self.MOL_DIMER1,  self.MOL_DIMER2
		
		self.lat 			= Lattice(dimX, dimY)
		self.energyScale	= energyScale
		self.rate1			= rate1
		self.rate2			= rate2
		self.cat			= cat
		
		self.monomerNum 	= monomerInitNum
		self.dimer1Num 		= dimer1InitNum
		self.dimer2Num 		= dimer2InitNum
		
		self.monomerAppear	= monomerAppear
		self.monomerVanish	= monomerVanish
		self.dimerVanish	= dimerVanish
		self.dimerBreak		= dimerBreak
				
		self.__initVars()
		
		self.lat.setAtomTypeNum(4)
		self.lat.setEnergyMatrix(array([\
			[ 2,  2,  2,  0],\
			[ 2,  2,  2,  0],\
			[ 2,  2,  2,  0],\
			[ 0,  0,  0,  0]]) * self.energyScale)
											
		self.lat.bindingEnergy = -1.0 * self.energyScale;
		
		mNum = monomerInitNum + dimer1InitNum + dimer2InitNum
		self.moleculeNum = mNum
		
		initX = randint(0, self.lat.dimX, mNum)
		initY = randint(0, self.lat.dimY, mNum)
		
		for n in range(self.monomerNum):
			self.lat.addMolecule(Molecule(MOL_MONOMER, initX[n], initY[n], self.moleculeTemp1))
		for n in range(self.dimer1Num):
			self.lat.addMolecule(Molecule(MOL_DIMER1,   initX[n], initY[n], self.moleculeTemp2))
		for n in range(self.dimer2Num):
			self.lat.addMolecule(Molecule(MOL_DIMER2,   initX[n], initY[n], self.moleculeTemp3))
		
	def __initVars(self):	
		ATOM_MONOMER, ATOM_DIMER1, ATOM_DIMER2, ATOM_SITE = \
		self.ATOM_MONOMER, self.ATOM_DIMER1, self.ATOM_DIMER2, self.ATOM_SITE
		
		MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 =  self.MOL_MONOMER,  self.MOL_DIMER1,  self.MOL_DIMER2

		self.newDimerTemp = range(8)
		self.newDimerTemp[0] = map(Atom.fromTuple, [\
			(ATOM_DIMER1,	0,	0), 	(ATOM_DIMER1,	1,	0), \
			(ATOM_SITE,		0,	1),		(ATOM_SITE,		1,	1), \
			(ATOM_SITE,		0,	-1),	(ATOM_SITE,		1,	-1)] )
		self.newDimerTemp[1] = map(Atom.fromTuple, [\
			(ATOM_DIMER1,	0,	0),		(ATOM_DIMER1,	-1,	0), \
			(ATOM_SITE,		0,	1),		(ATOM_SITE,		-1,	1), \
			(ATOM_SITE,		0,	-1),	(ATOM_SITE,		-1,	-1)] )
		self.newDimerTemp[2] = map(Atom.fromTuple, [\
			(ATOM_DIMER1,	0,	0),		(ATOM_DIMER1,	0,	1), \
			(ATOM_SITE,		1,	0),		(ATOM_SITE,		1,	1), \
			(ATOM_SITE,		-1,	0),		(ATOM_SITE,		-1,	1)] )
		self.newDimerTemp[3] = map(Atom.fromTuple, [\
			(ATOM_DIMER1,	0,	0),		(ATOM_DIMER1,	0,	-1), \
			(ATOM_SITE,		1,	0),		(ATOM_SITE,		1,	-1), \
			(ATOM_SITE,		-1,	0),		(ATOM_SITE,		-1,	-1)] )
		self.newDimerTemp[4] = map(Atom.fromTuple, [\
			(ATOM_DIMER2,	0,	1),		(ATOM_DIMER2,	-1,	0), \
			(ATOM_SITE,		1,	1),		(ATOM_SITE,		-1,	-1),\
			(ATOM_SITE,		0,	0,	2)])
		self.newDimerTemp[5] = map(Atom.fromTuple, [\
			(ATOM_DIMER2,	0,	1),		(ATOM_DIMER2,	1,	0), \
			(ATOM_SITE,		-1,	1),		(ATOM_SITE,		1,	-1),\
			(ATOM_SITE,		0,	0,	2)])
		self.newDimerTemp[6] = map(Atom.fromTuple, [\
			(ATOM_DIMER2,	0,	-1),	(ATOM_DIMER2,	1,	0), \
			(ATOM_SITE,		-1,	-1),	(ATOM_SITE,		1,	1), \
			(ATOM_SITE,		0,	0,	2)])
		self.newDimerTemp[7] = map(Atom.fromTuple, [\
			(ATOM_DIMER2,	0,	-1),	(ATOM_DIMER2,	-1,	0), \
			(ATOM_SITE,		1,	-1),	(ATOM_SITE,		-1,	1), \
			(ATOM_SITE,		0,	0,	2)])
		self.reactDirMap = [[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[-1,-1],[1,-1]]
		
	colorScale = ( [
		[0.20, 0.20, 0.20],\
		[0.30, 0.00, 0.00],\
		[0.00, 0.30, 0.00],\
		[0.05, 0.05, 0.05]] )
		
	def colorMap(self, lattice):
		return clip(tensordot(lattice.atomNumMap, self.colorScale, axes=([0,0])), 0, 1)
		
	def run(self, simulationTime, outputPeriod, display, outputFileName):
		simTime		= simulationTime
		#display		= display
		#outputFileName	= outputFileName
		
		lat = self.lat
		colorMap = self.colorMap
		reactDirMap = self.reactDirMap
		moleculeNum = self.moleculeNum
		moleculeTemp1 = self.moleculeTemp1
		newDimerTemp = self.newDimerTemp
		ATOM_MONOMER, ATOM_DIMER1, ATOM_DIMER2, ATOM_SITE = \
			self.ATOM_MONOMER, self.ATOM_DIMER1, self.ATOM_DIMER2, self.ATOM_SITE
		MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 =  self.MOL_MONOMER,  self.MOL_DIMER1,  self.MOL_DIMER2

		
		if outputFileName == None:
			fileFlag = False
		else:
			fileFlag = True
			file = open(outputFileName, 'w')
			
		if display:
			fig = figure()
			img = imshow(self.colorMap(lat), interpolation='none')
			ioff()
		
		lat.newDimerNum = zeros((3,3), int)
		
		tMoveMol 		= zeros(simTime, int)
		tMoveDir 		= zeros(simTime, int)
		tMoveDis 		= zeros(simTime, int)
		tMoveProb 		= zeros(simTime)
		
		rMoveMol 		= zeros(simTime, int)
		rMoveDir 		= zeros(simTime, int)
		rMoveProb 		= zeros(simTime)
		
		reactMol 		= zeros(simTime, int)
		reactDir 		= zeros(simTime, int)
		reactAtom 		= zeros(simTime, int)
		reactProb		= rand(simTime)
		
		degProb 		= rand(simTime)
		
		newX 			= zeros(simTime, int)
		newY 			= zeros(simTime, int)
		newProb 		= rand(simTime)
		
		bindProb 		= rand(simTime)
		
		def expRandTime(rate=1.):
			if rate > 0.:
				return -log(rand())/rate
			else:
				return float('inf')
		
		class Movement:
			def reset(self):
				newSpeed = float(self.speedFunc())
				if newSpeed > 0.:
					self.wait = self.timeFunc()/newSpeed
					self.currentSpeed = newSpeed
				else:
					self.wait = float('inf')
					self.currentSpeed = 0.
				return self.wait
			def updateParam(self):
				newSpeed = float(self.speedFunc())
				if newSpeed == self.currentSpeed:
					pass
				elif self.currentSpeed > 0.:
					if newSpeed > 0.:
						self.wait = self.wait * (self.currentSpeed/newSpeed)
						self.currentSpeed = newSpeed
					else:
						self.wait = float('inf')
						self.currentSpeed = 0.
				else:
					return self.reset()
			def __call__(self):
				return self.moveFunc(self)
			def __init__(self,moveFunc,timeFunc,speedFunc):
				self.moveFunc = moveFunc
				self.timeFunc = timeFunc
				self.speedFunc = speedFunc
				self.currentSpeed = 0.
				self.wait = 0.
				
		def doTranslation(self):
			# Translate one molecule
			tMoveMol = randint(0, lat.moleculeNum)
			tMoveDir = randint(0, 2)
			tMoveDis = randint(0, 2) * 2 - 1
			tMoveProb = rand()

			dx = tMoveDis * tMoveDir
			dy = tMoveDis * (1 - tMoveDir)
			lat.translateMoleculeByIndex(tMoveMol, dx, dy, tMoveProb)
			return False
		def doRotation(self):
			# Rotate one molecule
			rMoveDir = randint(0, 2)
			rMoveMol = randint(0, lat.moleculeNum)
			rMoveProb = rand()
			
			if lat.moleculeList[rMoveMol] != MOL_MONOMER:
				if rMoveDir == 0:
					lat.rotateMoleculeCWByIndex(rMoveMol, rMoveProb)
				else:
					lat.rotateMoleculeCCWByIndex(rMoveMol, rMoveProb)
			return False
		def subVacateMonomer(ra):
			rm = ra.parent
			rm.boundMonomer -= ra.copies
			lat.raiseMolecule(rm)
			ra.type = ATOM_SITE
			lat.layMolecule(rm)
		def subGetMonomer(ra):
			rm = ra.parent
			rm.boundMonomer += ra.copies
			lat.raiseMolecule(rm)
			ra.type = ATOM_MONOMER
			lat.layMolecule(rm)
		def doAttachDetach(self):
			lm = lat.atomList[ATOM_MONOMER]
			ra = lm[randint(0,len(lm))]
			if ra.parent.type == MOL_MONOMER:
				ls = filter(lambda a:a.type == ATOM_SITE,lat.getAtomListAt(ra.x, ra.y))
				if len(ls) == 0:
					return False
				ra2 = ls[0]
				subGetMonomer(ls[0])
				lat.removeMolecule(ra.parent)
				return True
			else:
				p = rand()
				if p < exp(ra.copies*lat.bindingEnergy):
					subVacateMonomer(ra)
					lat.addMolecule(Molecule(MOL_MONOMER, ra.x, ra.y, moleculeTemp1))
					return True
			return False
		def doMonomerBirth(self):
			newX = randint(floor(lat.dimX*0.0), floor(lat.dimX*1.0))
			newY = randint(floor(lat.dimY*0.0), floor(lat.dimY*1.0))
			lat.addMolecule(Molecule(MOL_MONOMER, newX, newY, moleculeTemp1))
			return True
		def doMonomerBirth2(self):
			newX = randint(floor(lat.dimX*0.4), floor(lat.dimX*0.6))
			newY = randint(floor(lat.dimY*0.4), floor(lat.dimY*0.6))
			lat.addMolecule(Molecule(MOL_MONOMER, newX, newY, moleculeTemp1))
			return True
		def doMonomerDeath(self):
			al = lat.atomList[ATOM_MONOMER]
			ra = al[randint(0,len(al))]
			rm = ra.parent
			if rm.type == MOL_MONOMER:
				lat.removeMolecule(rm)
				return True
			else:
				p = rand()
				if p < exp(ra.copies*lat.bindingEnergy):
					subVacateMonomer(ra)
					return True
			return False
		def subRemoveDimer(rm):
			for atom in rm.atomList:
				if atom.type == ATOM_MONOMER:
					lat.addMolecule(Molecule(MOL_MONOMER, atom.x, atom.y, moleculeTemp1))
			lat.removeMolecule(rm)
		def doDimerDeath(self):
			a1,a2 = lat.atomList[ATOM_DIMER1],lat.atomList[ATOM_DIMER2]
			n1,n2 = len(a1),len(a2)
			m = randint(0,n1+n2)
			if m < n1:
				ra = a1[m]
			else:
				ra = a2[m-n1]
			subRemoveDimer(ra.parent)
			return True
		def subMakeDimer(type,rd,ra,ra2):
			# I-shaped dimer
			if type == 0:
				lat.addMolecule(Molecule(MOL_DIMER1, ra.x, ra.y, newDimerTemp[rd]))
			# L-shaped dimer
			else:
				lat.addMolecule(Molecule(MOL_DIMER2, ra2.x, ra.y, newDimerTemp[rd]))
			lat.newDimerNum[ra.parent.type, ra2.parent.type] += 1
			# Remove the involved monomers
			for atom in [ra, ra2]:
				rm = atom.parent
				if rm.type == MOL_MONOMER:
					lat.removeMolecule(rm)
				else:
					subVacateMonomer(atom)
		def doDimerization(self,type=0):
			al = lat.atomList[ATOM_MONOMER]
			ra = al[randint(0,len(al))]
			rd = randint(0, 4) + type*4
			x2 = ra.x + reactDirMap[rd][0]
			y2 = ra.y + reactDirMap[rd][1]
			
			if 0 < lat.getDataXY(lat.atomNumMap[ATOM_MONOMER], x2, y2):
				for ra2 in lat.getAtomListAt(x2, y2):
					if ra2.type == ATOM_MONOMER:
						subMakeDimer(type,rd,ra,ra2)
						return True
			return False
		doDimerizationI = lambda s: doDimerization(s,0)
		doDimerizationL = lambda s: doDimerization(s,1)
		def doCatDimerization(self,type=0):
			al = lat.atomList[ATOM_MONOMER]
			ra = al[randint(0,len(al))]
			if ra.parent.type != MOL_MONOMER:
				rd = randint(0, 4) + type*4
				x2 = ra.x + reactDirMap[rd][0]
				y2 = ra.y + reactDirMap[rd][1]
				if 0 < lat.getDataXY(lat.atomNumMap[ATOM_MONOMER], x2, y2):
					for ra2 in lat.getAtomListAt(x2, y2):
						if ra2.type == ATOM_MONOMER and ra2.parent == ra.parent:
							subMakeDimer(type,rd,ra,ra2)
							return True
			return False
		doCatDimerizationI = lambda s: doCatDimerization(s,0)
		doCatDimerizationL = lambda s: doCatDimerization(s,1)
		def doAbsorbingBC(self):
			i = randint(0, lat.moleculeNum)
			rm = lat.moleculeList[i]
			x = rm.x%lat.dimX
			y = rm.y%lat.dimY
			if 0 == x*y:
				if rm.type == MOL_MONOMER:
					lat.removeMolecule(rm)
				else:
					subRemoveDimer(rm)
				return True
			return False
		def doDraw(self):
			img.set_array(colorMap(lat))
			draw()
			return False
		def doRecord(self):
			newDimerNum = lat.newDimerNum
			file.write('# New Dimer Num Per Interval\n')
			for mt1 in newDimerNum:
				file.write('# ')
				for mt2 in mt1:
					file.write('{} '.format(mt2))
				file.write('\n')
			file.write('# \n')
			newDimerNum *= 0
			for atomType in lat.atomNumMap:
				for row in atomType:
					for col in row:
						file.write('{} '.format(col))
					file.write('\n')
				file.write('\n')
			file.write('\n')
			return False
		
		mvList = [ \
			Movement(doTranslation,expRandTime,lambda:lat.moleculeNum), \
			Movement(doRotation,expRandTime,lambda:lat.moleculeNum), \
			Movement(doAbsorbingBC,expRandTime,lambda:5. * lat.moleculeNum), \
			Movement(doAttachDetach,expRandTime,lambda:5. * len(lat.atomList[ATOM_MONOMER])), \
			#Movement(doDimerizationI,expRandTime,lambda:self.rate1 * len(lat.atomList[ATOM_MONOMER])), \
			#Movement(doDimerizationL,expRandTime,lambda:self.rate2 * len(lat.atomList[ATOM_MONOMER])), \
			Movement(doCatDimerizationI,expRandTime,lambda:self.cat * self.rate1 * len(lat.atomList[ATOM_MONOMER])), \
			Movement(doCatDimerizationL,expRandTime,lambda:self.cat * self.rate2 * len(lat.atomList[ATOM_MONOMER])), \
			Movement(doDimerDeath,expRandTime,lambda:self.dimerVanish * (len(lat.atomList[ATOM_DIMER1])+len(lat.atomList[ATOM_DIMER2]))/2), \
			Movement(doMonomerBirth2,expRandTime,lambda:self.monomerAppear), \
			Movement(doMonomerDeath,expRandTime,lambda:self.monomerVanish * len(lat.atomList[ATOM_MONOMER]))  ]
		if display:
			mvList.append(Movement(doDraw,lambda:1,lambda:1./outputPeriod))
		if fileFlag:
			mv = Movement(doRecord,lambda:1,lambda:1./outputPeriod)
			#mv.newDimerNum = newDimerNum
			mvList.append(mv)

		t = 0
		for m in mvList:
			m.reset()
		mvList.sort(key=attrgetter('wait'))
		wait = mvList[0].wait
		t += wait
		while t < simTime:
			for m in mvList:
				m.wait -= wait
			isToUpdate = mvList[0]()
			if isToUpdate:
				for m in mvList:
					m.updateParam()
			mvList[0].reset()
			mvList.sort(key=attrgetter('wait'))
			wait = mvList[0].wait
			t += wait
			
		if fileFlag:
			file.close()

		return
class Experiment:

	ATOM_MONOMER, ATOM_DIMER1, ATOM_DIMER2, ATOM_SITE, ATOM_REP, ATOM_ATT = 0, 1, 2, 3, 4, 5
	MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 = 0, 1, 2
	
	# Monomer Temp
	moleculeTemp1 = {'atomList': map(Atom.fromTuple, [\
		(ATOM_MONOMER,0,0), \
		(ATOM_REP,0,1),(ATOM_REP,1,0),(ATOM_REP,-1,0), \
		(ATOM_REP,1,1),(ATOM_REP,-1,1)]), 'dir': (0,1)}
	# I Dimer
	moleculeTemp2 = map(Atom.fromTuple, [\
		(ATOM_DIMER1,	0,	0),		(ATOM_DIMER1,	0,	1), \
		(ATOM_SITE,		1,	0),		(ATOM_SITE,		1,	1), \
		(ATOM_SITE,		-1,	0),		(ATOM_SITE,		-1,	1)])
	# L Dimer
	moleculeTemp3 = map(Atom.fromTuple, [\
		(ATOM_DIMER2,	0,	-1),	(ATOM_DIMER2,	-1,	0), \
		(ATOM_SITE,		1,	-1),	(ATOM_SITE,		-1,	1), \
		(ATOM_SITE,		0,	0 ),(ATOM_SITE,		0,	0)])
	
	def __init__(\
			self, dimX, dimY, energyScale, rate, \
			monomerAppear, monomerVanish, dimerVanish, dimerBreak, \
			monomerInitNum, dimer1InitNum, dimer2InitNum):
			
		MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 =  self.MOL_MONOMER,  self.MOL_DIMER1,  self.MOL_DIMER2
		
		self.lat 			= Lattice(dimX, dimY)
		self.energyScale	= energyScale
		self.rate			= rate
		
		self.monomerNum 	= monomerInitNum
		self.dimer1Num 		= dimer1InitNum
		self.dimer2Num 		= dimer2InitNum
		
		self.monomerAppear	= monomerAppear
		self.monomerVanish	= monomerVanish
		self.dimerVanish	= dimerVanish
		self.dimerBreak		= dimerBreak
				
		self.__initVars()
		
		self.lat.setAtomTypeNum(6)
		self.lat.setEnergyMatrix(array([\
			[ 5,  5,  5, -3,  0,  0],\
			[ 5,  5,  5,  0,  3, -3],\
			[ 5,  5,  5,  0,  3, -3],\
			[-3,  0,  0,  0,  0,  0],\
			[ 0,  3,  3,  0,  0,  0],\
			[ 0, -3, -3,  0,  0,  0]]) * self.energyScale)
											
		self.lat.bindingEnergy = -5.0 * self.energyScale;
		
		mNum = monomerInitNum + dimer1InitNum + dimer2InitNum
		self.moleculeNum = mNum
		
		initX = randint(0, self.lat.dimX, mNum)
		initY = randint(0, self.lat.dimY, mNum)
		
		for n in range(self.monomerNum):
			self.lat.addMolecule(Molecule(MOL_MONOMER, initX[n], initY[n], self.moleculeTemp1))
		for n in range(self.dimer1Num):
			self.lat.addMolecule(Molecule(MOL_DIMER1,   initX[n], initY[n], self.moleculeTemp2))
		for n in range(self.dimer2Num):
			self.lat.addMolecule(Molecule(MOL_DIMER2,   initX[n], initY[n], self.moleculeTemp3))
		
	def __initVars(self):	
		ATOM_MONOMER, ATOM_DIMER1, ATOM_DIMER2, ATOM_SITE, ATOM_REP, self.ATOM_ATT = \
		self.ATOM_MONOMER, self.ATOM_DIMER1, self.ATOM_DIMER2, self.ATOM_SITE, self.ATOM_REP, self.ATOM_ATT
		
		MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 =  self.MOL_MONOMER,  self.MOL_DIMER1,  self.MOL_DIMER2

		self.newDimerTemp = range(8)
		self.newDimerTemp[0] = map(Atom.fromTuple, [\
			(ATOM_DIMER1,	0,	0), 	(ATOM_DIMER1,	1,	0), \
			(ATOM_SITE,		0,	1),		(ATOM_SITE,		1,	1), \
			(ATOM_SITE,		0,	-1),	(ATOM_SITE,		1,	-1)] )
		self.newDimerTemp[1] = map(Atom.fromTuple, [\
			(ATOM_DIMER1,	0,	0),		(ATOM_DIMER1,	-1,	0), \
			(ATOM_SITE,		0,	1),		(ATOM_SITE,		-1,	1), \
			(ATOM_SITE,		0,	-1),	(ATOM_SITE,		-1,	-1)] )
		self.newDimerTemp[2] = map(Atom.fromTuple, [\
			(ATOM_DIMER1,	0,	0),		(ATOM_DIMER1,	0,	1), \
			(ATOM_SITE,		1,	0),		(ATOM_SITE,		1,	1), \
			(ATOM_SITE,		-1,	0),		(ATOM_SITE,		-1,	1)] )
		self.newDimerTemp[3] = map(Atom.fromTuple, [\
			(ATOM_DIMER1,	0,	0),		(ATOM_DIMER1,	0,	-1), \
			(ATOM_SITE,		1,	0),		(ATOM_SITE,		1,	-1), \
			(ATOM_SITE,		-1,	0),		(ATOM_SITE,		-1,	-1)] )
		self.newDimerTemp[4] = map(Atom.fromTuple, [\
			(ATOM_DIMER2,	0,	1),		(ATOM_DIMER2,	-1,	0), \
			(ATOM_SITE,		1,	1),		(ATOM_SITE,		-1,	-1),\
			(ATOM_SITE,		0,	0,	2)])
		self.newDimerTemp[5] = map(Atom.fromTuple, [\
			(ATOM_DIMER2,	0,	1),		(ATOM_DIMER2,	1,	0), \
			(ATOM_SITE,		-1,	1),		(ATOM_SITE,		1,	-1),\
			(ATOM_SITE,		0,	0,	2)])
		self.newDimerTemp[6] = map(Atom.fromTuple, [\
			(ATOM_DIMER2,	0,	-1),	(ATOM_DIMER2,	1,	0), \
			(ATOM_SITE,		-1,	-1),	(ATOM_SITE,		1,	1), \
			(ATOM_SITE,		0,	0,	2)])
		self.newDimerTemp[7] = map(Atom.fromTuple, [\
			(ATOM_DIMER2,	0,	-1),	(ATOM_DIMER2,	-1,	0), \
			(ATOM_SITE,		1,	-1),	(ATOM_SITE,		-1,	1), \
			(ATOM_SITE,		0,	0,	2)])
		self.reactDirMap = [[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[-1,-1],[1,-1]]
		
	colorScale = ( [
		[0.20, 0.20, 0.20],\
		[0.30, 0.00, 0.00],\
		[0.00, 0.30, 0.00],\
		[0.00, 0.00, 0.00],\
		[0.05, 0.05, 0.05],\
		[0.05, 0.05, 0.05]] )
		
	def colorMap(self, lattice):
		return clip(tensordot(lattice.atomNumMap, self.colorScale, axes=([0,0])), 0, 1)
		
	def run(self, simulationTime, outputPeriod, display, outputFileName):
		simTime		= simulationTime
		#display		= display
		#outputFileName	= outputFileName
		
		lat = self.lat
		reactDirMap = self.reactDirMap
		moleculeNum = self.moleculeNum
		moleculeTemp1 = self.moleculeTemp1
		newDimerTemp = self.newDimerTemp
		ATOM_MONOMER, ATOM_DIMER1, ATOM_DIMER2, ATOM_SITE, ATOM_REP = \
			self.ATOM_MONOMER, self.ATOM_DIMER1, self.ATOM_DIMER2, self.ATOM_SITE, self.ATOM_REP
		MOL_MONOMER, MOL_DIMER1, MOL_DIMER2 =  self.MOL_MONOMER,  self.MOL_DIMER1,  self.MOL_DIMER2

		
		if outputFileName == None:
			fileFlag = False
		else:
			fileFlag = True
			file = open(outputFileName, 'w')
			
		if display:
			fig = figure()
			img = imshow(self.colorMap(lat), interpolation='none')
			ioff()
		
		newDimerNum = zeros((3,3), int)
		
		tMoveMol 		= zeros(simTime, int)
		tMoveDir 		= zeros(simTime, int)
		tMoveDis 		= zeros(simTime, int)
		tMoveProb 		= zeros(simTime)
		
		rMoveMol 		= zeros(simTime, int)
		rMoveDir 		= zeros(simTime, int)
		rMoveProb 		= zeros(simTime)
		
		reactMol 		= zeros(simTime, int)
		reactDir 		= zeros(simTime, int)
		reactAtom 		= zeros(simTime, int)
		reactProb		= rand(simTime)
		
		degProb 		= rand(simTime)
		
		newX 			= zeros(simTime, int)
		newY 			= zeros(simTime, int)
		newProb 		= rand(simTime)
		
		bindProb 		= rand(simTime)
		
		for t in range(simTime):

			# Translate one molecule
			tMoveMol[t] = randint(0, lat.moleculeNum)
			tMoveDir[t] = randint(0, 2)
			tMoveDis[t] = randint(0, 2) * 2 - 1
			tMoveProb[t] = rand()

			dx = tMoveDis[t] * tMoveDir[t]
			dy = tMoveDis[t] * (1 - tMoveDir[t])
			lat.translateMoleculeByIndex(tMoveMol[t], dx, dy, tMoveProb[t])
			
			# Rotate one molecule
			rMoveDir[t] = randint(0, 2)
			rMoveMol[t] = randint(0, lat.moleculeNum)
			rMoveProb[t] = rand()
			
			if lat.moleculeList[rMoveMol[t]] != MOL_MONOMER:
				if rMoveDir[t] == 0:
					lat.rotateMoleculeCWByIndex(rMoveMol[t], rMoveProb[t])
				else:
					lat.rotateMoleculeCCWByIndex(rMoveMol[t], rMoveProb[t])
			
			if reactProb[t] < self.rate:			
				# Pick one monomer atom and see if a dimer can be formed
				molN = len(lat.atomList[ATOM_MONOMER]) + len(lat.atomList[ATOM_DIMER1])/2 + len(lat.atomList[ATOM_DIMER2])/2;
				reactAtom[t] = randint(0, molN)
				
				if reactAtom[t] < len(lat.atomList[ATOM_MONOMER]):
					ra = lat.atomList[ATOM_MONOMER][reactAtom[t]]

					rd = reactDir[t] = randint(0, 8)
					
					x2 = ra.x + reactDirMap[rd][0]
					y2 = ra.y + reactDirMap[rd][1]
				
					#anl = lat.getAtomNumAt(x2, y2)
					
					if 0 < lat.getDataXY(lat.atomNumMap[ATOM_MONOMER], x2, y2):
						for ra2 in lat.getAtomListAt(x2, y2):
							if ra2.type == ATOM_MONOMER and ra.parent.dir == ra2.parent.dir:
								# I-shaped dimer
								if rd < 4:
									lat.addMolecule(Molecule(MOL_DIMER1, ra.x, ra.y, newDimerTemp[rd]))
								# L-shaped dimer
								else:
									lat.addMolecule(Molecule(MOL_DIMER2, ra2.x, ra.y, newDimerTemp[rd]))
								newDimerNum[ra.parent.type, ra2.parent.type] = newDimerNum[ra.parent.type, ra2.parent.type] + 1
								# Remove the involved monomers
								for atom in [ra, ra2]:
									rm = atom.parent
									if rm.type == MOL_MONOMER:
										lat.removeMolecule(rm)
									else:
										lat.raiseMolecule(rm)
										atom.type = ATOM_SITE
										lat.layMolecule(rm)							
								break
			
			
			reactMol[t] = randint(0, lat.moleculeNum)
			rm = lat.moleculeList[reactMol[t]]
			
			# Death of monomer
			if rm.type == MOL_MONOMER:
				if degProb[t] < self.monomerVanish:
					lat.removeMolecule(rm)						
			elif (rm.type == MOL_DIMER1 or rm.type == MOL_DIMER2):
				# Death of dimer
				if degProb[t] < self.dimerVanish:
					for atom in rm.atomList:
						if atom.type == ATOM_MONOMER:
							lat.addMolecule(Molecule(MOL_MONOMER, atom.x, atom.y, moleculeTemp1))
					lat.removeMolecule(rm)
					moleculeNum -= 1
				# Degradation of dimer into monomers
				elif degProb[t] > (1-self.dimerBreak):
					for atom in rm.atomList:
						if atom.type != ATOM_SITE:
							lat.addMolecule(Molecule(MOL_MONOMER, atom.x, atom.y, moleculeTemp1))
					lat.removeMolecule(rm)
				else:
					pass
					#for atom in rm.atomList:
					#	# Attach monomer to adsorption site of dimer
					#	if atom.type == ATOM_SITE:
					#		aL1 = lat.getAtomListAt(atom.x, atom.y)
					#		for atom1 in filter(lambda x: x.parent.type == MOL_MONOMER, aL1):
					#			lat.raiseMolecule(rm)
					#			atom.type = ATOM_MONOMER
					#			lat.layMolecule(rm)
					#			lat.removeMolecule(atom1.parent)
					#			break
					#	# Detach monomer from adsorption site of dimer
					#	elif atom.type == ATOM_MONOMER:
					#		if bindProb[t] < min(1,exp(atom.copies*lat.bindingEnergy)):
					#			lat.raiseMolecule(rm)
					#			atom.type = ATOM_SITE
					#			lat.layMolecule(rm)
					#			lat.addMolecule(Molecule(MOL_MONOMER, atom.x, atom.y, moleculeTemp1))
			
			# Add monomers randomly to the system
			if newProb[t] < self.monomerAppear/lat.moleculeNum:
				newX[t] = randint(floor(lat.dimX*0.0), floor(lat.dimX*1.0))
				newY[t] = randint(floor(lat.dimY*0.0), floor(lat.dimY*1.0))
				lat.addMolecule(Molecule(MOL_MONOMER, newX[t], newY[t], moleculeTemp1))
			
			# Update the animation per ## moves
			if (t+1)%(outputPeriod) == 0:
				if display:
					img.set_array(self.colorMap(lat))
					draw()
				if fileFlag:
					file.write('# New Dimer Num Per Interval\n')
					for mt1 in newDimerNum:
						file.write('# ')
						for mt2 in mt1:
							file.write('{} '.format(mt2))
						file.write('\n')
					file.write('# \n')
					newDimerNum = newDimerNum * 0;
					for atomType in lat.atomNumMap:
						for row in atomType:
							for col in row:
								file.write('{} '.format(col))
							file.write('\n')
						file.write('\n')
					file.write('\n')
		if fileFlag:
			file.close()
Exemple #46
0
def make_thick(kf1,kf2,ld,anz=1,verbose=False):
    kf1 = kf1
    kd1 = kf1
    lf1 = 0.4
    ld1 = lf1
    ff1 = kf1*lf1
    fd1 = kd1*ld1

    kf2 = kf2
    kd2 = kf2
    lf2 = lf1
    ld2 = lf2
    ff2 = kf2*lf2
    fd2 = kd2*ld2

    ld = ld

    DL  = D(length=ld,label='L')
    QF1 = QF(k0=kf1,length=0.5*lf1,label='QF1')
    QF2 = QF(k0=kf2,length=0.5*lf2,label='QF2')
    QD1 = QD(k0=kd1,length=0.5*ld1,label='QD1')
    QD2 = QD(k0=kd2,length=0.5*ld2,label='QD2')

    cell = Lattice()
    cell.add_element(QD1)
    cell.add_element(QF1)
    cell.add_element(DL)
    cell.add_element(QD2)
    cell.add_element(QF2)
    cell.add_element(QF2)
    cell.add_element(QD2)
    cell.add_element(DL)
    cell.add_element(QF1)
    cell.add_element(QD1)
    lat = Lattice()
    for i in range(anz):
        lat.concat(cell)
    lat.cell()
    mcell = lat.accel
    betax = lat.betax0
    betay = lat.betay0
    if verbose:
        # {:.3f}
        print('L= {:.3f}'.format(ld),end=' ')
        print('triplet 1: kf= {:.3f}, kd={:.3f}'.format(kf1,kd1),end=' | ')
        print('triplet 2: kf= {:.3f}, kd={:.3f}'.format(kf2,kd2),end=' | ')
        print('betax= {:.3f}, betay= {:.3f}'.format(betax,betay))
    return lat,betax,betay
Exemple #47
0
            file.write(s)
        elif (j+1)%p==0:
            s = '%-5s    %7.5f    %7.5f    %7.5f  %5i\n' % (el_name[j],xyz[j,0],xyz[j,1],xyz[j,2],p)
            file.write(s)
    file.close()

##########################################################################
##########################################################################
if __name__ == "__main__":
    # define cell and hkl:
    #cell = [a,b,c,alpha,beta,gam]
    #hkl = [h,k,l]
    
    cell = [10.223, 5.992, 4.761,90,90,90]
    hkl = [1.,0.,1.]
    lat = Lattice(*cell)
    
    # calculate d spacing in Angstroms
    d_space = lat.d(hkl)

    # calculate vector d in bulk real space basis
    d = lat.dvec(hkl)

    # calculate inplane vectors to choose Va and Vb
    Vs,Vr = surface_vectors(hkl,lat)

    #################
    # choose basis vectors for surface system
    Va = [1.,0.,-1.]
    Vb = [0.,1.,0.]
    Vc = 5*d
Exemple #48
0
                      and filename[-len(output_suffix):] == output_suffix)+1
    except Exception as e:
        counter = 1
    opt.output = os.path.join(output_dir, (output_prefix+'{:05d}'+
                                           output_suffix).format(counter))

fd = open(opt.output, 'w', buffer_size)
fd.write('# N={:d}\n'.format(N))
fd.write('# beta={:f}\n'.format(opt.beta))
# Write RNG seed and commit hash so this run can be repeated after the code has
# changed
fd.write('# seed={:d}\n'.format(seed))
fd.write('# commit='+check_output(['git', 'log', '--pretty=format:%H', '-n',
                                   '1' ])+'\n')

lattice = Lattice(sp.random.random_integers(0, 1, size=(opt.length,
                                                        opt.length)))

print 'Simulating {:d} steps of a {:d}x{:d} lattice at beta={:f}'.format(
    opt.steps, opt.length, opt.length, opt.beta)
print 'Writing run data to ' + opt.output
if opt.movie:
    if opt.movie != True:
        video_filename = opt.movie
    else:
        if opt.output[-4] == '.':
            video_filename = opt.output[:-3] + 'avi'
        else:
            video_filename = opt.output + '.avi'
    from cv import FOURCC
    from cv2 import VideoWriter
    movieWriter = VideoWriter(video_filename, FOURCC('U','2','6','3'),
Exemple #49
0
def main():
    l = Lattice(20,20)
    answer = l.count_lattice_paths()
    sys.stdout.write("%s\n" %answer)
Exemple #50
0
import scipy as sp
from lattice import Lattice
from sys import stdout

length = 512
fps = 20

from cv import FOURCC
from cv2 import VideoWriter
movieWriter = VideoWriter('freeze.avi', FOURCC('U','2','6','3'),
                          fps, (length, length), False)

lattice = Lattice(sp.random.random(size=(length, length)))
samples = fps*60
x = samples/10
for beta in sp.linspace(.01, 10, samples):
    movieWriter.write((128*lattice.state).astype(sp.uint8))
    lattice.step(beta)
    samples -= 1
    if samples % x == 0:
        stdout.write('-')
        stdout.flush()