def _rings_to_multi_polygon(self, rings, is_ccw): exterior_rings = [] interior_rings = [] for ring in rings: if ring.is_ccw != is_ccw: interior_rings.append(ring) else: exterior_rings.append(ring) polygon_bits = [] # Turn all the exterior rings into polygon definitions, # "slurping up" any interior rings they contain. for exterior_ring in exterior_rings: polygon = sgeom.Polygon(exterior_ring) prep_polygon = prep(polygon) holes = [] for interior_ring in interior_rings[:]: if prep_polygon.contains(interior_ring): holes.append(interior_ring) interior_rings.remove(interior_ring) polygon_bits.append((exterior_ring.coords, [ring.coords for ring in holes])) # Any left over "interior" rings need "inverting" with respect # to the boundary. if interior_rings: boundary_poly = self.domain x3, y3, x4, y4 = boundary_poly.bounds bx = (x4 - x3) * 0.1 by = (y4 - y3) * 0.1 x3 -= bx y3 -= by x4 += bx y4 += by for ring in interior_rings: polygon = sgeom.Polygon(ring) if polygon.is_valid: x1, y1, x2, y2 = polygon.bounds bx = (x2 - x1) * 0.1 by = (y2 - y1) * 0.1 x1 -= bx y1 -= by x2 += bx y2 += by box = sgeom.box(min(x1, x3), min(y1, y3), max(x2, x4), max(y2, y4)) # Invert the polygon polygon = box.difference(polygon) # Intersect the inverted polygon with the boundary polygon = boundary_poly.intersection(polygon) if not polygon.is_empty: polygon_bits.append(polygon) if polygon_bits: multi_poly = sgeom.MultiPolygon(polygon_bits) else: multi_poly = sgeom.MultiPolygon() return multi_poly

def perform_scaling(data, electrode_indices): """This function, suprisingly, performs scaling on a given set of data. The data is returned as a dictionary of 8 differently scaled data sets. The 8 data sets represents all combinations of the following scaling methodologies: 'Vector' of 'MinMax' scaling 'Within'- or 'Across'-subject scaling 'All' or 'Few' electrodes included in scaling The data can be accessed in the following way: data_scaled = perform_scaling(data, electrode_indices) print(data_scaled['Vector']['Across']['All'] """ # TODO: Should the scaled for selected electrodes data retain all the # unscaled values? I.e. for compatibility with other scripts - i.e. the # electrode numbers will be all screwed up... data_scaled = { "Vector": {"Across": {"All": None, "Few": None}, "Within": {"All": None, "Few": None}}, "MaxMin": {"Across": {"All": None, "Few": None}, "Within": {"All": None, "Few": None}}, } mean_all = mean(data, 0) mean_few = mean(data[:, electrode_indices], 0) data_scaled["Vector"]["Across"]["All"] = copy(data) / sqrt(vdot(mean_all, mean_all)) data_scaled["Vector"]["Across"]["Few"] = copy(data) / sqrt(vdot(mean_few, mean_few)) min_point = min(mean_all) max_point = max(mean_all) diff = max_point - min_point data_scaled["MaxMin"]["Across"]["All"] = (copy(data) - min_point) / diff min_point = min(mean_few) max_point = max(mean_few) diff = max_point - min_point data_scaled["MaxMin"]["Across"]["Few"] = (copy(data) - min_point) / diff data_scaled["Vector"]["Within"]["All"] = zeros(data.shape) data_scaled["Vector"]["Within"]["Few"] = zeros(data.shape) data_scaled["MaxMin"]["Within"]["All"] = zeros(data.shape) data_scaled["MaxMin"]["Within"]["Few"] = zeros(data.shape) for i in range(data.shape[0]): data_scaled["Vector"]["Within"]["All"][i, :] = copy(data[i, :]) / sqrt(vdot(data[i, :], data[i, :])) data_scaled["Vector"]["Within"]["Few"][i, :] = copy(data[i, :]) / sqrt( vdot(data[i, electrode_indices], data[i, electrode_indices]) ) min_point = min(data[i, :]) max_point = max(data[i, :]) diff = max_point - min_point data_scaled["MaxMin"]["Within"]["All"][i, :] = (copy(data[i, :]) - min_point) / diff min_point = min(data[i, electrode_indices]) max_point = max(data[i, electrode_indices]) diff = max_point - min_point data_scaled["MaxMin"]["Within"]["Few"][i, :] = (copy(data[i, :]) - min_point) / diff return data_scaled

