def process_new_rectangle(path, caldata, r): print "New rectangle!" # identify cid cid = None for c in caldata.courses.itervalues(): if c['name'] == r['cname']: cid = c['id'] if cid is None: raise Exception("Unknown course") c = course.Course(cid, r['cname']) # load relevant details file det = load_or_new_details(path, cid) # build element el = element.Element(r['organiser'], r['what'], r['where'], FullPattern(r['when']), False, r['type'], c) # add to groups for term in range(0, 3): e = copy.deepcopy(el) if e.restrictToTerm(term): g = det.getGroup(r['type'], term) g.group.append(e) # save details det_fn = os.path.join(path, "details_%s.json" % cid) j = det.to_json() # outside open to allow exceptions c = open(det_fn, "wb") json.dump(j, c) c.close() return cid
def build_json(self, part,subject,dets): # What groups do we have? ds = details.Details([part,subject],subject,"Various","Various",{"notes": "", "course-description": ""}) # Add elements for (_term,what,who,where,pattern,type) in dets: ds.addRow(element.Element(who,what,where,pattern,True,type,subject)) # Outer wrapper return ds.to_json()
def split_only_by_color(matrix, backgroundColor, transparentColor, numberOfColors): listOfElements = [] isColor = [False for i in range(numberOfColors)] leftUpCornerElementFrame = [] rightDownCornerOfElementFrame = [] width = len(matrix[0]) height = len(matrix) for i in range(numberOfColors): leftUpCornerElementFrame.append((height, width)) rightDownCornerOfElementFrame.append((-1, -1)) for row in range(height): for col in range(width): currentColor = matrix[row][col] isColor[currentColor] = True if row > rightDownCornerOfElementFrame[currentColor][0]: rightDownCornerOfElementFrame[currentColor] = ( row, rightDownCornerOfElementFrame[currentColor][1]) if col > rightDownCornerOfElementFrame[currentColor][1]: rightDownCornerOfElementFrame[currentColor] = ( rightDownCornerOfElementFrame[currentColor][0], col) if row < leftUpCornerElementFrame[currentColor][0]: leftUpCornerElementFrame[currentColor] = ( row, leftUpCornerElementFrame[currentColor][1]) if col < leftUpCornerElementFrame[currentColor][1]: leftUpCornerElementFrame[currentColor] = ( leftUpCornerElementFrame[currentColor][0], col) matrices = [] for i in range(numberOfColors): if isColor[i]: elementFrameWidth = rightDownCornerOfElementFrame[i][1] - \ leftUpCornerElementFrame[i][1] + 1 elementFrameHeight = rightDownCornerOfElementFrame[i][0] - \ leftUpCornerElementFrame[i][0] + 1 matrixForElement = [[ transparentColor for j in range(elementFrameWidth) ] for k in range(elementFrameHeight)] matrices.append(matrixForElement) else: matrices.append([None]) for row in range(height): for col in range(width): currentColor = matrix[row][col] pos = (row - leftUpCornerElementFrame[currentColor][0], col - leftUpCornerElementFrame[currentColor][1]) matrices[currentColor][pos[0]][pos[1]] = currentColor for i in range(numberOfColors): if i != backgroundColor and isColor[i]: listOfElements.append( element.Element(matrices[i], leftUpCornerElementFrame[i], i)) return listOfElements
def importData(dataFile): data = open("data.txt", "r").readlines() elements = [] for el in data: el = el.rstrip().split() x = element.Element(el[0], el[1], int(el[2]), float(el[3]), int(el[4]), int(el[5])) elements.append(x) return elements
def add_element(self, element_type): """Adds an element on the tile (guard or item). Arguments: element_type -- guard or item """ if element_type == "guard": self.element = element.Element(self.pos_x, self.pos_y, element_type) elif element_type == "plastic_tube": self.element = element.Element(self.pos_x, self.pos_y, element_type) elif element_type == "needle": self.element = element.Element(self.pos_x, self.pos_y, element_type) elif element_type == "ether": self.element = element.Element(self.pos_x, self.pos_y, element_type)
def __init__(self, dt, course, type, key, order, merged, rcodehash=None): self.dt = dt self.type = type self._termweeks = [[], [], []] self._course = course self.meta = element.Element(type=type, course=course.cname) self.key = key self._patterns = FullPattern() self.order = order self._merged = merged self.text = None self.saved_dt = None self.rcodehash = rcodehash
def _find_k_neighbors(input, samples, errors, k): result = [] heapq.heapify(result) for i in range(0, len(samples)): current_element = element.Element(_calculate_distance(input, samples[i]) * -1, errors[i][0]) if len(result) < k: result.append(current_element) else: max = heapq.heappop(result) if max < current_element: heapq.heappush(result, current_element) else: heapq.heappush(result, max) return result
def merge(self, mergeState): # Fakes for cid in mergeState.courseIds: print >> sys.stderr, "MISSING %s" % cid ds = details.Details(cid, mergeState.names[cid], "Example organiser", "Example location", { "notes": "", "course-description": "" }) for term in ['Michaelmas', 'Lent', 'Easter']: for type in ['Lecture', 'Practical']: ds.addRow( element.Element( "Example person", mergeState.names[cid], "Example location", FullPattern(term[:2] + ' ' + self.fake_time()), False, type, mergeState.names[cid])) filepaths.saveDetailFile(ds.to_json(), cid)
def input_mesh(mesh_file): with open(mesh_file) as f: lines = f.readlines() nnode,nelem,nmaterial,dof = [int(s) for s in lines[0].split()] irec = 1 nodes = [None] * nnode for inode in range(nnode): items = lines[inode+irec].split() #mesh.in2行以降 id = int(items[0]) xyz = np.array([float(s) for s in items[1:3]]) #node座標list2成分 freedom = np.array([int(s) for s in items[3:]]) nodes[inode] = node.Node(id,xyz,freedom) irec += nnode #irecを1+nnodeで再定義 elements = [None] * nelem for ielem in range(nelem): items = lines[ielem+irec].split() #mesh.in1+nnode行以降 id = int(items[0]) style = items[1] material_id = int(items[2]) inode = np.array([int(s) for s in items[3:]]) elements[ielem] = element.Element(id,style,material_id,inode) irec += nelem materials = [None] * nmaterial for imaterial in range(nmaterial): items = lines[imaterial+irec].split() id = int(items[0]) style = items[1] param = np.array([float(s) for s in items[2:]]) materials[imaterial] = material.Material(id,style,param) return fem.Fem(dof,nodes,elements,materials)
def __getattr__(self, name): # For a strange bugfix !!! if name == '_params': raise AttributeError # Alias if name == 'q': name = 'charge' if name in self._params: return self._params[name] elif self.atype: return getattr(self.atype, name) # Try to get mass from element elif name == 'mass': try: el = element.Element(self.symbol) return el.mass except ValueError: # Invalid symbol raise AttributeError else: raise AttributeError
def from_json(data, order): dt = daytime.DayTimeRange(data['day'], data['starttime'], data['endtime']) c = course.Course(data['cid'], data['cname']) (rcodehash, rid, _) = data['rid'].split(':') merge = rid[0] == 'Y' if 'rid' in data else False # Is this correct? out = Rectangle(dt, c, data['type'], data['code'], order, merge, rcodehash) out._termweeks = data['termweeks'] el = element.Element(what=data['what'], where=data['where'], who=data['organiser'], when=FullPattern(data['when']), type=data['type'], course=data['cname'], merge=merge) out.meta.additional(el) out._patterns = FullPattern(data['when']) # Extract saved daytime out.saved_dt = daytime.DayTimeRange(int(rid[1]), int(rid[2:4]), int(rid[4:6]), int(rid[6:8]), int(rid[8:10])) return out
def everything_as_one_element(matrix, backgroundColor, transparentColor): width = len(matrix[0]) height = len(matrix) leftUpCornerElementFrame = (height, width) rightDownCornerOfElementFrame = (-1, -1) for row in range(height): for col in range(width): if matrix[row][col] != backgroundColor: if row > rightDownCornerOfElementFrame[0]: rightDownCornerOfElementFrame = ( row, rightDownCornerOfElementFrame[1]) if col > rightDownCornerOfElementFrame[1]: rightDownCornerOfElementFrame = ( rightDownCornerOfElementFrame[0], col) if row < leftUpCornerElementFrame[0]: leftUpCornerElementFrame = (row, leftUpCornerElementFrame[1]) if col < leftUpCornerElementFrame[1]: leftUpCornerElementFrame = (leftUpCornerElementFrame[0], col) elementFrameWidth = rightDownCornerOfElementFrame[1] - \ leftUpCornerElementFrame[1] + 1 elementFrameHeight = rightDownCornerOfElementFrame[0] - \ leftUpCornerElementFrame[0] + 1 matrixForElement = [[transparentColor for j in range(elementFrameWidth)] for k in range(elementFrameHeight)] for row in range(height): for col in range(width): if matrix[row][col] != backgroundColor: pos = (row - leftUpCornerElementFrame[0], col - leftUpCornerElementFrame[1]) matrixForElement[pos[0]][pos[1]] = matrix[row][col] el = element.Element(matrixForElement, leftUpCornerElementFrame, None) if el.width == 0: return [] return [el]
def cm(self): '''Get the center of mass of a molecule''' if self._cm is None: x = y = z = 0.0 mass_total = 0.0 for atom in self.atoms: if 'mass' in atom.fields: mass = atom.mass else: # Get the mass from the element if unavailable try: mass = element.Element(atom.symbol).mass except ValueError: mass = 1.0 x += atom.x * mass y += atom.y * mass z += atom.z * mass mass_total += mass x /= mass_total y /= mass_total z /= mass_total self._cm = (x, y, z) return self._cm
# get index of name column name_col_index = np.where(property_names == "Name")[0][0] elements = [] for i in range(len(data)): row = data[i] name = row[name_col_index] properties = {} for j in range(0, len(row)): # skip name if j != name_col_index: properties[property_names[j]] = row[j] elements.append(element.Element(name, properties)) elements.sort() for elem in elements: print(elem) discoverer = input("Enter name of discoverer: ") discovers = [ elem for elem in elements if elem.get_property("Discoverer") == discoverer ] if discovers: print(f"{discoverer} discovered: ") for elem in discovers: print(elem) else:
def update_details(path, cid, rs): logger = logging.getLogger('indium') changed = False for rv in rs: if rv.changedp(): changed = True break if not changed: return logger.info("updating %s" % cid) old_det = load_or_new_details(path, cid) new_det = old_det.new_same_header() # Index values by eid and take copy as orig els = {} orig_els = {} for g in old_det.getGroups(): for e in g.elements: id = e.eid(g.term) els[id] = copy.deepcopy(e) orig_els[id] = e # Change values for rv in rs: # We need the orgi as only changes to rectangles should be propagated to the element to avoid the # risk of reversion if multiple rectangles map to an element and only early rectangles change. orig = orig_els[rv.key] new = els[rv.key] # what, where, who rv.update_to_element(new, orig) # did it move? if rv.saved_dt != rv.dt: # Remove the corresponding old daytimes for all patterns for this rectangle tws = [] wout = FullPattern() for p in new.when.each(): hit = p.removeDayTimeRangeDirect(rv.saved_dt) wout.addOne(p) if hit: # derive term/weeks from deleted patterns tws.append(p) # Add in new daytime newp = patternatom.PatternAtom(False) newp.addDayTimeRangeDirect(rv.dt) for p in tws: newp.addTermWeeksFrom(p) wout.addOne(newp) new.when = wout # Populate based on changed values for (eid, e) in els.iteritems(): new_det.addRow( element.Element(e.who, e.what, e.where, FullPattern(e.when), e.merge, e.type, new_det.name)) if old_det.to_json(True) != new_det.to_json(True): print " saving" det_fn = os.path.join(path, "details_%s.json" % cid) j = new_det.to_json() # outside open to allow exceptions c = open(det_fn, "wb") json.dump(j, c) c.close() return True else: logger.debug(" didn't seem to change") return False
import qt import numpy as np import pulsar import pulse import element import pprint reload(pulse) reload(element) reload(pulsar) test_element = element.Element('a test element', pulsar=qt.pulsar) # we copied the channel definition from out global pulsar # print 'Channel definitions: ' # pprint.pprint(test_element._channels) # print # define some bogus pulses. sin_pulse = pulse.SinePulse(channel='RF', name='A sine pulse on RF') sq_pulse = pulse.SquarePulse(channel='MW_pulsemod', name='A square pulse on MW pmod') special_pulse = pulse.SinePulse(channel='RF', name='special pulse') special_pulse.amplitude = 0.2 special_pulse.length = 2e-6 special_pulse.frequency = 10e6 special_pulse.phase = 0 # create a few of those test_element.add(pulse.cp(sin_pulse, frequency=1e6, amplitude=1, length=1e-6),
#------------------------------------------------------- # define some bogus pulses. # We use an element to configure and store the pulse # For now we have defined some standard pulses but will # increase our library in the future # train = pulse.clock_train(channel='trigger', name='A sine pulse on RF') # sq_pulse = pulse.SquarePulse(channel='MW_pulsemod', # name='A square pulse on MW pmod') trig_pulse = pulse.SquarePulse(channel='trigger', name="trig pulse for FSV") I_pulse = pulse.CosPulse(channel='I_test', name="I pulse on ch1") test_element1 = element.Element('test_AWG_FSV_Sarwan14', pulsar=AWG, ignore_offset_correction=True) # we copied the channel definition from out global pulsar # # create a few of those # test_element1.add(pulse.cp(I_pulse, amplitude=0.4 , length=0.5e-6,frequency = 100e6),start = 0, # name='first pulse') # test_element1.add(pulse.cp(trig_pulse, amplitude=1, length=100e-9), start = 100e-9, # name='second pulse', refpulse='first pulse', refpoint='end') test_element1.add(pulse.cp(trig_pulse, amplitude=1, length=20e-9), start=40e-9, name='first pulse') test_element1.add(pulse.cp(I_pulse,
def add_event(part, when, code, what, who): dt = get_details(part, code) dt.addRow( element.Element(who, what, "See faculty notices", fullpattern.FullPattern(when), True, 'Lecture', mml_subjs[part][code]))
def split(matrix, backgroundColor, transparentColor, spaceConnectionType=4, colorMatters=True): if spaceConnectionType not in [4, 8]: raise ValueError("spaceConnectionType should be 4 or 8") width = len(matrix[0]) height = len(matrix) # isCellAssignedToSomeElement = [[False] * width] * height isCellAssignedToSomeElement = [[False] * width for i in range(height)] stack = [] listOfElements = [] listOfCellsBelongingToElement = [] for i in range(height): for j in range(width): if not isCellAssignedToSomeElement[i][ j] and matrix[i][j] != backgroundColor: # noqa stack.append((i, j)) currentColor = matrix[i][j] rightDownCornerOfElementFrame = (i, j) leftUpCornerElementFrame = (i, j) listOfCellsBelongingToElement.clear() while len(stack) > 0: currentCell = stack.pop() col = currentCell[1] row = currentCell[0] isCellAssignedToSomeElement[row][col] = True listOfCellsBelongingToElement.append(currentCell) if row > rightDownCornerOfElementFrame[0]: rightDownCornerOfElementFrame = ( row, rightDownCornerOfElementFrame[1]) if col > rightDownCornerOfElementFrame[1]: rightDownCornerOfElementFrame = ( rightDownCornerOfElementFrame[0], col) if row < leftUpCornerElementFrame[0]: leftUpCornerElementFrame = ( row, leftUpCornerElementFrame[1]) if col < leftUpCornerElementFrame[1]: leftUpCornerElementFrame = ( leftUpCornerElementFrame[0], col) if colorMatters: check_neighbours_color_matters( matrix, isCellAssignedToSomeElement, stack, currentColor, row, col, height, width, spaceConnectionType) else: check_neighbours_color_not_matters( matrix, isCellAssignedToSomeElement, stack, backgroundColor, row, col, height, width, spaceConnectionType) elementFrameWidth = rightDownCornerOfElementFrame[1] - \ leftUpCornerElementFrame[1] + 1 elementFrameHeight = rightDownCornerOfElementFrame[0] - \ leftUpCornerElementFrame[0] + 1 elementMatrix = [[transparentColor] * elementFrameWidth for k in range(elementFrameHeight)] for cell in listOfCellsBelongingToElement: pos = (cell[0] - leftUpCornerElementFrame[0], cell[1] - leftUpCornerElementFrame[1]) elementMatrix[pos[0]][pos[1]] = matrix[cell[0]][cell[1]] if colorMatters: colorOfElement = currentColor else: colorOfElement = None listOfElements.append( element.Element(elementMatrix, leftUpCornerElementFrame, colorOfElement)) return listOfElements
# Wolfgang Pfaff <*****@*****.**> import qt import numpy as np import pulsar import pulse import element import pprint reload(pulse) reload(element) reload(pulsar) test_element = element.Element( # Implementation of a sequence element. 'a test element', # Basic idea: add different pulses, and compose the actual numeric pulsar=qt.pulsar) # arrays that form the amplitudes for the hardware (typically an AWG). # we copied the channel definition from out global pulsar print 'Channel definitions: ' pprint.pprint(test_element._channels) print # Define some bogus pulses. sin_pulse = pulse.SinePulse( channel='RF', name='A sine pulse on RF')
# Authors: # Bas Hensen <*****@*****.**> # Gijs de Lange - TNW <*****@*****.**> # Wolfgang Pfaff <*****@*****.**> import numpy as np import pulse import pulselib import element import view reload(pulse) reload(element) reload(view) reload(pulselib) e = element.Element('sequence_element', clock=1e9, min_samples=0) e.define_channel('EOM_Matisse') e.define_channel('EOM_AOM_Matisse') opt_pulse = pulselib.short_EOMAOMPulse('Eom Aom Pulse', eom_channel='EOM_Matisse', aom_channel='EOM_AOM_Matisse') e.add(opt_pulse) e.print_overview() print e.next_pulse_time('EOM_Matisse'), e.next_pulse_time('EOM_AOM_Matisse') view.show_element(e)
def main(): #CSV file import csv_import.csv_toVar( '9_Buckling_Dokumentation.csv', variablesArray ) # it takes the csv file and import its into an array as ints e0 = element.Element(0, prop, nodes, elements) # Test funcionts.fivePrec(e0.kElementMartix) # Test e0.printEr() # Test #Printing of the input elementsContainer = [] # contains all the ellement element.elementsMaker( variablesArray, elementsContainer) # makes the elements from the data's funcionts.printHelper("nodes", nodes) funcionts.printHelper("elements", elements) funcionts.printHelper("len(elements)", len(elements)) funcionts.printHelper("CondU", condU) funcionts.printHelper("len(nodes)", len(nodes)) #Elements fig = plt.figure() ax = fig.add_subplot(111) elmo = int((len(elements))) for i in range(elmo): el1 = int(elements[i][1]) el2 = int(elements[i][2]) x_values = [float(nodes[el1][1]), float(nodes[el2][1])] y_values = [float(nodes[el1][2]), float(nodes[el2][2])] ax.plot(x_values, y_values, '-k') #Constraints in x,y,r direction for x in range(len(nodes)): if int(condU[x][2]) == 1 and int(condU[x][3]) != 1 and int( condU[x][4]) != 1: ax.plot(float(nodes[x][1]), float(nodes[x][2]), 'sg') if int(condU[x][2]) != 1 and int( condU[x][3]) == 1 and int(condU[x][4]) != 1: ax.plot(float(nodes[x][1]), float(nodes[x][2]), 'pc') if int(condU[x][2]) == 1 and int( condU[x][3]) == 1 and int(condU[x][4]) != 1: ax.plot(float(nodes[x][1]), float(nodes[x][2]), 'Pm') if int(condU[x][2]) == 1 and int(condU[x][3]) == 1 and int( condU[x][4]) == 1: ax.plot(float(nodes[x][1]), float(nodes[x][2]), '*y') if int(condU[x][2]) != 1 and int(condU[x][3]) != 1 and int( condU[x][4]) != 1: ax.plot(float(nodes[x][1]), float(nodes[x][2]), 'ok') #Forces in "x" direction for j in range(len(condF)): if int(condF[j][2]) < 0: x_values = [ int(nodes[int(condF[j][1])][1]), int(nodes[int(condF[j][1])][1]) - 10 ] #+int(condF[j][2])] y_values = [ int(nodes[int(condF[j][1])][2]), int(nodes[int(condF[j][1])][2]) ] ax.plot(x_values, y_values, 'm<-') if int(condF[j][2]) > 0: x_values = [ int(nodes[int(condF[j][1])][1]), int(nodes[int(condF[j][1])][1]) + 10 ] #+int(condF[j][2])] y_values = [ int(nodes[int(condF[j][1])][2]), int(nodes[int(condF[j][1])][2]) ] ax.plot(x_values, y_values, 'm>-') #Forces in "y" direction for j in range(len(condF)): if int(condF[j][3]) < 0: x_values = [ int(nodes[int(condF[j][1])][1]), int(nodes[int(condF[j][1])][1]) ] y_values = [ int(nodes[int(condF[j][1])][2]), int(nodes[int(condF[j][1])][2]) - 10 ] #+int(condF[j][3])] ax.plot(x_values, y_values, 'mv-') if int(condF[j][3]) > 0: x_values = [ int(nodes[int(condF[j][1])][1]), int(nodes[int(condF[j][1])][1]) ] y_values = [ int(nodes[int(condF[j][1])][2]), int(nodes[int(condF[j][1])][2]) + 10 ] #+int(condF[j][3])] ax.plot(x_values, y_values, 'm^-') #Creation of the "K"-Matrix mxSize = len( variablesArray[1] ) * 3 #TODO implement as DOF # It gives the size of the K matrix globalKMx = np.zeros((mxSize, mxSize)) # makes a nxn zero matrix funcionts.printHelper("global K Matrix", globalKMx) # Test k_matrix.globalKMxMaker( globalKMx, elementsContainer) # it makes the global K matrix form the elements funcionts.fivePrec( globalKMx) # it makes the valus display for the 5th value funcionts.printHelper("global K Matrix", globalKMx) # Test # "K"-Matrix reduction globalRedKMx = np.copy(globalKMx) # makes a copy of the global K Matrix funcionts.printHelper("global K Red Matrix", globalRedKMx) # test # gr = np.delete(globalRedKMx,[0,1],0)#<-- array, what i, row/coloum ## Test # gr2 = np.delete(gr,[0,1],1) #<-- array, what i, row/coloum ## Test globalRedKMx = k_matrix.globalRedKMxMaker( globalRedKMx, variablesArray[3] ) # makes the reducted K matrix from the global and the Initial U cond funcionts.printHelper( "globalRedKMx", globalRedKMx, ) # Test fMx = f_matrix.initFToArrayMaker( mxSize, variablesArray[4]) # makes a nx1 matrix/vector from the array F funcionts.printHelper("F matrix", fMx) # Test fMxRed = f_matrix.fTofRed(variablesArray[3], fMx) # Test funcionts.printHelper( "F Red matrix", fMxRed) #TODO # NYOMaték #Test funcionts.printHelper("F Red matrix", fMxRed) # Test funcionts.printHelper("K Red Matrix", globalRedKMx) # Test # Matrix Inversion try1 = np.linalg.inv(globalRedKMx) # Inverz funcionts.fivePrec(try1) # it makes the valus display for the 5th value #try2 = np.multiply(fMxRed,try1) # try mult #try3 = try1*fMxRed # try multi #try4 = np.matmul(try1,fMxRed) # try multi try5 = try1 @ fMxRed # try multi funcionts.printHelper("try1", try1) # Test funcionts.printHelper("try5", try5) # Displacement Selection nArray = [] for init in condU: if int(init[2]) == 1: nArray.append(int(init[1]) * 3) if int(init[3]) == 1: nArray.append(int(init[1]) * 3 + 1) if int(init[4]) == 1: nArray.append(int(init[1]) * 3 + 2) funcionts.printHelper("nArray", nArray) funcionts.printHelper("len(nodes)", len(nodes)) FullMatrix = [] kszam = (int(len(nodes))) * 3 for z in range(kszam): FullMatrix.append(z) funcionts.printHelper("kszam", kszam) funcionts.printHelper("FullMatrix", FullMatrix) MatDiff = (list( list(set(FullMatrix) - set(nArray)) + list(set(nArray) - set(FullMatrix)))) funcionts.printHelper("MatDiff", MatDiff) ZeroMatrix = [] zszam = (int(len(nodes))) * 3 for z in range(zszam): ZeroMatrix.append(0) for l in range(len(MatDiff)): ZeroMatrix[MatDiff[l]] = try5[l][0] funcionts.printHelper("ZeroMatrix", ZeroMatrix) MovementMatrix = np.array(ZeroMatrix) HP = MovementMatrix.reshape(int(len(nodes)), 3) funcionts.printHelper("HP", HP) NodesMod = np.array(nodes) funcionts.printHelper("NodesMod", NodesMod) A = np.delete(NodesMod, 0, axis=1) B = np.delete(HP, 2, axis=1) funcionts.printHelper("A", A) funcionts.printHelper("B", B) funcionts.printHelper("100B", 10000 * B) C = A.astype(float) LMatrix = np.add(B, C) FixMatrix = np.add(float(prop[0][7]) * B, C) funcionts.printHelper("LMatrix", LMatrix) funcionts.printHelper("FixMatrix", FixMatrix) #Buckling #Original element length L0Array = [] for i in range(elmo): el1 = int(elements[i][1]) el2 = int(elements[i][2]) x_values0 = (float(A[el1][0]) - float(A[el2][0])) * (float(A[el1][0]) - float(A[el2][0])) y_values0 = (float(A[el1][1]) - float(A[el2][1])) * (float(A[el1][1]) - float(A[el2][1])) L0 = math.sqrt(x_values0 + y_values0) L0Array.append(L0) funcionts.printHelper("L0Array", L0Array) #Deformed element length LAArray = [] for i in range(elmo): el1 = int(elements[i][1]) el2 = int(elements[i][2]) x_valuesA = (float(LMatrix[el1][0]) - float(LMatrix[el2][0])) * ( float(LMatrix[el1][0]) - float(LMatrix[el2][0])) y_valuesA = (float(LMatrix[el1][1]) - float(LMatrix[el2][1])) * ( float(LMatrix[el1][1]) - float(LMatrix[el2][1])) LA = math.sqrt(x_valuesA + y_valuesA) LAArray.append(LA) funcionts.printHelper("LAArray", LAArray) # Beam slenderness ElmProp = (float(prop[0][4]) / float(prop[0][5])) * float(prop[0][8]) Lambda = np.multiply(LAArray, math.sqrt(ElmProp)) funcionts.printHelper("Lambda", Lambda) # Axial Stress in the Beam Sigma = [] Hu = int((len(LAArray))) for i in range(Hu): Eps = (LAArray[i] - L0Array[i]) / L0Array[i] Sig = float(prop[0][2]) * Eps Sigma.append(Sig) funcionts.printHelper("prop[0][2]", prop[0][2]) funcionts.printHelper("Eps", Eps) # Buckling case decision LambdaG = float(prop[0][10]) LambdaF = float(prop[0][9]) SigmaK = [] for i in range(len(LAArray)): if Lambda[i] > LambdaG: SigmaK.append( (math.pi * math.pi * float(prop[0][2]) * float(prop[0][5])) / (LAArray[i] * float(prop[0][4]))) if Lambda[i] < LambdaF: SigmaK.append(0) if Lambda[i] < LambdaG and Lambda[i] > LambdaF: SigmaK.append( (float(prop[0][11]) - float(prop[0][12]) * Lambda[i] + float(prop[0][13]) * Lambda[i] * Lambda[i]) * 10**6) funcionts.printHelper("Sigma", Sigma) funcionts.printHelper("SigmaK", SigmaK) # Buckling stress comparison Buckling = [] for i in range(len(SigmaK)): if Sigma[i] < 0: if SigmaK[i] / 5 < abs(Sigma[i]): Buckling.append(0) else: Buckling.append(1) else: Buckling.append(1) #StressRatio.append(SigmaK[i]/Sigma[i]) funcionts.printHelper("Buckling", Buckling) # Result Visualization # Elements elma = int((len(elements))) for i in range(elma): el11 = int(elements[i][1]) el22 = int(elements[i][2]) x_values2 = [float(FixMatrix[el11][0]), float(FixMatrix[el22][0])] y_values2 = [float(FixMatrix[el11][1]), float(FixMatrix[el22][1])] ax.plot(x_values2, y_values2, 'b') # Buckling for i in range(elma): if Buckling[i] == 0: el11 = int(elements[i][1]) el22 = int(elements[i][2]) x_values2 = [float(FixMatrix[el11][0]), float(FixMatrix[el22][0])] y_values2 = [float(FixMatrix[el11][1]), float(FixMatrix[el22][1])] ax.plot(x_values2, y_values2, 'g') # Beam stress above limit for i in range(elma): if float(prop[0][6]) < abs(Sigma[i]) * 5: el11 = int(elements[i][1]) el22 = int(elements[i][2]) x_values2 = [float(FixMatrix[el11][0]), float(FixMatrix[el22][0])] y_values2 = [float(FixMatrix[el11][1]), float(FixMatrix[el22][1])] ax.plot(x_values2, y_values2, 'r') funcionts.printHelper("x_values2", x_values2) funcionts.printHelper("y_values2", y_values2) bl1 = mlines.Line2D([], [], color='black', marker='o', markersize=10, label='Original structure') bl2 = mlines.Line2D([], [], color='blue', marker='o', markersize=10, label='Deformed structure') bl3 = mlines.Line2D([], [], color='green', marker='s', markersize=10, label='x-direction blocked') bl4 = mlines.Line2D([], [], color='cyan', marker='p', markersize=10, label='y-direction blocked') bl5 = mlines.Line2D([], [], color='magenta', marker='P', markersize=10, label='x and y direction blocked') bl6 = mlines.Line2D([], [], color='yellow', marker='*', markersize=10, label='Movement blocked') bl7 = mlines.Line2D([], [], color='red', marker='^', markersize=10, label='Force') plt.legend(handles=[bl1, bl2, bl3, bl4, bl5, bl6, bl7]) funcionts.printHelper("try5", try5) plt.axis('equal') plt.show()
# global variables import element import variable # define global variables elem = element.Element() util = variable.UtilVar() flow = variable.FlowVar() prob = variable.ProbVar() stat = variable.StatVar()
phases = np.linspace(0, 360, 37) for i, phase in enumerate(phases): devAWG.init_dir() seq = sequence.Sequence('phase_%d' % phase) phases = np.linspace(0, 360, 37) print(phases) elements = [] elem = element.Element('phase_%d' % phase, pulsar=AWG) #, ignore_offset_correction=True) # create a few of those elem.add(pulse.cp(sq_pulse, amplitude=1., length=0.5e-6), start=0.2e-6, name='first pulse', refpoint='start') elem.add(pulse.cp(SSB_pulse, mod_frequency=-50e6, amplitude=0.5, length=20.0e-6, phase=phase), start=5.0e-6, name='second pulse', refpulse='first pulse',
def setup_AWG_pulsed_spec_sequence(sequence_name='Cool_Sequence', measurement_trigger_delay=2e-6, SSB_modulation_frequency=-50e6, measurement_pulse_length=10e-6, cooling_pulse_length=200e-6, cooling_measurement_delay=5e-6, buffer_pulse_length=2.e-6, readout_trigger_length=1.0e-6, measurement_pulse_amp=0.5, doplot=True, devAWG=Tektronix_AWG520(name='AWG'), us_clock=True, trigger_first=False): ''' makes the AWG single element sequences for the cooling experiment. It contains a cooling pulse, a readout trigger and a readout pulse. readout trigger is the fixpoint, as it defines the timing we see on the signal analyzer. readout pulse is defined with the IQ modulation of a vector source. Cooling pulse is a marker to a microwave switch. There is some funky stuff happening if there is no buffers around the sequence, therefore we have buffer pulses at the beginning and end such that the channels are zero there! ''' if us_clock is True: measurement_trigger_delay = measurement_trigger_delay * 1e-3 SSB_modulation_frequency = SSB_modulation_frequency * 1e-3 measurement_pulse_length = measurement_pulse_length * 1e-3 cooling_measurement_delay = cooling_measurement_delay * 1e-3 cooling_pulse_length = cooling_pulse_length * 1e-3 buffer_pulse_length = buffer_pulse_length * 1e-3 readout_trigger_length = 1 * readout_trigger_length * 1e-3 if trigger_first is True: left_reference_pulse_name = 'readout trigger' else: left_reference_pulse_name = 'pulsed spec' AWG = AWG_station.AWG_Station() AWG.AWG = devAWG clock = devAWG.get_clock() devAWG.set_run_mode('ENH') devAWG.set_refclock_ext() AWG.define_channels(id='ch1', name='RF1', type='analog', high=0.541, low=-0.541, offset=0., delay=0, active=True) AWG.define_channels(id='ch2', name='RF2', type='analog', high=0.541, low=-0.541, offset=0., delay=0, active=True) AWG.define_channels(id='ch2_marker1', name='MW_pulsemod', type='marker', high=1.0, low=0, offset=0., delay=0, active=True) AWG.define_channels(id='ch1_marker1', name='readout_trigger', type='marker', high=1, low=0, offset=0., delay=0, active=True) sin_pulse = pulse.CosPulse(channel='RF1', name='A sine pulse on RF') sin_pulse_2 = pulse.CosPulse(channel='RF2', name='A sine pulse on RF') SSB_pulse = pulse.MW_IQmod_pulse(I_channel='RF1', Q_channel='RF2', name='SSB pulse') pulsed_spec_pulse = pulse.SquarePulse(channel='MW_pulsemod', name='A square pulse on MW pmod') readout_trigger_pulse = pulse.SquarePulse(channel='readout_trigger', name='A square pulse on MW pmod') readout_trigger_pulse = pulse.SquarePulse(channel='readout_trigger', name='A square pulse on MW pmod') sq_pulse_ch1 = pulse.SquarePulse(channel='RF1', name='A square pulse on MW pmod') sq_pulse_ch2 = pulse.SquarePulse(channel='RF2', name='A square pulse on MW pmod') test_element1 = element.Element( (sequence_name + '_element1'), pulsar=AWG) #, ignore_offset_correction=True) test_element2 = element.Element( (sequence_name + '_element2'), pulsar=AWG) #, ignore_offset_correction=True) test_element1.add(pulse.cp(readout_trigger_pulse, amplitude=1., length=readout_trigger_length), start=0.1e-6, name='readout trigger', refpoint='start') test_element1.add(pulse.cp(SSB_pulse, mod_frequency=SSB_modulation_frequency, amplitude=measurement_pulse_amp, length=measurement_pulse_length), start=measurement_trigger_delay, name='readout pulse', refpulse='readout trigger', refpoint='start') test_element1.add(pulse.cp(pulsed_spec_pulse, amplitude=1., length=cooling_pulse_length), start=-1 * cooling_measurement_delay - cooling_pulse_length, name='pulsed spec', refpulse='readout pulse', refpoint='start') test_element1.add(pulse.cp(readout_trigger_pulse, amplitude=0., length=buffer_pulse_length), start=-1 * buffer_pulse_length, name='buffer left', refpulse=left_reference_pulse_name, refpoint='start') test_element1.add(pulse.cp(readout_trigger_pulse, amplitude=0., length=buffer_pulse_length), start=0, name='buffer right', refpulse='readout pulse', refpoint='end') test_element2.add(pulse.cp(readout_trigger_pulse, amplitude=1., length=readout_trigger_length), start=0.1e-6, name='readout trigger', refpoint='start') test_element2.add(pulse.cp(SSB_pulse, mod_frequency=SSB_modulation_frequency, amplitude=measurement_pulse_amp, length=measurement_pulse_length), start=measurement_trigger_delay, name='readout pulse', refpulse='readout trigger', refpoint='start') test_element2.add(pulse.cp(pulsed_spec_pulse, amplitude=1., length=cooling_pulse_length), start=-1 * cooling_measurement_delay - cooling_pulse_length, name='pulsed spec', refpulse='readout pulse', refpoint='start') test_element2.add(pulse.cp(readout_trigger_pulse, amplitude=0., length=buffer_pulse_length), start=-1 * buffer_pulse_length, name='buffer left', refpulse=left_reference_pulse_name, refpoint='start') test_element2.add(pulse.cp(readout_trigger_pulse, amplitude=0., length=buffer_pulse_length), start=0, name='buffer right', refpulse='readout pulse', refpoint='end') #print('Channel definitions: ') #test_element1.print_overview() # test_element2.print_overview() # -------------------------continue------------------------------- # ------------------------------------------------------- # viewing of the sequence for second check of timing etc if doplot is True: viewer.show_element_stlab(test_element1, delay=False, channels='all', ax=None) viewer.show_element_stlab(test_element2, delay=False, channels='all', ax=None) # -------------------------------------------------------- devAWG.init_dir() devAWG.clear_waveforms() seq = sequence.Sequence(sequence_name) seq.append(name='first_element', wfname=(sequence_name + '_element1'), trigger_wait=True, goto_target='second element') seq.append(name='second_element', wfname=(sequence_name + '_element2'), trigger_wait=True, goto_target='first_element') AWG.program_awg(seq, test_element1, test_element2, verbose=True) #, test_element2)
def init(parent): return element.Element(parent)
# For now we have defined some standard pulses but will # increase our library in the future sin_pulse = pulse.CosPulse(channel='RF1', name='A sine pulse on RF') sin_pulse_2 = pulse.CosPulse(channel='RF2', name='A sine pulse on RF') qubit_spec_SSB_pulse = pulse.MW_IQmod_pulse(I_channel='RF1', Q_channel='RF2', name='SSB pulse') readout_switch_marker = pulse.SquarePulse(channel='MW_pulsemod', name='A square pulse on MW pmod') ATS_trigger_pulse = pulse.SquarePulse(channel='readout_trigger', name='A square pulse on MW pmod') test_element1 = element.Element((sequence_name + '_element1'), pulsar=AWG) #, ignore_offset_correction=True) test_element2 = element.Element((sequence_name + '_element2'), pulsar=AWG) #, ignore_offset_correction=True) test_element1.add(pulse.cp(ATS_trigger_pulse, amplitude=1., length=readout_trigger_length), start=0.1e-6, name='readout trigger', refpoint='start') test_element1.add(pulse.cp(readout_switch_marker, amplitude=1., length=measurement_pulse_length), start=measurement_trigger_delay, name='readout switch marker',
class explorer0Env(gym.Env): game_map = np.array([ [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1], [0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1], [0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1], [0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1], [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1], [1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1], [0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1], [0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1], [0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1], [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1], [1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1] ]) # posición aleatoria válida del explorador explorer = element.Element(np.random.randint(0, 19), np.random.randint(0, 19)) while game_map[explorer.initial_x][explorer.initial_y] == 0: explorer = element.Element(np.random.randint(0, 19), np.random.randint(0, 19)) map_exit = element.Element(19, 19) def __init__(self): self.action_space = 4 self.observation_space = len(self.game_map) def step(self, action): """ ejecuta la acción escogida reward retorna 1 si ha llegado al final, o -1 si aún no ha llegado al final """ #print("explorer position = " + str(self.explorer.get_position())) #print("value at coordinates = " + str(self.game_map[self.explorer.x, self.explorer.y])) if action == 0: if self.explorer.x - 1 >= 0 and self.game_map[self.explorer.x - 1, self.explorer.y] > 0: self.explorer.move(-1, 0) else: pass elif action == 1: if self.explorer.y + 1 < len(self.game_map[0]): if self.game_map[self.explorer.x, self.explorer.y + 1] > 0: self.explorer.move(0, 1) else: pass elif action == 2: if self.explorer.x + 1 < len(self.game_map): if self.game_map[self.explorer.x + 1, self.explorer.y] > 0: self.explorer.move(1, 0) else: pass elif action == 3: if self.explorer.y - 1 >= 0 and self.game_map[self.explorer.x, self.explorer.y - 1] > 0: self.explorer.move(0, -1) else: pass # la observación del entorno es la distancia entre el explorador y la salida, (x, y) ob = self.get_observation(self.map_exit) # la recompensa es 1 si ha llegado a la salida, -1 si no es así reward = self.get_reward() return reward, ob # reset coloca al explorador en una nueva posición inicial def reset(self): self.explorer.set_position(np.random.randint(0, 19), np.random.randint(0, 19)) while self.game_map[self.explorer.initial_x][self.explorer.y] == 0: self.explorer.set_position(np.random.randint(0, 19), np.random.randint(0, 19)) return self.get_observation(self.map_exit) # TODO: inicializar map_image en constructor para no realizar este proceso cada render? def render(self, mode='human', close=False): map_image = np.zeros((self.observation_space, self.observation_space, 3), dtype=np.uint8) #sera tamaño line_index = 0 for line in self.game_map: for pixel in range(len(line)): if self.game_map[line_index][pixel] == 1: map_image[line_index][pixel] = 250, 250, 250 line_index += 1 map_image[self.explorer.x][self.explorer.y] = 255, 100, 100 map_image[self.map_exit.x][self.map_exit.y] = 0, 0, 255 img = Image.fromarray(map_image, "RGB") img = img.resize((400, 400), resample=Image.NEAREST) cv2.imshow("", np.array(img)) cv2.waitKey(20) def get_reward(self): if self.explorer.x == self.map_exit.x and self.explorer.y == self.map_exit.y: return 1 else: return -1 def get_observation(self, other): return self.explorer.distance(other)
def testProperties(self): el = element.Element(element.Gadget.class_type, key='value') self.assertEquals('value', el.key)
# # at insertion time. # # a difference with Lucio's sequencer: the reference time is evaluated # # at insertion time, i.e. manipulation of pulses inside the element # # (they are deep copies) can break the reference relation! # e.add(pulse.cp(p1, amplitude=1, length=10e-8), name='reference') # e.add(pulse.cp(p1, amplitude=0.5, length=10e-9), start=10e-9, # refpulse='reference', refpoint='end') # e.add(pulse.cp(p2, 1e7, 1, 1e-7), start=10e-9) # e.print_overview() # view.show_element(e, delay=True) # if delay is false, the channel delay shift # # is omitted in the plots (channels are offset then) e2 = element.Element('sequence_element', clock=1e9, min_samples=0, global_time=True, time_offset=1.236e-6) e2.define_channel('ch1', delay=110e-9) e2.define_channel('ch2', delay=100e-9) e2.define_channel('ch3', delay=120e-9) e2.append(pulse.cp(p1, amplitude=1, length=100e-9), pulse.cp(p1, amplitude=0.5, length=10e-9), pulse.cp(p2, 1e7, 1, 1e-7)) e2.print_overview() print e2.next_pulse_time('ch1'), e2.next_pulse_time('ch2'), \ e2.next_pulse_time('ch3')