# In[60]:


# Get a list of all of the tif files
tif_files = [os.path.join(path_to_harvey_images, fn) for fn in os.listdir(path_to_harvey_images) if fn.endswith('tif')]
tif_files[:3]


# In[61]:


# Get the shape of each image
geometry = []
for tif_file in tif_files:
    with rasterio.open(tif_file) as src:
        geometry.append(shapely.geometry.box(*src.bounds))


# In[62]:


# Create a GeoDataFrame with the image footprints
footprints = gpd.GeoDataFrame({'file_name': tif_files}, geometry=geometry, crs={'init': 'epsg:4326'})


# In[63]:


# Filter for just the images that have flooding in them (I know I sqeezed a lot into one line)
footprints_with_flooding = footprints[footprints.index.isin(gpd.sjoin(flooding, footprints, how='inner', op='intersects').index_right.unique())]
Esempio n. 2
0
def Adaptive_Choropleth_Mapper_viz(param):

    # convert year, variable to years, variables in the param
    if ('years' not in param and 'year' in param):
        param['years'] = [param['year']]
    if ('variables' not in param and 'variable' in param):
        param['variables'] = [param['variable']]
    #print(param)

    # select community by state_fips, msa_fips, county_fips
    community = None
    if ('msa_fips' in param and param['msa_fips']):
        community = Community.from_ltdb(years=param['years'],
                                        msa_fips=param['msa_fips'])
        #community = Community.from_ltdb(msa_fips=param['msa_fips'])
    elif ('county_fips' in param and param['county_fips']):
        community = Community.from_ltdb(years=param['years'],
                                        county_fips=param['county_fips'])
    elif ('state_fips' in param and param['state_fips']):
        community = Community.from_ltdb(years=param['years'],
                                        state_fips=param['state_fips'])
    #print(community.gdf)

# if the user enters CSV and shapefile, use the files from the user

#### This is executed when the user enter attributes in csv file and geometroy in shapefile ######################
    if (community is None and 'inputCSV' in param):
        community = Community()
        #community.gdf = pd.read_csv(param['inputCSV'], dtype={'geoid':str})
        community.gdf = param["inputCSV"]
        #print(community.gdf)
        geoid = community.gdf.columns[0]
        #community.gdf = community.gdf.astype(str)
        #print("inputCSV:  " + community.gdf.geoid)
        community.gdf[community.gdf.columns[0]] = community.gdf[geoid].astype(
            str)
        #print("community.gdf.columns[0]:", community.gdf.columns[0])

        # read shape file to df_shape
        #df_shape = gpd.read_file(param['shapefile'])
        df_shape = param['shapefile']
        df_shape = df_shape.astype(str)
        #print("shapefile:  " + df_shape.GEOID10)
        geokey = df_shape.columns[0]
        #print(geokey)
        df_shape = df_shape.set_index(geokey)

        # insert geometry to community.gdf
        geometry = []
        for index, row in community.gdf.iterrows():
            tractid = row[geoid]
            try:
                tract = df_shape.loc[tractid]
                geometry.append(shapely.wkt.loads(tract.geometry))
            except KeyError:
                #print("Tract ID [{}] is not found in the shape file {}".format(tractid, param['shapefile']))
                geometry.append(None)
    # print( "geometry" in community.gdf )
    #f hasattr(community.gdf, "geoemtry"):
    #if (community.gdf["geoemtry"] is None):
    #   pass
    #else:
        if (("geometry" in community.gdf) == False):
            community.gdf.insert(len(community.gdf.columns), "geometry",
                                 geometry)