def maxsr_distance_between_codingblocks(self, other, organism=None): """ Distance in AA between two CodingBlockGraphs measured on their maxsr @type organism: * @param organism: Organism identifier (or None) @rtype: dictionary (or integer if organism or node is specified) @return: dictionary with organisms (keys) and AA-distance between CBGs (values), or only a distance if an Organism identifier was specified @attention: other (CBG) is supposed to be 3p/rigth of 'self' (current CBG) """ # get maximal spanning ranges maxsrSelf = self.maximal_spanning_range() maxsrOther = other.maximal_spanning_range() distances = {} for org in self.organism_set().intersection(other.organism_set()): if organism and org != organism: continue nodeA = self.node_by_organism(org) nodeB = other.node_by_organism(org) # although other is supposed to be 3p of self, take both # orientations into account. distA = min(maxsrSelf[nodeA]) - max(maxsrOther[nodeB]) - 1 distB = min(maxsrOther[nodeB]) - max(maxsrSelf[nodeA]) - 1 distances[org] = max([0, distA, distB]) # return distance only of a specific organism is requested for if organism: return distances[organism] else: return distances

def computeArea(self, A, B, C, D, E, F, G, H): result = (C - A) * (D - B) + (G - E) * (H - F) if C < E or D < F or A > G or B > H: return result top, bottom, left, right = min(D, H), max(B, F), max(A, E), min(C, G) return result - (right - left) * (top - bottom)

def set_cursor(self, param): x, sep, y = param.partition(";") x = to_int(x, 1) - 1 y = to_int(y, 1) - 1 sbinfo = self.screen_buffer_info() new_pos = COORD(min(max(0, x), sbinfo.Size.X), min(max(0, y), sbinfo.Size.Y)) windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos)

def buildCache(self): """ merges corpora and computes probabilities """ self.cache = {} for pname, pool in self.pools.items(): # skip our special pool if pname == "__Corpus__": continue poolCount = pool.tokenCount themCount = max(self.corpus.tokenCount - poolCount, 1) cacheDict = self.cache.setdefault(pname, self.dataClass(pname)) for word, totCount in self.corpus.items(): # for every word in the copus # check to see if this pool contains this word thisCount = float(pool.get(word, 0.0)) if thisCount == 0.0: continue otherCount = float(totCount) - thisCount if not poolCount: goodMetric = 1.0 else: goodMetric = min(1.0, otherCount / poolCount) badMetric = min(1.0, thisCount / themCount) f = badMetric / (goodMetric + badMetric) # PROBABILITY_THRESHOLD if abs(f - 0.5) >= 0.1: # GOOD_PROB, BAD_PROB cacheDict[word] = max(0.0001, min(0.9999, f))

def panimage(ima, columns=5): "panimage(ima) - display ima in a scrolled window" top = Tkinter.Toplevel() top.title("panimage ") Pmw.initialise() sf = Pmw.ScrolledFrame(top, labelpos=N, label_text="Image Array", usehullsize=1, hull_width=700, hull_height=420) sf.pack(fill="both", expand=1) frame = [] image = [] numb = [] vminl = [] vmaxl = [] nd = len(ima) h = len(ima[0]) w = len(ima[0][0]) pal = readPalette() for i in range(nd): im = array(ima[i]) vmin, vmax = max(max(im)), min(min(im)) da = preprocess(im) frame.append(Tkinter.Frame(sf.interior())) image.append(PNGImage2(frame[i], da, pal=pal, tmpNm="tmp.ppm")) image[i].pack(side="top") dn = "Image Array : Seq # " + str(i) + ": " numb.append(Tkinter.Label(frame[i], text=dn)) numb[i].pack(side="top") vminl.append(Tkinter.Label(frame[i], text="min:" + str(vmin))) vminl[i].pack(side="top") vmaxl.append(Tkinter.Label(frame[i], text="max:" + str(vmax))) vmaxl[i].pack(side="top") frame[i].grid(row=i / columns, column=i % columns, padx=0, pady=5)

