def get_parcels(): small_parcel = Parcel(5, 8) # 3 medium_parcel = Parcel(25, 30) # 8 large_parcel = Parcel(80, 60) # 15 xlarge_parcel = Parcel(110, 90) # 25 heavy_parcel = Parcel(20, 20, 80) # 50 + 30 return [ small_parcel, medium_parcel, large_parcel, xlarge_parcel, heavy_parcel ]
def grow(self): # self.map_log() for building_type in self.building_iterator: print("\nTrying to place {}".format(building_type.name)) # Village Element Seeding Process interest_map, accessibility_map, sociability_map = interest( building_type, self.scenario, self.maps, [self.ghost] + self.parcel_list, self.size, self.parcel_size) building_position = random_interest(interest_map) new_parcel = Parcel(building_position, building_type, self.maps) self.parcel_list.append(new_parcel) self.maps.obstacle_map.add_parcel_to_obstacle_map(new_parcel, 2) # self.map_log(obstacle_map=self.maps.obstacle_map.map) # Road Creation Process self.maps.road_network.connect_to_network(new_parcel.entry_point) self.map_log(interest_map, accessibility_map, sociability_map, building_type)
def load_parcels(self, file): """ Load parcels from csv file. Returns a list with Parcel objects. """ with open(INPUT) as in_file: data_frame = csv.reader(in_file, delimiter=',') next(data_frame) parcels = [] for parcel in data_frame: name = parcel[0] parcel = Parcel(parcel[0], float(parcel[1]), float(parcel[2])) parcels.append(parcel) return parcels
def __init__(self, scenario, maps, ghost_position, parcel_list, parcel_size=7): # type: (str, map.maps.Maps, Point2D, List[Parcel], int) -> VillageSkeleton assert (parcel_size % 2) # assert parcel_size is odd self.scenario = scenario self.size = (maps.width, maps.length) self.maps = maps self.ghost = Parcel(ghost_position, BuildingType.from_name('ghost')) self.building_iterator = BuildingPool( (maps.width - parcel_size - 1) * (maps.length - parcel_size - 1) - maps.fluid_map.as_obstacle_array.sum()) self.parcel_list = parcel_list self.parcel_size = parcel_size
def get_data_from_parcel_file(self): """ Loads information and retrieves parcel weights and destinations. :return:None """ filename = 'parcels.txt' cities = [] weights = [] with open(filename, 'r') as parcel_file: for line in parcel_file.readlines(): if line.startswith('#'): continue data = line.split() cities.append(data[0]) weights.append(float(data[1])) for city, weight in zip(cities, weights): self.list_of_parcels.append(Parcel(city, weight))
scenario, settlement_seeds) return sociability_map if __name__ == '__main__': from building_seeding import BuildingType # Sociability test N = 50 building_net = np.zeros((N, N)) set_seeds = [] house_1 = Parcel(Point2D(15, 31), BuildingType().house) building_net[15, 31] = 1 set_seeds.append(house_1) house_2 = Parcel(Point2D(26, 6), BuildingType().house) building_net[26, 6] = 1 set_seeds.append(house_2) mill_1 = Parcel(Point2D(37, 18), BuildingType().windmill) building_net[37, 18] = 2 set_seeds.append(mill_1) building_cmap = colors.ListedColormap( ['forestgreen', 'darkorange', "yellow"]) building_map = Map("building_map", N, building_net, building_cmap, (0, 2), ['Grass', 'House', "Windmill"])
Nds = 20 a_types = np.array([0.1 for i in range(Nds)]) A_types = np.array([(i+1)/Nds for i in range(Nds)]) T_types = np.random.normal(295., 10., size=a_types.shape) T_types = None # Step forward in time and plot that toward convergence h = 0.001 ts = np.arange(0., 100.+h, h) pops = np.zeros((len(ts), len(a_types))) pops[0] = np.zeros_like(a_types) + 0.01 # daisy object initialization daisy = Daisy(1, 0.3, a_types, A_types, 1, T_types) for i, t in enumerate(ts[:-1]): # go one step forward pops[i+1] = daisy.rk4Solve(0, h, onestep=True)[:-1] daisy. print(f'Iteration {i} of {len(ts)} done. {daisy.L}.', end='\r') print(end='\n') # Plot the values as a function of time figure, ax = plt.subplots() cmap = plt.get_cmap('rainbow') colors = [cmap(i/pops.shape[1]) for i in range(pops.shape[1])] for c, d in zip(colors, range(pops.shape[1])): ax.plot(ts, pops[:,d], c=c, label=f'Daisy {d}')
from shipping_price_info import ShippingPriceInfo from parcel import Parcel def get_parcels(): small_parcel = Parcel(5, 8) # 3 medium_parcel = Parcel(25, 30) # 8 large_parcel = Parcel(80, 60) # 15 xlarge_parcel = Parcel(110, 90) # 25 heavy_parcel = Parcel(20, 20, 80) # 50 + 30 return [ small_parcel, medium_parcel, large_parcel, xlarge_parcel, heavy_parcel ] if __name__ == "__main__": shipping_infos = { "Small": ShippingPriceInfo(3, 1, 2), "Medium": ShippingPriceInfo(8, 3, 2), "Large": ShippingPriceInfo(15, 6, 2), "XLarge": ShippingPriceInfo(25, 10, 2), "Heavy": ShippingPriceInfo(50, 50, 1) } small_parcel = [Parcel(1, 1)] small_order = Shipment(small_parcel, shipping_infos) assert small_order.get_shipment_price() == 3 many_parcels = get_parcels() shipments = Shipment(many_parcels, shipping_infos) assert shipments.get_shipment_price() == 131
def roughness_calc(self, parcel, wind_direction): # This function calculates a data-driven surface roughness and the corresponding fetch length: parcel_data = pd.read_csv('D:/Users/Karen/Documents/GitHub/DPBWE/Datasets/Parcels/ResSub.csv') # Find the parcel's centroid - this will be the origin for the z0 calculation: originz = parcel.footprint['geometry'].centroid # Parcel footprint is a Polygon type xp,yp = parcel.footprint['geometry'].exterior.xy # Create an array of fetch lengths: fetch = np.arange(0.0005, 1, 0.0005) # degrees latitude/longitude # Interested in storing the following information per (final) sector: sector_df = pd.DataFrame(columns=['z0', 'Local Wind Speed', 'Fetch', 'Building List', 'Sector Geometry']) for sector in range(0,2): # Create an empty DataFrame to hold values of wind speed, roughness length, and fetch length: terrain_params = pd.DataFrame(columns=['Roughness Length', 'Fetch Length', 'Local Wind Speed']) # Create an empty DataFrame to store any buildings that are within the fetch: fetch_bldgs = pd.DataFrame(columns=['Building ID', 'BIM']) # Create an empty DataFrame to hold all values needed for roughness length calc: z_params = pd.DataFrame(columns=['Building ID', 'Building Height', 'Surface Area']) for f in fetch: # Determine the sector geometries: sector_geom = Site.get_sector(self, originz, wind_direction, f) # Create point objects for each building (longitude, latitude) & check if point is within sector: for row in range(0, len(parcel_data)): bldg_point = Point(parcel_data['Longitude'][row], parcel_data['Latitude'][row]) # Check if the building is within the specified boundary: if bldg_point.within(sector_geom[sector]): # Check that a BIM has not yet been created for the building and that the BIM is not the case study: pid = parcel_data['Parcel ID'][row] if pid in fetch_bldgs["Building ID"].values or pid == parcel.pid: pass else: # Populate the remaining fields to create a Parcel Instance: occupancy = parcel_data['Use Code'][row] if 'VAC' in occupancy: vac_flag = 1 # Keep track of VACANT LOTS else: vac_flag = 0 num_stories = parcel_data['Stories'][row] yr_built = parcel_data['Year Built'][row] address = parcel_data['Address'][row] sq_ft = parcel_data['Square Footage'][row] lon = parcel_data['Longitude'][row] lat = parcel_data['Latitude'][row] new_parcel = Parcel(pid, num_stories, occupancy, yr_built, address, sq_ft, lon, lat) fetch_bldgs = fetch_bldgs.append({'Building ID': pid, 'BIM': new_parcel}, ignore_index=True) xparcel,yparcel = new_parcel.footprint["geometry"].exterior.xy plt.plot(xparcel, yparcel) else: pass # Check to see if we have any buildings: print('Number of buildings captured:', len(fetch_bldgs["BIM"])) if len(fetch_bldgs["BIM"]) == 0: tol = 1.0 # Provide a default value for tolerance and move on to the next fetch length else: # Buildings within bounding geometry: interested in their 1) height and 2) surface area # Loop through the buildings: for bldg in fetch_bldgs['BIM']: # Avoid repeating this step for previously identified buildings: if bldg.pid in z_params['Building ID'].values: pass else: # Given wind direction, calculate surface area as follows: # Create equivalent rectangle using building footprint coordinates and multiply by building height xbldg,ybldg = bldg.footprint["geometry"].exterior.xy rect = Polygon([(max(xbldg), max(ybldg)), (max(xbldg), min(ybldg)), (min(xbldg), min(ybldg), min(xbldg), max(ybldg))]) xrect,yrect = rect.exterior.xy # Convert coordinates into numpy arrays: xrect = np.array(xrect) yrect = np.array(yrect) # Calculate the surface area for each obstruction (building): if wind_direction == 0 or wind_direction == 180: # For these wind directions, we want the side parallel to the latitude: d1 = Site.dist_calc(self, max(xrect), min(yrect), min(xrect), min(yrect)) d2 = Site.dist_calc(self, min(xrect), max(yrect), min(xrect), min(yrect)) #d = Site.dist_calc(self, max(xrect), min(yrect), min(xrect), min(yrect)) h_rmean = 0.5 * (min(d1, d2) / 2) * math.atan(2 / 12) bldg.h_bldg = bldg.h_bldg + h_rmean surf_area = bldg.h_bldg * d1 elif wind_direction == 90 or wind_direction == 270: # For these wind directions, we want the side parallel to the longitude: d1 = Site.dist_calc(self, max(xrect), min(yrect), min(xrect), min(yrect)) d2 = Site.dist_calc(self, min(xrect), max(yrect), min(xrect), min(yrect)) #d = Site.dist_calc(self, min(xrect), max(yrect), min(xrect), min(yrect)) # If this building has a pitched roof, find the mean roof height using the smallest dimension: h_rmean = 0.5*(min(d1, d2)/2)*math.atan(2/12) bldg.h_bldg = bldg.h_bldg+h_rmean print("new height:", bldg.h_bldg) surf_area = bldg.h_bldg * d2 elif wind_direction == 45 or wind_direction == 135 or wind_direction == 225 or wind_direction == 315: # For these wind directions, we want both sides of the rectangle: d1 = Site.dist_calc(self, max(xrect), min(yrect), min(xrect), min(yrect)) d2 = Site.dist_calc(self, min(xrect), max(yrect), min(xrect), min(yrect)) h_rmean = 0.5 * (min(d1, d2) / 2) * math.atan(2 / 12) bldg.h_bldg = bldg.h_bldg + h_rmean surf_area = bldg.h_bldg * (d1+d2) # Add new row to empty DataFrame: z_params = z_params.append({'Building ID': bldg.pid, 'Building Height': bldg.h_bldg, 'Surface Area': surf_area}, ignore_index=True) # Calculate the average height of all buildings within the fetch length: h_avg = z_params['Building Height'].mean() # Calculate the average surface area: surf_avg = z_params['Surface Area'].mean() # Calculate the site area: # Calculate the meters distance of the fetch length: fdist = Site.dist_calc(self, originz.x, originz.y, originz.x + f, originz.y) print('Fetch in meters:', fdist, "Fetch size:", f) site_area = (math.pi*fdist**2)/8 # Calculate the roughness length: z0 = 0.5*h_avg*surf_avg/(site_area/len(fetch_bldgs)) print('Roughness length:', z0) # Calculate the wind speed: vnew = Site.calc_windspeed(self, parcel.h_bldg, z0) # Populate the DataFrame with the values for this fetch length: terrain_params = terrain_params.append({'Roughness Length': z0, 'Fetch Length': fdist, 'Local Wind Speed': vnew}, ignore_index=True) # Create plot to show current buildings within the sector: for bldg in fetch_bldgs['BIM']: xcoords, ycoords = bldg.footprint["geometry"].exterior.xy plt.plot(xcoords, ycoords) # Add the case study structure to the plot and the sector geometry: xsite, ysite = sector_geom[sector].exterior.xy plt.plot(xp, yp, xsite, ysite) plt.axis('equal') plt.show() # Check the difference in the wind speed: if len(terrain_params['Roughness Length']) == 1: tol = 1.0 # provide a default value for the tolerance for first z0 else: vcurrent = terrain_params.loc[terrain_params.index[-1], "Local Wind Speed"] # get current wind speed vprev = terrain_params.loc[terrain_params.index[-2], "Local Wind Speed"] # get previous step wind speed tol = abs((vcurrent-vprev)/vcurrent) # Threshold checks: # Roughness length: Assume we are in Exposure B (ASCE 7-10) range of z0 unless other criteria are met: zreq = [0.15, 0.7] # range of z0 values for Suburban/urban [m] # zreq = [0.01, 0.15] # range of z0 values for Open Terrain [m] # zreq = [0.005, 0.01] # range of z0 for Open Water (lower limit from ASCE 7) [m] # Break the loop if the new fetch length provides us with the right tolerance value: if abs(tol) < 0.1 and fdist > 457.2 and z0 > 0.1: # Now that we've identified all parcels, plot for confirmation: xsite, ysite = sector_geom[sector].exterior.xy plt.plot(xp, yp, xsite, ysite) plt.axis('equal') plt.show() print("fetch length:", fdist) print("roughness length:", z0) print("tolerance:", abs(tol)) # Store the final values for the sector: sector_df.append({'z0': z0, 'Local Wind Speed': vnew, 'Fetch': fdist, 'Building List': fetch_bldgs, 'Sector Geometry': sector_geom[sector]}, ignore_index=True) break else: pass
elif hnew < 4.6: kz = 2.01*((15/3.281)/zg)**(2/alpha) return vnew # Identify the parcel: # Cedar's Crossing: # lon = -85.620215 # lat = 30.180998 # test = Parcel('14805-133-000', 1, 'SINGLE FAM', 2009, '1806 EVERITT AVE PANAMA CITY 32405', 2103, lon, lat) lon = -85.666162 lat = 30.19953 test = Parcel('12989-113-000', 1, 'SINGLE FAM', 1974, '2820 STATE AVE PANAMA CITY 32405', 3141, lon, lat) # Create an instance of the site class: wind_direction = 270 # data is a DataFrame object with column label = ['geometry'] and indexes = [0: end] # Accessing a specific Polygon object then requires: data['geometry'][index] site = Site(test, wind_direction) #test = site.calc_windspeed(21, 0.78, 11.7, 10, 0.08) #print(test) # Recreating plot from HAZUS-HM #heights = np.array([3, 5, 10, 20, 50, 100]) #zs = np.linspace(0.001,1,1000) #for h in heights: #lst = []
import numpy as np from shapely.geometry import Polygon from bldg_code import ASCE7 from tpu_pressures import calc_tpu_pressures from tpu_pressures import find_tpu_use_case, get_TPU_surfaces, map_tap_data # Initialization script for data-driven workflow: # Asset Description # Parcel Models lon = -85.676188 lat = 30.190142 test = Parcel('12345', 4, 'financial', 1989, '1002 23RD ST W PANAMA CITY 32405', 41134, lon, lat, length_unit='ft') test.hasElement['Roof'][0].hasShape['flat'] = True test.hasElement['Roof'][0].hasPitch = 0 # Hazard Characterization # Here is where we provide wind speed, location, etc. for data-driven roughness length # Will also need to add WDR (rain rate) characterizations # Will also need to add subroutine for WBD # Asset Representation # Generate and determine the building's TPU surfaces: tpu_wdir = 0 key = 'local'
def ready(self): Parcel.start()
def setupGrid(self, n, m, maxtheta=80, oceans=False, inputfile=None): ''' Sets up the Tube's grid of parcels. Args: + n, m (ints): the width and height of the grid. If inputfile is provided, the input will be padded to match n and m if one is greater than the provided dimensions, and if n and m are less than the provided dimensions they will be ignored. + maxtheta (float): the maximum latitude (in degrees) to model to. Default is 80. + oceans (bool): if True, will model oceans (default False). If inputfile is provided, will read that in for the oceans (where O's are considered oceans, X's landmasses, and spaces are ignored.) For example, if I had the file: x x o o x x o o o This would generate a 3x3 grid (provided n, m are equal to or less than 3) with one landmass in cells (0,0), (0,1), (1,1), and (1,2), with all other cells filled by oceans. If m or n was larger than 3, the remaining cells would be padded *by ocean objects*. + inputfile (str or None): if None (default) will randomly generate oceans if oceans is True. If a string, will use that file per the description above to generate a world. NOTE: If inputfile is provided, it will override the value of oceans and will assume oceans are to be generated. ''' # Read in the inputfile if provided. if inputfile is not None: # Make sure inputfile is a string assert isinstance(inputfile, str), "Infile must be None or" \ "a string" # Read in the file with open(inputfile, 'r') as infile: m = 0 lines = [] # Doing it this way for ease of coding, not expensive anyways for line in infile.readlines(): m += 1 n = 0 for char in line.strip().split(): if char.lower().strip() == 'x': val = 1 else: val = 0 lines.append(val) n += 1 landgrid = np.array(lines) elif oceans: # Randomly generate ocean map landgrid = np.random.randint(2, size=m * n) else: labdgrid = np.ones(m * n) # Assign attributes self.n = n # width self.m = m # height self.maxtheta = maxtheta # max latitude to use self.deltheta = self.maxtheta / (0.5 * m) # theta resolution self.npix = n * m self.thetas = (np.ones([m, n]) * np.linspace(maxtheta, -maxtheta, m)[:, np.newaxis]) self.Ls = abs( np.sin((90 - self.thetas.reshape(self.npix)) * np.pi / 180 + self.phi)) grid = [] for i, val in enumerate(landgrid): if landgrid[i] == 1: grid.append( Parcel(self.P, self.gamma, self.a_vec, self.A_vec, self.Ls[i], T_vec=self.T_vec)) else: grid.append(Ocean(290)) self.grid = np.reshape(grid, (m, n))
# Reads the parcel information from a CSV file and creates a # new Parcel object with the values from the current row. with open('parcels.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: parcel_id = int(row[0]) address = row[1] city = row[2] state = row[3] zip_code = row[4] deadline = row[5] mass = int(row[6]) special = row[7] parcel = Parcel(parcel_id, address, city, state, zip_code, deadline, mass, special) package_table.insert(parcel) # Updating the address for the package that had the wrong address. package_table.table[9].address = '410 S State St' # Create the Controller, truck_1 and truck_2 # Loads the trucks WGUPS_controller = Controller() truck_1 = Truck(locations[0], locations, 8, 0) truck_2 = Truck(locations[0], locations, 8, 0) WGUPS_controller.add_truck(truck_1) WGUPS_controller.add_truck(truck_2) truck_2.add_parcel(package_table.search_parcel(15)) truck_2.add_parcel(package_table.search_parcel(16)) truck_2.add_parcel(package_table.search_parcel(34))
def getHash(): packageHash = Hash(40) packageHash.insert( Parcel(1, 5, (10, 30), "SLC", "84115", 21, "undelivered")) packageHash.insert(Parcel(2, 9, (17, 0), "SLC", "84106", 44, "undelivered")) packageHash.insert(Parcel(3, 8, (17, 0), "SLC", "84103", 2, "undelivered")) packageHash.insert(Parcel(4, 18, (17, 0), "SLC", "84115", 4, "undelivered")) packageHash.insert(Parcel(5, 19, (17, 0), "SLC", "84111", 5, "undelivered")) packageHash.insert( Parcel(6, 13, (10, 30), "W Valley", "84119", 88, "undelivered")) packageHash.insert(Parcel(7, 2, (17, 0), "SLC", "84106", 8, "undelivered")) packageHash.insert(Parcel(8, 12, (17, 0), "SLC", "84103", 9, "undelivered")) packageHash.insert(Parcel(9, 19, (17, 0), "SLC", "84103", 2, "undelivered")) # Wrong address packageHash.insert( Parcel(10, 25, (17, 0), "SLC", "84105", 1, "undelivered")) packageHash.insert( Parcel(11, 10, (17, 0), "SLC", "84118", 1, "undelivered")) packageHash.insert( Parcel(12, 16, (17, 0), "W Valley", "84119", 1, "undelivered")) packageHash.insert( Parcel(13, 6, (10, 30), "SLC", "84104", 2, "undelivered")) packageHash.insert( Parcel(14, 20, (10, 30), "MillCreek", "84117", 88, "undelivered")) packageHash.insert( Parcel(15, 21, (9, 0), "Holladay", "84117", 4, "undelivered")) packageHash.insert( Parcel(16, 21, (10, 30), "Holladay", "84117", 88, "undelivered")) packageHash.insert( Parcel(17, 14, (17, 0), "SLC", "84119", 2, "undelivered")) packageHash.insert(Parcel(18, 3, (17, 0), "SLC", "84123", 6, "undelivered")) packageHash.insert( Parcel(19, 4, (17, 0), "SLC", "84115", 37, "undelivered")) packageHash.insert( Parcel(20, 17, (10, 30), "SLC", "84115", 37, "undelivered")) packageHash.insert( Parcel(21, 17, (17, 0), "SLC", "84115", 3, "undelivered")) packageHash.insert( Parcel(22, 26, (17, 0), "Murray", "84121", 2, "undelivered")) packageHash.insert( Parcel(23, 23, (17, 0), "SLC", "84118", 5, "undelivered")) packageHash.insert( Parcel(24, 22, (17, 0), "Murray", "84107", 7, "undelivered")) packageHash.insert( Parcel(25, 24, (10, 30), "SLC", "84117", 7, "undelivered")) packageHash.insert( Parcel(26, 24, (17, 0), "SLC", "84117", 25, "undelivered")) packageHash.insert(Parcel(27, 1, (17, 0), "SLC", "84104", 5, "undelivered")) packageHash.insert( Parcel(28, 11, (17, 0), "SLC", "84115", 7, "undelivered")) packageHash.insert( Parcel(29, 2, (10, 30), "SLC", "84106", 2, "undelivered")) packageHash.insert( Parcel(30, 12, (10, 30), "SLC", "84103", 1, "undelivered")) packageHash.insert( Parcel(31, 15, (10, 30), "SLC", "84119", 1, "undelivered")) packageHash.insert( Parcel(32, 15, (17, 0), "SLC", "84119", 1, "undelivered")) packageHash.insert(Parcel(33, 9, (17, 0), "SLC", "84106", 1, "undelivered")) packageHash.insert( Parcel(34, 21, (10, 30), "Holladay", "84117", 2, "undelivered")) packageHash.insert( Parcel(35, 1, (17, 0), "SLC", "84104", 88, "undelivered")) packageHash.insert( Parcel(36, 7, (17, 0), "W Valley", "84119", 88, "undelivered")) packageHash.insert( Parcel(37, 19, (10, 30), "SLC", "84111", 2, "undelivered")) packageHash.insert( Parcel(38, 19, (17, 0), "SLC", "84111", 9, "undelivered")) packageHash.insert(Parcel(39, 6, (17, 0), "SLC", "84104", 9, "undelivered")) packageHash.insert( Parcel(40, 18, (10, 30), "SLC", "84115", 45, "undelivered")) return packageHash