def test_latticeEntropy_temperature_getEntropy(self): lattice = Lattice(123, 1) lattice2 = Lattice(123, 2) expected = 0.00035104320939824554 result = lattice.lattice_entropy(123) result2 = lattice2.lattice_entropy(123) assert result == expected assert result2 == 2 * expected
def test_latticeFreeEnergy_temperature_getFreeEnergy(self): lattice = Lattice(123, 1) lattice2 = Lattice(123, 2) expected = -0.009809044240247611 result = lattice.lattice_free_energy(123) result2 = lattice2.lattice_free_energy(123) assert result == expected assert result2 == 2 * expected
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()
def main2(output_file_name): lattice = Lattice() a = lattice.add_node('a') b = lattice.add_node('b') c = lattice.add_node('c') d = lattice.add_node('d') e = lattice.add_node('e') f = lattice.add_node('f') g = lattice.add_node('g') lattice.add_edge(a, b) lattice.add_edge(a, c) lattice.add_edge(a, d) lattice.add_edge(b, e) lattice.add_edge(b, f) lattice.add_edge(c, e) lattice.add_edge(c, f) lattice.add_edge(d, e) lattice.add_edge(d, f) lattice.add_edge(e, g) lattice.add_edge(f, g) lattice.supremum = a export_latex(lattice, output_file_name)
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') ]
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
def main_old(): pyramids = get_pyramids() p = np.array(pyramids[0]) lattice = Lattice() a = lattice.add_node(binaryze_as_tuple(p, 0)) b = lattice.add_node(binaryze_as_tuple(p, 1)) c = lattice.add_node(binaryze_as_tuple(p, 2)) d = lattice.add_node(binaryze_as_tuple(p, 3)) e = lattice.add_node(binaryze_as_tuple(p, 4)) f = lattice.add_node(binaryze_as_tuple(p, 5)) g = lattice.add_node(binaryze_as_tuple(p, 6)) lattice.add_edge(a, b) lattice.add_edge(a, c) lattice.add_edge(a, d) lattice.add_edge(b, e) lattice.add_edge(b, f) lattice.add_edge(c, e) lattice.add_edge(c, f) lattice.add_edge(d, e) lattice.add_edge(d, f) lattice.add_edge(e, g) lattice.add_edge(f, g) lattice.supremum = a export_latex_grid(lattice, width_coef=2.5, height_coef=2.5)
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))
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
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
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()
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
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()
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
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 __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 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 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, )
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)
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)
def test_energy_antiferro(): ''' Check the energy of the antiferromagnetic state.''' size = 10 coupling = 1.0 lattice = Lattice(size, size) ham = Hamiltonian(lattice, coupling) afm = tile(eye(2, dtype=bool), (5, 5)) assert ham.energy( afm ) == -2 * coupling * size * size, "Energy of antiferromagnetic state is incorrect."
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()
def makeLattice(self): """Generate and save a lattice for the field by user input and lattice optimization""" from math import floor image = cv2.imread(self.image_path) good_guess = False while not good_guess: fig, ax = plt.subplots(figsize=(24, 12)) ax.set_title( 'Please click 3 points to define an initial guess for lattice. ' + 'If you don\'t know what points to click, please find instructions in the documentation. ' + 'If these instructions do not yet exist, you might have a problem.' ) ax.imshow(image, cmap='gray') plt.get_current_fig_manager().window.showMaximized() print( 'Please input points to define an initial guess for lattice.') points = plt.ginput(3) plt.close() adjust = floor((self.Nb - 1) / 2) offset = np.array(points[0]) vec_a = (np.array(points[1]) - offset) / (self.Na - 1) vec_b = (np.array(points[2]) - offset + vec_a * (adjust - self.Na + 1)) / (self.Nb - 1) self.lattice = Lattice(self.Na, self.Nb, vec_a, vec_b, offset) self.plotLattice() answer = input('Does the lattice look decent? (Y/N) ') if answer == 'y' or answer == 'Y': good_guess = True else: print('Try again.') plt.close() print('Optimizing lattice') self.lattice = self.optimizeLattice(self.lattice) print('Lattice optimized') self.plotLattice() print('Saving new lattice') self.clearBlobsByPoint() pickle.dump(self.lattice, open(self.lattice_path, 'wb'))
def test_generate_simple_exact_cover_solution(self): col_names = ['a', 'b', 'c'] matrix = [['0', '1', '1'], ['1', '0', '0'], ['1', '0', '1'], ['0', '1', '0']] lattice = Lattice(matrix, col_names, delete_zeros=True) solutions = generate_exact_cover_solutions(lattice) solution_rows = [] for s in range(len(solutions)): solution_rows.append([]) for c in solutions[s]: solution_rows[s].append(c.row_num) # Sort the solutions so they appear in an order that is easy to test. for r in solution_rows: r = r.sort() self.assertEqual(2, len(solutions)) self.assertEqual([[1, 2], [3, 4]], solution_rows)
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)
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 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 optimizeLattice(self, lattice): """Optimize the given lattice to fit with the detected blobs""" 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 fixParams(params): """Help function for optimizeLattice Format the parameters given by lattice.getParams to be used by scipy.optimize.minimize """ vax = params[2][0] vay = params[2][1] vbx = params[3][0] vby = params[3][1] ox = params[4][0] oy = params[4][1] return vax, vay, vbx, vby, ox, oy from scipy.optimize import minimize params = np.array(fixParams(lattice.getParams())) res = minimize(getRSS, params, args=(self.Na, self.Nb, self.getBlobsByPoint()), method='Nelder-Mead') vax, vay, vbx, vby, ox, oy = res['x'] lattice = Lattice(self.Na, self.Nb, [vax, vay], [vbx, vby], [ox, oy]) return lattice
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 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