def get_suggested_focal_point(self): with self.get_willow_image() as willow: faces = willow.detect_faces() if faces: # Create a bounding box around all faces left = min(face[0] for face in faces) top = min(face[1] for face in faces) right = max(face[2] for face in faces) bottom = max(face[3] for face in faces) focal_point = Rect(left, top, right, bottom) else: features = willow.detect_features() if features: # Create a bounding box around all features left = min(feature[0] for feature in features) top = min(feature[1] for feature in features) right = max(feature[0] for feature in features) bottom = max(feature[1] for feature in features) focal_point = Rect(left, top, right, bottom) else: return None # Add 20% to width and height and give it a minimum size x, y = focal_point.centroid width, height = focal_point.size width *= 1.20 height *= 1.20 width = max(width, 100) height = max(height, 100) return Rect.from_point(x, y, width, height)

def insert(self, start, end, linenum=0, other=None): root = self if start > self.start: # insert to right tree if self.right: self.right = self.right.insert(start, end, linenum, other) else: self.right = IntervalNode(start, end, linenum, other) # rebalance tree if self.priority < self.right.priority: root = self.rotateleft() else: # insert to left tree if self.left: self.left = self.left.insert(start, end, linenum, other) else: self.left = IntervalNode(start, end, linenum, other) # rebalance tree if self.priority < self.left.priority: root = self.rotateright() if root.right and root.left: root.maxend = max(root.end, root.right.maxend, root.left.maxend) root.minend = min(root.end, root.right.minend, root.left.minend) elif root.right: root.maxend = max(root.end, root.right.maxend) root.minend = min(root.end, root.right.minend) elif root.left: root.maxend = max(root.end, root.left.maxend) root.minend = min(root.end, root.left.minend) return root

def __index(img): r, c = np.shape(img) start = 0 while start < c & len(np.where(img[:, start])[0]) == 0: start += 1 if start >= 10: start = 2 end = c - 1 while end >= 0 and len(np.where(img[:, end])[0]) == 0: end -= 1 if end < 710: end = min(c - 1, 717) indexes = [] for i in range(31): idx = int(min(start + i * ((end - start) / 30.0), c - 1)) locs = np.where(img[:, idx])[0] if len(locs) == 0: indexes.append(0) continue loc = int(np.median(locs)) indexes.append(r - loc + 1) m = min(indexes) return [i - m for i in indexes]

def lookUp(self, parameter): maxIndex = self.length - 1 p = min(max(parameter * maxIndex, 0), maxIndex) before = int(p) after = min(before + 1, maxIndex) influence = p - before return self.parameters[before] * (1 - influence) + self.parameters[after] * influence

def __generate_payouts(self, num_hills, hill_size): """ Compute several gaussians and build the payout map """ hills = [] for i in range(num_hills): cx = random.randint(0, self.width - 1) cy = random.randint(0, self.height - 1) sx = random.random() * hill_size + 1 sy = random.random() * hill_size + 1 theta = random.random() * math.pi hills.append(Gaussian2D((cx, cy), (sx, sy), theta)) # Add a mirror image one too to make the map fair hills.append(Gaussian2D(self.__mirror(cx, cy), (sx, sy), theta + math.pi)) # Sum all the hills money_payout_rates = [[0.0] * self.height for x in range(self.width)] for y in range(self.height): for x in range(self.width): money_payout_rates[x][y] = sum([h.value((x, y)) for h in hills]) # Normalize the rates from 0->1 max_payout = max([max(row) for row in money_payout_rates]) min_payout = min([min(row) for row in money_payout_rates]) for y in range(self.height): for x in range(self.width): offset = money_payout_rates[x][y] - min_payout money_payout_rates[x][y] = offset / (max_payout - min_payout) money_payout_rates[x][y] = int(1000 * money_payout_rates[x][y]) / 1000.0 return money_payout_rates

