def getBasicState(): state = GameState.getBlankState() # player 1 p1Queen = Ant((0, 0), QUEEN, 0) state.board[0][0].ant = p1Queen state.inventories[0].ants.append(p1Queen) p1Hill = Building((0, 0), ANTHILL, 0) p1Tunnel = Building((9, 0), TUNNEL, 0) state.board[0][0].constr = p1Hill state.board[0][9].contrs = p1Tunnel state.inventories[0].constrs += [p1Hill, p1Tunnel] #player 2 p2Queen = Ant((9, 9), QUEEN, 1) state.board[9][9].ant = p2Queen state.inventories[1].ants.append(p2Queen) p1Hill = Building((9, 9), ANTHILL, 1) p1Tunnel = Building((0, 9), TUNNEL, 1) state.board[9][9].constr = p1Hill state.board[9][0].contrs = p1Tunnel state.inventories[1].constrs += [p1Hill, p1Tunnel] return state
def test_building_buffed_by_town_properties(self): town_buffed = self.towns[0] town_norm = self.towns[2] town_dampened = self.towns[1] arb = 10 farm_buffed = Building("farm", town_buffed, [0, arb], self.player) farm_norm = Building("farm", town_norm, [0, arb], self.player) farm_dampened = Building("farm", town_dampened, [0, arb], self.player) farm_buffed.calculate_production() farm_norm.calculate_production() farm_dampened.calculate_production() print(farm_buffed.city.properties) print(farm_norm.city.properties) print(farm_dampened.city.properties) farm_rich = farm_buffed.production[0] farm_standard = farm_norm.production[0] farm_poor = farm_dampened.production[0] assert farm_rich > farm_standard assert farm_standard > farm_poor
def printState(self, bestGene): ''' Description: Creates a state with the best gene in a population to print an ascii representation to a file. Parameters: bestGene - best gene in the current population ''' ants1 = [] cons1 = [] ants2 = [] cons2 = [] #Booger Player Buildings cons3 = [] #FOOD #fill state with best gene's placements for i, coord in enumerate(bestGene): if i == 0: cons1.append(Building((coord), ANTHILL, self.playerId)) elif i == 1: cons1.append(Building((coord), TUNNEL, self.playerId)) elif i < 11: cons1.append(Building((coord), GRASS, self.playerId)) else: cons3.append(Building((coord), FOOD, NEUTRAL)) newInventories = [ Inventory(self.playerId, ants1, cons1, 0), Inventory(abs(self.playerId - 1), ants2, cons2, 0), Inventory(NEUTRAL, [], cons3, 0) ] dummyState = GameState(None, newInventories, 2, self.playerId) self.asciiPrintState(dummyState) #print state to file
def make_buildings_from_saved_file( building_data: Dict[str, List]) -> List[Building]: buildings: List[Building] = [] # First, create buildings without their connections for building_data in building_data["data"]: buildings.append( Building(**building_data, annotate_with_text=False)) # then connect them all temp_city = City(buildings, on_change=lambda: None, create_streets_between_buildings=False) def get_building_at_pos(x, y): return temp_city.get_building_at_pos((x, y)) # Convert each building's connections from coordinates to Building objects for building in buildings: building.connections = [ get_building_at_pos(*coords) for coords in building.connections ] return buildings
def test_building_placed(self): case_study_town = self.towns[0] test_farm = Building("farm", case_study_town, [0, 0], self.player) case_study_town.holdings.append(test_farm) case_study_town.holdings = [test_farm] assert test_farm in case_study_town.holdings
def test_elevators(): ELEVATOR_COUNT = 2 theBuilding = Building("Blair Plaza", 17, ELEVATOR_COUNT) theBuilding.start_elevators() print("Elevator status: " + ', '.join(theBuilding.get_elevators_statuses())) theTracker = Elevator_tracker(theBuilding, 0.2) theTracker.start_tracking() sleep(1.5) theBuilding.call_elevator(4, -1) sleep(2.5) # theBuilding.call_elevator(8, 1) sleep(5) # theBuilding.call_elevator(2, 1) # sleep(10) print ("The End") theBuilding.stop_elevators() print("Elevator status: " + ', '.join(theBuilding.get_elevators_statuses())) theTracker.end_tracking() #print("Tracker status: " + theTracker.get_tracker_status()) theTracker.plot_track()
def initializeBuildingsAndPopulation(self): # Initialize Buildings step = self.townSize[0] / 15 for x in range(step, 14 * step, step): for y in range(step, 14 * step, step): self.buildings.append( Building('House', (x, y), [0, random.randint(2, 6)])) mid = len(self.buildings) / 2 self.buildings[mid].type = 'Store' self.buildings[mid].capacity = [0, 0] #Initialize population infective = int(self.parameters.initialProbabilityInfected * 100) susceptible = 100 - infective my_list = ['I'] * infective + ['S'] * susceptible for i in range(self.popSize): for b in self.buildings: if b.capacity[0] < b.capacity[1]: friends = self.findFriends(b) initialCondition = random.choice(my_list) if initialCondition == 'I': self.population.append( Person(i + 1, b.location[0], b.location[1], False, True, b, self.buildings[mid], friends)) else: self.population.append( Person(i + 1, b.location[0], b.location[1], True, False, b, self.buildings[mid], friends)) b.capacity[0] += 1 break
def create_map(self): for row in range(self.size_rows): self.maps.append([]) for col in range(self.size_columns): self.maps[row].append( Building("building", self.building_types[random.randrange(0, 13)])) while self.number_of_main_road_elements != 0: self.generate_next_element() print("") for line in self.maps: for element in line: if isinstance(element, Building): print("B", end=" ") elif isinstance(element, Street): print(".", end=" ") else: print("*", end=" ") print("") print("") # print(self.road) # print("") return self.maps
def init(self): # self.arrivesMemoryVariable = "Arrives Freight House" self.departsMemoryVariable = "Departs Freight House" self.freightHouse = Building() self.freightHouse.init(self.arrivesMemoryVariable, self.departsMemoryVariable) self.scheduleTimes = [] self.scheduleTimes.append( memories.provideMemory(self.arrivesMemoryVariable)) self.stove = lights.provideLight("NL120") self.platformLights = lights.provideLight("NL121") self.officeLight = lights.provideLight("NL122") self.dockLight = lights.provideLight("NL123") self.platformIndicator = lights.provideLight("IL121") self.officeIndicator = lights.provideLight("IL122") self.dockIndicator = lights.provideLight("IL123") self.platformLightDimmer = lights.provideLight("NL124") self.officeLightDimmer = lights.provideLight("NL125") self.dockLightDimmer = lights.provideLight("NL126")
def addBuilding(angle, distFromCenter, sectorAngle, buildingSize=1): innerLength = max(distFromCenter - ringSize, 0) angleSeperationOuter = ( sectorAngle - (buildingSeperation / distFromCenter)) * buildingSize angleSeperationInner = angleSeperationOuter poly = [ Point(innerLength * math.cos(angle), innerLength * math.sin(angle)), Point(distFromCenter * math.cos(angle), distFromCenter * math.sin(angle)), Point(distFromCenter * math.cos(angle + angleSeperationOuter), distFromCenter * math.sin(angle + angleSeperationOuter)), Point(innerLength * math.cos(angle + angleSeperationInner), innerLength * math.sin(angle + angleSeperationInner)) ] pointsOutOfFrame = 0 for p in poly: pM = p + Point(imageSize[0] / 2, imageSize[1] / 2) if not (pM.x > 0 and pM.x < imageSize[0] and pM.y > 0 and pM.y < imageSize[1]): pointsOutOfFrame += 1 if pointsOutOfFrame < len(poly): objects.append( Building(Point(imageSize[0] / 2, imageSize[1] / 2), poly, 1, fill=(random.randint(50, 255), 0, random.randint(50, 255))))
def get_full_enigma_data(self): file = open("db/seed/data.csv", "rU") reader = csv.reader(file, delimiter=',') idx = 0 for building_data in reader: if idx < self.start_idx: idx += 1 continue building_class = building_data[44] if building_data[24] == None: idx += 1 continue addressArr = building_data[24].split(' ', 1) class_prefix = building_class[0] if building_class == None: # Don't save to db if not a proper building class idx += 1 continue if class_prefix not in {"A", "B", "C", "D", "S"} and building_class not in {"HB", "HH", "HR", "R1", "R2", "R3", "R4", "R6", "R7", "R8", "R9", "RR"}: idx += 1 continue if len(addressArr) == 1: # Don't save to db if not a full address idx += 1 continue building = Building(building_data) building.get_bis() if driver.title != DEFAULT_TITLE: print("Overworked server. Starting again at index {}".format(idx)) time.sleep(.5) populator = Populator(ENIGMA_BUILDINGS_ID, True, False, idx) return building.get_bis_data() if driver.title != PROPERTY_PROFILE_TITLE: # listing not found -- move to next index print("Listing does not exist in BIS network") idx += 1 continue # exit out of loop and proceed to next entry building.get_building_id() is_duplicate = building.check_if_duplicate() if self.is_replacing_duplicates and is_duplicate: building.delete_duplicate() if is_duplicate and not self.is_replacing_duplicates: print("Duplicate entry: #{}".format(building.building_id)) idx += 1 continue print("Current idx: {}".format(idx)) building.get_complaints_and_violations() building.get_landlord() building.get_lat_long_coordinates() building.get_building_footprint() building.post_data(idx) idx += 1
def __init__(self): """Initialize the SLSQP algorithm for a specific building. """ print("Initializing the SLSQP Optimizer...") self.opt_prob = [] self.opt = [] self.building = Building()
def __init__( self, building_path="data/building_oib_16linie.xlsx", kWp=1, # PV kWp battery_kWh=1): # Battery kWh ###### Compononets ##### # (Other classes and parts, that form the model) self.building = Building(path=building_path) self.HVAC = HVAC() self.PV = PV(csv="data/pv_1kWp.csv", kWp=1) self.PV.set_kWp(kWp) self.battery = Battery(kWh=battery_kWh) ###### Parameters ##### self.cp_air = 0.34 # spez. Wärme kapazität Luft (Wh/m3K) self.price_grid = 0.19 # €/kWh self.price_feedin = 0.05 # €/kWh ###### Timeseries ##### # load Usage characteristics self.Usage = pd.read_csv("data/usage_profiles.csv", encoding="cp1252") # load climate data self.TA = np.genfromtxt("data/climate.csv", delimiter=";")[1:, 1] # load solar gains self.QS = np.genfromtxt("data/Solar_gains.csv") # W/m²
def test2(): ELEVATOR_COUNT = 2 theBuilding = Building("Blair Plaza", 17, ELEVATOR_COUNT) theBuilding.start_elevators() theTracker = Elevator_tracker(theBuilding, 1) #0.2 theTracker.start_tracking() print ("The End") theTracker.end_tracking()
def main(): list = [] while (True): print("1 - add new") print("2 - delete") print("3 - search") print("4 - show all") x = input() if int(x) == 1: print("City name:") city_name = input() print("population:") population = input() print("Street name") street_name = input() print("Building number:") building_number = input() print("Apartment number:") apartment_number = input() if street_name == "" and building_number == "" and apartment_number == "": item = City(city_name, population) elif building_number == "" and apartment_number == "": item = Street(city_name, population, street_name) elif apartment_number == "": item = Building(city_name, population, street_name, building_number) else: item = Apartment(city_name, population, street_name, building_number, apartment_number) list.append(item) elif int(x) == 2: print("1 - City name") print("2 - Population") print("3 - Street name") print("4 - Building number") print("5 - Apartment") field = input() print("What?") what = input() print("DELETED") for m in delete(list, field, what): print(m) elif int(x) == 3: print("1 - City name") print("2 - Population") print("3 - Street name") print("4 - Building number") print("5 - Apartment") field = input() print("What?") what = input() for m in search(list, field, what): print(m) else: for m in list: print(m)
def __init__(self, building_path="data/building.xlsx", # building parameters kWp=0, # PV parameters battery_kWh=0): # battery parameters print("initializing Model") ###### Compononets ##### # (Other classes and parts, that form the model) # your code here... self.building = Building(path=building_path)
def populate_building(self, single_row): """ From each row of an Excel sheet Building,it craetes object of Building and stores it in dictionary. Also populates the dictionary which maps mail codes with corresponding buildings Args: :param single_row: represents one row of the sheet building of an excel file """ b = Building(single_row[0], single_row[1], single_row[2]) self.__node_by_id[single_row[0]] = b self.populate_bulding_mail_code_from_list(single_row[0], single_row[3])
def __constructBuildings__(self, buildingNameMap, rawData): idToBuildingPixelMap = {k: [] for k in buildingNameMap} for y in range(Constants.HEIGHT): for x in range(Constants.WIDTH): buildingId = rawData[y * Constants.WIDTH + x] assert (buildingId == 0 or buildingId in buildingNameMap) if (buildingId != 0): idToBuildingPixelMap[buildingId].append(Point(x, y)) return [ Building(buildingNameMap[buildingId], buildingId, pixels) for buildingId, pixels in idToBuildingPixelMap.items() ]
def placeBuilds(self, scene, cityMap, length, width, origin): currX = origin[0] for row in cityMap: currY = origin[1] for cell in row: if cell == "tower": self.tower = Building(scene, "tower", currX, currY, 0) elif type(cell) == list: self.renderBlocks(scene, cell, length / 9, width / 11, (currX, currY)) currY -= width currX -= length
def create_state(self, ai): #create game state for testing self.state = self.setup_state() players = [c.PLAYER_ONE, c.PLAYER_TWO] for player in players: self.state.whoseTurn = player constrsToPlace = [] constrsToPlace += [Building(None, c.ANTHILL, player)] constrsToPlace += [Building(None, c.TUNNEL, player)] constrsToPlace += [ Construction(None, c.GRASS) for i in xrange(0, 9) ] setup = ai.getPlacement(self.state) for piece in setup: self.place_items(piece, constrsToPlace, self.state) self.state.flipBoard() self.state.phase = c.SETUP_PHASE_2 for player in players: self.state.whoseTurn = player constrsToPlace = [] constrsToPlace += [ Construction(None, c.FOOD) for i in xrange(0, 2) ] setup = ai.getPlacement(self.state) for food in setup: self.place_items(food, constrsToPlace, self.state) self.state.flipBoard() self.setup_play(self.state) self.state.whoseTurn = c.PLAYER_ONE return self.state
def addBuilding(position, otherBuildings, canvas): pool = multiprocessing.Pool(processes=12) polyPoints = [Point(0, 0)] + [ p for p in pool.starmap( findRayCollisions, zip( repeat(position), repeat(otherBuildings), range(0, int((math.pi * 2) * 1000), int((math.pi) * 1000 / NUM_RAYS)))) if p != None ] if len(polyPoints) > 2: #canvas.ellipse((position.x, position.y, position.x + 10, position.y + 10), fill=(255, 0, 0), outline=(0, 0, 0)) objects.append(Building(position, tuple(polyPoints), 1)) else: objects.append( Building(position, [ Point(0, 0), Point(random.randint(-100, 100), random.randint(-100, 100)), Point(random.randint(-100, 100), random.randint(-100, 100)) ]))
def buildingArray(browser, buildingSettings): allButtons = browser.find_elements_by_class_name('build_up') buildings = [] k = 0 while k < len(buildingSettings): newBuilding = Building(buildingSettings[k], allButtons[k]) if newBuilding.haveEnoughResources: buildings.append(newBuilding) k += 1 return buildings
def init(self): # self.arrivesMemoryVariable = "Arrives Freight House" self.departsMemoryVariable = "Departs Freight House" self.freightHouse = Building() self.freightHouse.init(self.arrivesMemoryVariable, self.departsMemoryVariable) self.scheduleTimes = [] self.scheduleTimes.append( memories.provideMemory(self.arrivesMemoryVariable)) #self.stove = lights.provideLight("NL120"); #self.platformLights = lights.provideLight("NL121"); #self.officeLight = lights.provideLight("NL122"); #self.dockLight = lights.provideLight("NL123"); #self.platformIndicator = lights.provideLight("IL121"); #self.officeIndicator = lights.provideLight("IL122"); #self.dockIndicator = lights.provideLight("IL123"); #self.platformLightDimmer = lights.provideLight("NL124"); #self.officeLightDimmer = lights.provideLight("NL125"); #self.dockLightDimmer = lights.provideLight("NL126"); self.freightDock = TriStateSensor( sensors.provideSensor("Freight Dock Dim"), sensors.provideSensor("Freight Dock On"), sensors.provideSensor("Freight Dock Off")) self.freightOffice = TriStateSensor( sensors.provideSensor("Freight Office Dim"), sensors.provideSensor("Freight Office On"), sensors.provideSensor("Freight Office Off")) self.freightPlatform = TriStateSensor( sensors.provideSensor("Freight Platform Dim"), sensors.provideSensor("Freight Platform On"), sensors.provideSensor("Freight Platform Off")) self.freightStove = TriStateSensor( None, sensors.provideSensor("Freight Stove"), None) self.sideDoor = sensors.provideSensor( "Mine Bldg Side Soor") # Mine Bldg Side Door self.lockerRoom = sensors.provideSensor( "Mine Bldg S2") # Mine Bldg Level 2 - Locker Room self.tipple = sensors.provideSensor("Mine Bldg S3") # Mine Bldg Tipple
def create_building(self, pos: Tuple[int, int]) -> None: """ Creates a building at the given position """ new_building_pos = (pos[0] - NODE_RADIUS // 4, pos[1] - NODE_RADIUS // 4) new_building = Building(*new_building_pos, connections=[], annotate_with_text=False) self.buildings.append(new_building) self.on_change()
def displayUndescribedPoints(village): undescribedPoints = [] for x in range(Constants.WIDTH): for y in range(Constants.HEIGHT): point = Point(x, y) dummyBuilding = Building("dummyBuilding", -1, [point]) if all([ len(elem) == 0 for elem in __getComparativePosition__( village, dummyBuilding) ]): undescribedPoints.append(point) print(f'Num of undescribed points: {len(undescribedPoints)}') mapArr = __createEmptyMap__() for building in village.getBuildings(): __replacePoints__(mapArr, building.getPoints(), Constants.WHITE) __replacePoints__(mapArr, undescribedPoints, Constants.RED) __display__(mapArr)
def __clickEvent__(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: global gClickCount global gMapArr isEvenClick = gClickCount % 2 == 0 gClickCount = gClickCount + 1 if isEvenClick: gMapArr = __setUpGMap__() clickBuilding = Building("clickBuilding", -1, [Point(x, y)]) print( __describeComparativePosition__( __getComparativePosition__(gVillage, clickBuilding))) comparativelySimilarPoints = __getComparativelySimilarPoints__( gVillage, clickBuilding) __replacePoints__(gMapArr, comparativelySimilarPoints, Constants.TEAL if isEvenClick else Constants.RED) cv2.imshow("Campus Map", gMapArr)
def renderBlocks(self, scene, block, length, width, origin): buildCode = {1:"house1", 2:"house2", 3:"house3", 4:"build", \ 5:"concrete", 6:"r", 7:"cafe", 8:"old"} currX = origin[0] # resets data so to fit key to ZData for row in block: currY = origin[1] # resets data to fit key to ZData for cell in row: try: # try to read z-value from database (x, y) = (int(currX // 100 * 100) - 400, int(currY // 100 * 100)) currZ = self.zData[(x, y)] except: continue if cell in buildCode: name = buildCode[cell] cell = Building(scene, name, currX, currY, currZ) currY -= width currX -= length
def createRandomInstance(self, nBuildings, nRooms, nCourses): # create random buildings for building in range(nBuildings): tmp = Building() tmp.xCoord = self.random.nextDouble() * self.MAX_X_COORD tmp.yCoord = self.random.nextDouble() * self.MAX_Y_COORD print("x: {} y: {}".format(tmp.xCoord, tmp.yCoord)) self.buildings.append(tmp) # create random rooms for room in range(nRooms): tmp = Room() bld = int(self.random.nextDouble() * nBuildings) print("bld: {}".format(bld)) tmp.b = self.buildings[int(self.random.nextDouble() * nBuildings)] tmp.capacity = (int(self.random.nextDouble() * 70)) + 30 self.rooms.append(tmp) # create random courses print(nCourses) for course in range(nCourses): tmp = Course() tmp.enrolledStudents = (int(self.random.nextDouble() * 70)) + 30 tmp.preferredLocation = self.buildings[int( self.random.nextDouble() * nBuildings)] tmp.value = self.random.nextDouble() * 100 tmp.timeSlotValues = [0] * self.NUM_TIME_SLOTS # debug # print("Num time slots: {}".format(self.NUM_TIME_SLOTS)) # print(tmp.timeSlotValues) for j in range(self.NUM_TIME_SLOTS): if (self.random.nextDouble() < float(0.3)): tmp.timeSlotValues[j] = 0 else: tmp.timeSlotValues[j] = int(self.random.nextDouble() * 10) self.courses.append(tmp) print("Courses timeslotvalues and real value:") for idx, course in enumerate(self.courses): print("idx {}: {} -> {}".format(idx, course.timeSlotValues, course.value))
def __init__(self): """Initialize the GP_SS algorithm for a specific building. """ print("Initializing the GP_SS...") self.building = Building() self.X = [] self.Y = [] self.dynModels = [] # Number of Initial Exploration Simulation self.initExploration = 36 # Number of Samples for witching to Sparse Gaussian Processes self.num_inducing = 2000 # Safety constraint for exploration self.explorationConstraint = 0.03 # Needed to determine the best controller out of all iterations self.costs = [] self.constraints = [] self.policies = [] self.baseline = []
def displaySimilarPointCluster(village, comparison): descriptionMap = {} most = ("", None) for x in range(Constants.WIDTH): for y in range(Constants.HEIGHT): point = Point(x, y) description = __describeComparativePosition__( __getComparativePosition__( village, Building("dummyBuilding", -1, [point]))) if description in descriptionMap.keys(): descriptionMap[description].append(point) else: descriptionMap[description] = [point] for key, val in descriptionMap.items(): if comparison(key, val, most[1]): most = (key, val) print(most[0]) print(f'number of points: {len(most[1])}') mapArr = __createEmptyMap__() for building in village.getBuildings(): __replacePoints__(mapArr, building.getPoints(), Constants.WHITE) __replacePoints__(mapArr, most[1], Constants.RED) __display__(mapArr)