################################################################################################################

    community.gdf = community.gdf.replace([np.inf, -np.inf], np.nan)
    # check if geometry is not null for Spatial Clustering
    community.gdf = community.gdf[pd.notnull(community.gdf['geometry'])]
    #print(community.gdf)

    codebook = pd.read_csv('template/conversion_table_codebook.csv')
    codebook.set_index(keys='variable', inplace=True)
    labels = copy.deepcopy(param['variables'])
    label = 'short_name'  # default
    if (param['label'] == 'variable'): label = 'variable'
    if (param['label'] == 'full_name'): label = 'full_name'
    if (param['label'] == 'short_name'): label = 'short_name'
    if (label != 'variable'):
        for idx, variable in enumerate(param['variables']):
            try:
                codeRec = codebook.loc[variable]
                labels[idx] = codeRec[label]
            except:
                print("variable not found in codebook.  variable:", variable)
    param['labels'] = labels

    write_INDEX_html(param)
    write_CONFIG_js(param)
    write_VARIABLES_js(community, param)
    write_GEO_JSON_js(community, param)
    '''
    #Create directory for local machine
    local_dir = os.path.dirname(os.path.realpath(__file__))
    fname =urllib.parse.quote('index.html')
    template_dir = os.path.join(local_dir, 'ACM_' + param['filename_suffix'])
    url = 'file:' + os.path.join(template_dir, fname)
    webbrowser.open(url)
    
    print('Please run ' + '"ACM_' + param['filename_suffix']+'/index.html"'+' to your web browser.')
    print('Advanced options are available in ' + '"ACM_' + param['filename_suffix']+'/data/CONFIG.js"')
    '''

    #Create directory for Visualization
    servers = list(notebookapp.list_running_servers())
    servers1 = 'https://cybergisx.cigi.illinois.edu' + servers[0][
        "base_url"] + 'view'
    servers2 = 'https://cybergisx.cigi.illinois.edu' + servers[0][
        "base_url"] + 'edit'
    cwd = os.getcwd()
    prefix_cwd = "/home/jovyan/work"
    cwd = cwd.replace(prefix_cwd, "")

    # This is for Jupyter notebbok installed in your PC
    local_dir1 = cwd
    local_dir2 = cwd

    #This is for CyberGISX. Uncomment two command lines below when you run in CyberGIX Environment
    #local_dir1 = servers1 + cwd
    #local_dir2 = servers2 + cwd

    #print(local_dir)
    fname = urllib.parse.quote('index.html')
    template_dir = os.path.join(local_dir1, 'ACM_' + param['filename_suffix'])
    #url = 'file:' + os.path.join(template_dir, fname)
    url = os.path.join(template_dir, fname)
    webbrowser.open(url)
    print(
        'To see your visualization, click the URL below (or locate the files):'
    )
    print(url)
    print('Advanced options are available in ')
    print(local_dir2 + '/' + 'ACM_' + param['filename_suffix'] +
          '/data/CONFIG_' + param['filename_suffix'] + '.js')
Esempio n. 3
0
    def geometry(self) -> [GeometricShape]:
        """
        Returns:
            A list of geometric objects. This are LineStrings describing paths
            between nodes and possibly additional features (e.g. way markers)
            of the paths.
        """
        display_bezier_points = True  #False     ### To come from settings...
        if self.__path_layout == 'automatic':
            log("Automated pathway layout. Path ID: ", self.__path_id)
            evaluate_settings = self.__sheath.settings()
            # TODO: use evenly-distributed offsets for the final product.
            number_of_neurons = len(evaluate_settings['derivatives'])
            # locations = [0.01 + x*(0.99-0.01)/number_of_neurons for x in range(number_of_neurons)]
            location = 0.5
            geometry = []
            for scaffold, path_id, derivative in zip(
                    evaluate_settings['scaffolds'],
                    evaluate_settings['path_ids'],
                    evaluate_settings['derivatives']):
                scaffold.generate()
                connectivity = Connectivity(path_id, scaffold, derivative,
                                            location)
                auto_beziers = connectivity.get_neuron_line_beziers()
                path = BezierPath.fromSegments(auto_beziers)
                geometry.append(
                    GeometricShape(
                        shapely.geometry.LineString(bezier_sample(path))))
            end_nodes = set(self.__source_nodes)
            end_nodes.update(self.__target_nodes)
            for node in end_nodes:
                for edge in self.__graph.edges(node, data=True):
                    if edge[2].get('type') == 'terminal':
                        line = self.__line_from_edge(edge)
                        if line is not None:
                            geometry.append(GeometricShape(line))
            if display_bezier_points:
                for beziers in self.__sheath.path_beziers.values():
                    for bezier in beziers:
                        bz_pts = tuple([p.x, p.y] for p in bezier.points)
                        for pt in [bz_pts[0], bz_pts[3]]:
                            geometry.append(
                                GeometricShape(GeometricShape.circle(pt), {
                                    'type': 'bezier',
                                    'kind': 'bezier-end'
                                }))
                        for pt in bz_pts[1:3]:
                            geometry.append(
                                GeometricShape(GeometricShape.circle(pt), {
                                    'type': 'bezier',
                                    'kind': 'bezier-control'
                                }))
                        geometry.append(
                            GeometricShape(GeometricShape.line(*bz_pts[0:2]),
                                           {'type': 'bezier'}))
                        geometry.append(
                            GeometricShape(GeometricShape.line(*bz_pts[2:4]),
                                           {'type': 'bezier'}))

            return geometry

        # Fallback is centreline layout
        geometry = []
        for edge in self.__graph.edges.data():
            nerve = edge[2].get('nerve')
            properties = {'nerve': nerve} if nerve is not None else None
            bezier = edge[2].get('geometry')
            if self.__path_layout != 'linear' and bezier is not None:
                geometry.append(
                    GeometricShape(
                        shapely.geometry.LineString(bezier_sample(bezier)),
                        properties))
            else:
                line = self.__line_from_edge(edge)
                if line is not None:
                    geometry.append(GeometricShape(line, properties))
        return geometry