def iter_test(self, func_name, dim_count): """ Runs the PSO algorithm given the initialization parameters, outputting a list of the best values from the run """ bests = [] func = Function(func_name)(dim_count) self.pop = self._generate_pop(self.size, func) p_min = min(self.pop) self.best = np.copy(p_min.position) self.best_val = p_min.val bests.append(self.best_val) for _ in xrange(self.gen): self.pop = [p.map_eval(self.best, self.alpha, self.beta) for p in self.pop] p_min = min(self.pop) if p_min.val < self.best_val: self.best = np.copy(p_min.position) self.best_val = p_min.val bests.append(self.best_val) return np.array(bests)

def OnMouseMotion(self, evt): pos = self.CalcUnscrolledPosition(evt.GetPosition()).Get() self._objectUnderCursor = self.FindObjectUnderPoint(pos) self._curMousePos = pos if not evt.LeftIsDown(): self._draggingObject = None self._connectionStartObject = None if evt.LeftIsDown() and evt.Dragging() and self._draggingObject: dx = pos[0] - self._lastDraggingPosition[0] dy = pos[1] - self._lastDraggingPosition[1] newX = self._draggingObject.position[0] + dx newY = self._draggingObject.position[1] + dy # Check canvas boundaries newX = min(newX, self.canvasDimensions[0] - self._draggingObject.boundingBoxDimensions[0]) newY = min(newY, self.canvasDimensions[1] - self._draggingObject.boundingBoxDimensions[1]) newX = max(newX, 0) newY = max(newY, 0) self._draggingObject.position = [newX, newY] # Cursor will be at a border of a node if it goes out of canvas self._lastDraggingPosition = [min(pos[0], self.canvasDimensions[0]), min(pos[1], self.canvasDimensions[1])] self.Render()

def process_order(self, event, order): max_volume = self.volume_limit * event.volume # price impact accounts for the total volume of transactions # created against the current minute bar remaining_volume = max_volume - self.volume_for_bar if remaining_volume < 1: # we can't fill any more transactions return # the current order amount will be the min of the # volume available in the bar or the open amount. cur_volume = int(min(remaining_volume, abs(order.open_amount))) if cur_volume < 1: return # tally the current amount into our total amount ordered. # total amount will be used to calculate price impact total_volume = self.volume_for_bar + cur_volume volume_share = min(total_volume / event.volume, self.volume_limit) simulated_impact = (volume_share) ** 2 * math.copysign(self.price_impact, order.direction) * event.price return create_transaction( event, order, # In the future, we may want to change the next line # for limit pricing event.price + simulated_impact, math.copysign(cur_volume, order.direction), )

