def run(self): num_round = 0 while(1): _,f = self.cam.read() if self.gen_maps: for gm_id in self.gen_maps: self.gen_maps[gm_id].update_attrs(utils.copy_image(f)) Patch.osc_update_all_attrs() for output in self.text_outputs: cv2.putText(f, output.text, output.loc, output.font, output.scale, output.color) if num_round % 30 == 0: for gm_id in self.gen_maps: gm = self.gen_maps[gm_id] cv2.putText(f, '%s-%s' % (gm.region.id, gm.gen.gen_type), (gm.region.centroid_x, gm.region.centroid_y), self.font, self.scale, self.color) gm.region.draw_outline(f, utils.BGR_RED) gm.region.draw_blobs(f, utils.BGR_GREEN) cv2.imshow('e2',f) if cv2.waitKey(10)==27: break cv2.destroyAllWindows()
def test_risque(self): patch1 = Patch(risqueString="frny-4001a-pp24-04-19 (back)") self.assertEqual(patch1.building, "frny") self.assertEqual(patch1.room, "4001a") self.assertEqual(patch1.patchType, "pp24") self.assertEqual(patch1.panelNumber, 4) self.assertEqual(patch1.portNumber, 19) patch2 = Patch(risqueString="bown-1111a-c6pp24-01-13 (back)") self.assertEqual(patch2.building, "bown") self.assertEqual(patch2.room, "1111a") self.assertEqual(patch2.patchType, "c6pp24") self.assertEqual(patch2.panelNumber, 1) self.assertEqual(patch2.portNumber, 13)
def loadPatches(filename): '''loads patches from one image ''' normalizedFilename = filename.replace('.bmp', '_normalized.data') normIn = open(normalizedFilename, 'r') normalized = np.fromstring(normIn.read()).reshape(502, 758) #print np.mean(normalized), np.std(normalized) normIn.close() patchesFilename = filename.replace('.bmp', '_patches.data') patchIn = open(patchesFilename, 'r') patchDesc = patchIn.read().split('\n') patchIn.close() patches = [] for patchLine in patchDesc: if not patchLine: continue (row, col) = [int(x) for x in patchLine.split()] patch = normalized[row:row + 16, col:col + 16].flatten() patches.append(Patch(patch)) return patches
def createPatches(self): #Use multiprocessing count = 0 for r in range(41): for c in range(41): self.__patches[r,c] = Patch(count, True) #this should insert a Patch object - I made every Patch a Field count += 1 return self.__patches
def __init__(self, compartments): """ Create a new network :param compartments: Compartments to add to node """ # Just one node, no edges nodes = [Patch(0, compartments)] MetapopulationNetwork.__init__(self, nodes)
def grid_patches(self, im=None): if im is None: im = self.im if type(im) is list: im = im[0] self.height, self.length, _ = im.shape offset_patches = int(self.size * 0.75) self.patches = [] for x in range(0, self.height - self.size, offset_patches): for y in range(0, self.length - self.size, offset_patches): self.patches.append(Patch(im, x, y, self.size)) self.patches.append( Patch(im, x, self.length - self.size, self.size)) for y in range(0, self.length - self.size, offset_patches): self.patches.append( Patch(im, self.height - self.size, y, self.size)) self.patches.append(Patch(im, self.height - self.size, self.length - self.size, self.size))
def patch_dispatcher(patchnumber): tid, ip = setup_log_vars() lggr = setup_local_logger(tid, ip) PAT = Patch() patch = str(patchnumber) data = getattr(PAT, patch.lower())(request) if 'redirect' in data: return data else: return render_template(data['template'], data=data)
def main(): genA = Gen(None, 'genA') genB = Gen(None, 'genB') genC = Gen(None, 'genC') genD = Gen(None, 'genD') genE = Gen(None, 'genE') genF = Gen(None, 'genF') genA.add_patch_to(genB) genB.add_patch_to(genC) genB.add_patch_to(genD) genD.add_patch_to(genA) genD.add_patch_to(genE) Patch.dfs_patch_search(genA) for patch in Patch.patch_list: print patch genB.add_patch_to(genF) Patch.dfs_patch_search(genA) for patch in Patch.patch_list: print patch
def __init__(self, compartments, number_patches, connections): """ Create a new multi-patch network :param compartments: Compartments of subpopulations of nodes :param number_patches: Number of nodes in network :param connections: Edge definitions - consists of (n1, n2) pairs integers, where 0 <= n1, n2 < number_patches """ # Create the nodes nodes = [Patch(n, compartments) for n in range(number_patches)] edges = [] # Create the edges for (n1, n2) in connections: edges.append(Edge(nodes[n1], nodes[n2])) MetapopulationNetwork.__init__(self, nodes, edges)
def determineField(self): self.__best_harvest = -100 best_field = Patch(0, True) for field in self.__household.getFieldsOwned( ): #traverses through fields_owned by the associated household this_harvest = (field.inner.getFertility() * self.__max_potential_yield * self.__household.getCompetency()) - ( self.findDistance(field) * self.__household.getDistanceCost()) #yield is dependent on fertility, whether or not the household actually farms the field (competency), distance from the field and the distance cost if (field.inner.isHarvested() == False and this_harvest >= self.__best_harvest): #finds the highest yield field self.__best_harvest = this_harvest best_field = field return best_field
def addPatchParams(self, pxcor, pycor, pcolor, plabel, plabelColor): rex_string = re.compile(r"\"(.*)\"") patch = Patch() patch.pxcor = int(pxcor) patch.pycor = int(pycor) patch.pcolor = float(pcolor) match = rex_string.search(plabel) if match != None: patch.plabel = match.group(1) else: patch.plabel = plabel patch.plabelColor = float(plabelColor) self.addPatch(patch) return patch
def main(): initOSCClient() gens = [SinOsc(None), SawOsc(None)] # sinA = SinOsc(None) # sawA = SawOsc(None) for gen in gens: if gen.is_root: Patch.dfs_patch_search(gen) Patch.osc_send_all_patches() while (True): for gen in gens: gen.attrs['gain'] = random() Patch.osc_update_all_attrs() time.sleep(0.5)
def rentLand(self): patches = self.map.getPatches() #gets list of patch objects r = np.arange(0, 41) c = np.arange(0, 41) cr = self.__coordinates[0] cc = self.__coordinates[1] radius = self.__knowledge_radius mask = (r[np.newaxis, :] - cr)**2 + ( c[:, np.newaxis] - cc )**2 < radius**2 #determines indices in the circle with knowledge radius best_harvest = 0 total_harvest = 0 best_field = Patch(34567, True) for patch in patches[ mask]: #traverses through array of patches in the knowledge radius this_harvest = ( patch.inner.getFertility() * 2475 * self.__competency) - ( self.inner.findDistance(patch) * self.__distance_cost) if (patch.isField() and patch.inner.isHarvested() == False and this_harvest >= best_harvest): self.__best_harvest = this_harvest best_field = patch #determines the yield of the field and finds the highest yield of all unharvested fields in the knowledge radius harvest_chance = random.uniform(0, 1) if (harvest_chance < self.__ambition * self.__competency): best_field.inner.toggleHarvested() total_harvest += ((best_harvest * (1 - (self.__rental_rate / 100))) - 300) #if high enough ambition and competency, total harvest is calculated according to the amount of yield of the best field and the rental rate self.__tot_grain += total_harvest self.inner.clearWorkersWorked()
def claimFields(self, row, col): patches = self.map.getPatches() claim_chance = random.uniform( 0, 1) #creates a random float between 0 and 1 if (claim_chance < self.__ambition and self.__size > len(self.__fields_owned) or len(self.__fields_owned) <= 1): #checks if household will be trying to claim land #The decision to claim is a function of the productivity of the field compared to existing fields and ambition. current_grain = self.__tot_grain claim_field = Patch(34567, True) best_fertility = 0 r = np.arange(0, 41) c = np.arange(0, 41) cr = row cc = col #current row and column coordinates of the household radius = self.__knowledge_radius #determines indices in the circle with knowledge radius mask = (r[np.newaxis, :] - cr)**2 + (c[:, np.newaxis] - cc)**2 < radius**2 for patch in patches[ mask]: #traverses through array of patches in the circle if patch.isField() == True and patch.isOwned( ) == False and patch.isRiver() == False and patch.isSettlement( ) == False: #checks to see if the field meets criteria to be claimed fertility = patch.inner.getFertility() if fertility > best_fertility: #finds field with best fertility best_fertility = fertility claim_field = patch x = self.completeClaim( claim_field) #complete claim method is called return x #returns coordinates of the field to be claimed
def _pick_patches(self): for i in range(self.nb - len(self.patches)): self.patches.append(Patch(self.im, size_patch=self.size))
def start(): # init camera cam = cv2.VideoCapture(1) # init osc communication with chuck initOSCClient() cam_thread = CameraOutThread(cam) cam_thread.start() time.sleep(0.5) raw_input("Press Enter when camera is positioned") # display numbers on regions image = cam.read() regions = Region.find_regions_by_border_color(image[1]) for region in regions: cam_thread.add_text(TextOutput(str(region.id), (region.centroid_x, region.centroid_y))) # ask for Gen type for each region dac = DAC() gen_maps = {} for i, region in enumerate(regions): while (True): try: gen_type = raw_input("Please enter UGen type for region %s: " % region.id) gen = eval(gen_type)() attr_range = [0.0, 1.0] if isinstance(gen, Osc): attr_range[0] = float(raw_input(" What is the low frequency on this oscillator? ")) attr_range[1] = float(raw_input(" What is the high frequency on this oscillator? ")) gen_maps[region.id] = GenMap(gen, region, attr_range=attr_range) break except: print 'Invalid UGen, try again.' # ask for gen links # dac special to_where while (raw_input("Add a patch? (y/n): ") == 'y'): from_where = None while (True): try: # NOTE: no range checking from_where = int(raw_input('from Region #: ')) from_where = gen_maps[from_where] break except ValueError: print 'Please enter an integer.' to_where = None while (True): try: to_where = raw_input('to Region #: ') if to_where == 'dac': to_where = dac break to_where = int(to_where) to_where = gen_maps[to_where] break except ValueError: print 'Please enter an integer.' # will handle dac later # for now, all patch paths assumed end in dac if not isinstance(to_where, DAC): (from_where.gen).add_patch_to(to_where.gen) Patch.find_patches([gen_maps[gm_id].gen for gm_id in gen_maps]) Patch.osc_send_all_patches() cam_thread.text_outputs = [] cam_thread.gen_maps = gen_maps
def addPatchPanel(self, patchString): try: self.patch = Patch(risqueString=patchString) except: # if we fail to add parse the patch panel, silently fail self.patch = None