def highPass2DFilter(sdataset, user_stretchval="Contrast", user_britlo=0, user_brithi=255): """ 2 dimensional high pass filter from McIDAS-X equation for each sdataset element = (sdataset - (sample average) + (sample midpoint)) user_britlo - minimum brightness value for the calibration user_brithi - maximum brightness value for the calibration """ newData = sdataset.clone() stretch = user_stretchval britlo = int(user_britlo) brithi = int(user_brithi) for t in xrange(newData.getDomainSet().getLength()): rangeObject = newData.getSample(t) vals = rangeObject.getFloats(0) in_hi = max(vals[0]) in_low = min(vals[0]) domain = GridUtil.getSpatialDomain(rangeObject) [element_size, line_size] = domain.getLengths() """ first and last 2 lines of the image do not change """ firstLine = vals[0][0:element_size] last2Lines = vals[0][(line_size - 2) * element_size : line_size * element_size] """ do the filter using 3 lines at a time """ for i in range(line_size)[:-3]: for j in range(element_size)[1:-1]: midValue = vals[0][(i + 1) * element_size + j] val = ( vals[0][(i + 2) * element_size + j] + vals[0][i * element_size + j] + vals[0][(i + 1) * element_size + j + 1] + vals[0][(i + 1) * element_size + j - 1] ) - 4 * midValue if val < midValue: vals[0][i * element_size + j] = scaleOutsideVal(midValue - val, britlo, brithi) else: vals[0][i * element_size + j] = 0 vals[0][0 : line_size * element_size] = firstLine + vals[0][0 : (line_size - 3) * element_size] + last2Lines for i in range(line_size): for j in range(element_size): vals[0][i * element_size + j] = scaleOutsideVal(vals[0][i * element_size + j], britlo, brithi) filt_low = int(min(vals[0])) filt_hi = int(max(vals[0])) if stretch == "Contrast": lookup = contrast(filt_low, filt_hi, britlo, brithi, filt_low, filt_hi) elif stretch == "Histogram": h = makeHistogram(vals, element_size, line_size, filt_low, brithi - britlo) lookup = histoStretch(filt_low, filt_hi, in_low, in_hi, h) vals = modify(vals, element_size, line_size, filt_low, lookup) rangeObject.setSamples(vals) return newData

def __handle_select_button_ccs(self, cc_no, cc_value): if cc_no == FX_SELECT_FIRST_BUTTON_ROW: if cc_value == CC_VAL_BUTTON_PRESSED: self.__parent.toggle_lock() elif cc_no == FX_SELECT_ENCODER_ROW: if cc_value == CC_VAL_BUTTON_PRESSED: new_index = min( len(self.song().scenes) - 1, max(0, list(self.song().scenes).index(self.song().view.selected_scene) - 1), ) self.song().view.selected_scene = self.song().scenes[new_index] elif cc_no == FX_SELECT_SECOND_BUTTON_ROW: if cc_value == CC_VAL_BUTTON_PRESSED: new_index = min( len(self.song().scenes) - 1, max(0, list(self.song().scenes).index(self.song().view.selected_scene) + 1), ) self.song().view.selected_scene = self.song().scenes[new_index] elif cc_no == FX_SELECT_POTIE_ROW: if cc_value == CC_VAL_BUTTON_PRESSED: self.song().view.selected_scene.fire_as_selected() elif cc_no == FX_SELECT_DRUM_PAD_ROW: if cc_value == CC_VAL_BUTTON_PRESSED: self.song().stop_all_clips() else: raise False or AssertionError, "unknown select row midi message"

def calc_L_T(all_nodes, jobs): todo = [] for n in all_nodes: n.visited = False if not n.outgoings: todo.append(n) max_L_T = max([n.E_T for n in todo]) print "max_L_T", max_L_T for n in todo: n.L_T = max_L_T while todo: # print [(n.id,n.order, n.E_T, n.L_T)for n in todo] n = todo.pop() # print 'del node : ', (n.id, n.order) n.visited = True for edge in n.incomings: edge.start_n.L_T = min(edge.start_n.L_T, n.L_T - edge.time) if edge.start_n.visited == False: todo.append(edge.start_n) # =========================================================================== # revise node's L_T which is for yc's discharging operation # =========================================================================== for j in jobs: if j.state == "discharging" and j.nodes[2].planed == False: j.nodes[2].L_T = min( j.nodes[2].L_T, j.nodes[1].L_T + Input.yc_discharging_operation + Input.yc_discharging_operation )

def on_touch_move(self, touch): if touch.grab_current == self: if touch.ud["page"] == "previous": self.children[-self.page - 1].x = max( min(self.x + self.border + (touch.x - touch.ox), self.right - self.border), self.x + self.border ) if self.page > 1: self.children[-self.page].x = min( self.x + self.border * (touch.sx - touch.osx), self.x + self.border ) if self.page < len(self.children) - 1: self.children[-self.page + 1].x = min( self.right - self.border * (1 - (touch.sx - touch.osx)), self.right ) elif touch.ud["page"] == "next": self.children[-self.page + 1].x = min( max(self.right - self.border + (touch.x - touch.ox), self.x + self.border), self.right - self.border ) if self.page >= 1: self.children[-self.page - 1].x = max(self.x + self.border * (1 - (touch.osx - touch.sx)), self.x) if self.page < len(self.children) - 2: self.children[-self.page].x = max( self.right + self.border * (touch.sx - touch.osx), self.right - self.border ) return self.children[-self.page - 1].on_touch_move(touch)

def polygon_vec(vertices, L, border_value=True): """ Return True/False is a pixel is inside a polygon. @param vertices: numpy ndarray Nx2 @param L: size of the image @param border_value: boolean Numpy vectorial implementation. """ y, x = numpy.ogrid[:L, :L] counter = numpy.zeros((L, L), dtype=int) nvert = len(vertices) polypoint1y, polypoint1x = vertices[nvert - 1][0], vertices[nvert - 1][1] for i in range(nvert): polypoint2y, polypoint2x = vertices[i][0], vertices[i][1] if polypoint1y == polypoint2y: counter[polypoint1y, min(polypoint1x, polypoint2x) : max(polypoint1x, polypoint2x)] += 1 else: c = numpy.logical_and(y > min(polypoint1y, polypoint2y), y <= max(polypoint1y, polypoint2y)) xinters = (y - polypoint1y) * (polypoint2x - polypoint1x) / (polypoint2y - polypoint1y) + polypoint1x counter[numpy.logical_and(c, x <= xinters)] += 1 polypoint1x, polypoint1y = polypoint2x, polypoint2y res = counter % 2 == 1 return res

def dameraulevenshtein(seq1, seq2): """ Calculate the Damerau-Levenshtein distance between sequences. codesnippet:D0DE4716-B6E6-4161-9219-2903BF8F547F Conceptually, this is based on a len(seq1) + 1 * len(seq2) + 1 matrix. However, only the current and two previous rows are needed at once, so we only store those. Same code as word-level checking. """ oneago = None thisrow = range(1, len(seq2) + 1) + [0] for x in xrange(len(seq1)): twoago, oneago, thisrow = oneago, thisrow, [0] * len(seq2) + [x + 1] for y in xrange(len(seq2)): delcost = oneago[y] + 1 addcost = thisrow[y - 1] + 1 subcost = oneago[y - 1] + (seq1[x] != seq2[y]) thisrow[y] = min(delcost, addcost, subcost) if x > 0 and y > 0 and seq1[x] == seq2[y - 1] and seq1[x - 1] == seq2[y] and seq1[x] != seq2[y]: thisrow[y] = min(thisrow[y], twoago[y - 2] + 1) return thisrow[len(seq2) - 1]

def reinit(self, A0, A1, B0, B1, C0, C1, D0, D1): self.box[:, :] = 0.0 self.A0 = A0 self.A1 = A1 self.B0 = B0 self.B1 = B1 self.C0 = C0 self.C1 = C1 self.D0 = D0 self.D1 = D1 self.offset0 = int(floor(min(self.A0, self.B0, self.C0, self.D0))) self.offset1 = int(floor(min(self.A1, self.B1, self.C1, self.D1))) self.box_size0 = int(ceil(max(self.A0, self.B0, self.C0, self.D0))) - self.offset0 self.box_size1 = int(ceil(max(self.A1, self.B1, self.C1, self.D1))) - self.offset1 self.A0 -= self.offset0 self.A1 -= self.offset1 self.B0 -= self.offset0 self.B1 -= self.offset1 self.C0 -= self.offset0 self.C1 -= self.offset1 self.D0 -= self.offset0 self.D1 -= self.offset1 self.pAB = self.pBC = self.pCD = self.pDA = None self.cAB = self.cBC = self.cCD = self.cDA = None self.area = None

def move_cursor(self, x_offset=0, y_offset=0): sbinfo = self.screen_buffer_info() new_pos = COORD( min(max(0, sbinfo.CursorPosition.X + x_offset), sbinfo.Size.X), min(max(0, sbinfo.CursorPosition.Y + y_offset), sbinfo.Size.Y), ) windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos)

def plotErrorBars(dict_to_plot, x_lim, y_lim, xlabel, y_label, title, out_file, margin=[0.05, 0.05], loc=2): plt.title(title) plt.xlabel(xlabel) plt.ylabel(y_label) if y_lim is None: y_lim = [1 * float("Inf"), -1 * float("Inf")] max_val_seen_y = y_lim[1] - margin[1] min_val_seen_y = y_lim[0] + margin[1] print min_val_seen_y, max_val_seen_y max_val_seen_x = x_lim[1] - margin[0] min_val_seen_x = x_lim[0] + margin[0] handles = [] for k in dict_to_plot: means, stds, x_vals = dict_to_plot[k] min_val_seen_y = min(min(np.array(means) - np.array(stds)), min_val_seen_y) max_val_seen_y = max(max(np.array(means) + np.array(stds)), max_val_seen_y) min_val_seen_x = min(min(x_vals), min_val_seen_x) max_val_seen_x = max(max(x_vals), max_val_seen_x) handle = plt.errorbar(x_vals, means, yerr=stds) handles.append(handle) print max_val_seen_y plt.xlim([min_val_seen_x - margin[0], max_val_seen_x + margin[0]]) plt.ylim([min_val_seen_y - margin[1], max_val_seen_y + margin[1]]) plt.legend(handles, dict_to_plot.keys(), loc=loc) plt.savefig(out_file)

def get_norm_image_size(self): if not self.texture: return self.size ratio = self.image_ratio w, h = self.size tw, th = self.texture.size # ensure that the width is always maximized to the containter width if self.allow_stretch: if not self.keep_ratio: return w, h iw = w else: iw = min(w, tw) # calculate the appropriate height ih = iw / ratio # if the height is too higher, take the height of the container # and calculate appropriate width. no need to test further. :) if ih > h: if self.allow_stretch: ih = h else: ih = min(h, th) iw = ih * ratio return iw, ih

def genFreeIP(self, vmgid): if not self.db: print "creator: Please give the db" exit(1) # subnet for uid/gids , usedIPs from mappings # or ask dhcp, maybe look in leases. try: row = self.db.getOneRowWithCriteria("VMGroup", "*", "and", {"id": vmgid}) ip_range = row["ip_range"] # "192.168.100.15-192.168.100.254" min_ip, max_ip = ip_range.split("-") min_ip = self.ipstr_to_number(min_ip) max_ip = self.ipstr_to_number(max_ip) # find used IPs (mappings) from this range rows = self.db.getRowsWithCriteria("Mapping", "ip", "", {}) if db.debug: print rows nlist = range(min_ip, max_ip) for row in rows: for ip in row: # only one # used_host_no=commands.getstatusoutput("cut -d'.' -f4 <<<{0}".format(ip))[1] #host digits ipno = self.ipstr_to_number(ip) if ipno in nlist: nlist.remove(ipno) if db.debug: print self.number_to_ipstr(min(nlist)) return self.number_to_ipstr(min(nlist)) except db.DatabaseException as e: print e.err exit(1) pass

def distance_between_codingblocks(self, other, organism=None, node=None): """ Distance in AA between two CodingBlockGraphs @type organism: * @param organism: Organism identifier (or None) @type node: * @param node: Node identifier (or None) @rtype: dictionary (or integer if organism or node is specified) @return: dictionary with organisms (keys) and AA-distance between CBGs (values), or only a distance if an Organism or Node identifier was specified @attention: other (CBG) is supposed to be 3p/rigth of 'self' (current CBG) """ # get overall minimal spanning ranges omsrSelf = self.overall_minimal_spanning_range() omsrOther = other.overall_minimal_spanning_range() distances = {} for org in self.organism_set().intersection(other.organism_set()): if organism and org != organism: continue nodeA = self.node_by_organism(org) nodeB = other.node_by_organism(org) distA = min(omsrSelf[nodeA]) - max(omsrOther[nodeB]) distB = min(omsrOther[nodeB]) - max(omsrSelf[nodeA]) distances[org] = max([distA, distB]) - 1 # return distance only of a specific organism is requested for if organism: return distances[organism] else: return distances

def contrast(in_low, in_hi, out_low, out_hi, minimum, maximum, inc=1): """ create a contrast stretch lookup table in_low - input low image value in_hi - input high image value out_low - output low image value out_hi - output high image value minimum - minimum data value maximum - maximum data value inc - increment """ smallFloat = 0.00000000000001 if in_hi == in_low: slope = 0 else: slope = float(out_hi - out_low) / float(in_hi - in_low) lookup = [] for input_value in xrange(minimum, maximum + 1, inc): out_value = out_low + int(round((input_value - in_low) * slope + smallFloat)) if slope < 0: out_value = max(min(out_value, out_low), out_hi) else: out_value = min(max(out_value, out_low), out_hi) indx = input_value - minimum for i in xrange(inc): lookup.insert(indx, out_value) indx = indx + 1 return lookup

def plot_value_function(agent_class, run, i): """ Plot the value functions for run i. """ plt.clf() agent = load(agent_class, run) state0 = simulator.Simulator().get_state() values, qval1, qval2 = [], [], [] min_range = -SHIFT_VECTOR[i] max_range = SCALE_VECTOR[i] variables = [] for j in range(VALUE_STEPS): var = max_range * (1.0 * j / VALUE_STEPS) + min_range state0[i] = var values.append(agent.value_function(state0)) feat = agent.action_features[0](state0) qval1.append(agent.action_weights[0].dot(feat)) qval2.append(agent.action_weights[1].dot(feat)) variables.append(var) max_val = max(max(qval1), max(qval2), min(values)) min_val = min(min(qval1), min(qval2), min(values)) plt.plot(variables, values, "-b", label="$V(s)$") plt.plot(variables, qval1, "-r", label="$Q(s, a_1)$") plt.plot(variables, qval2, "-g", label="$Q(s, a_2)$") plt.axis([min_range, max_range, min_val, max_val]) plt.legend(loc="lower right") plt.xlabel(str(i)) plt.ylabel("$V$") plt.savefig("./runs/" + agent.name + "/value_functions/s" + str(i), bbox_inches="tight")

def OnSplitterMouseMove(self, *args): if self.dragging: self.splitter.diffx = uicore.uilib.x - self.initx self.splitter.diffy = uicore.uilib.y - self.inity if self.isVertical: if self.totalValue is None: self.totalValue = self.GetAbsoluteSize()[0] diff = self.splitter.diffx else: if self.totalValue is None: self.totalValue = self.GetAbsoluteSize()[1] diff = self.splitter.diffy if self.victimCont.align in (uiconst.TOBOTTOM, uiconst.TORIGHT): diff = -diff mostDiffAllowed = self.restInitvalue - self.minRestValue diff = min(diff, mostDiffAllowed) newValue = max(self.minVictimValue, diff + self.victimInitvalue) newValue = min(self.maxVictimValue, newValue) if self.isVertical: self.victimCont.width = newValue else: self.victimCont.height = newValue self.victimValue = newValue self.victimRatio = float(newValue) / self.totalValue self.OnSizeChanging()