Basemap Change color of neighbour countries - python-2.7

from mpl_toolkits.basemap import Basemap
fig = plt.figure(figsize=(20,10)) # predefined figure size, change to your liking.
# But doesn't matter if you save to any vector graphics format though (e.g. pdf)
ax = fig.add_axes([0.05,0.05,0.9,0.85])
# These coordinates form the bounding box of Germany
bot, top, left, right = 5.87, 15.04, 47.26, 55.06 # just to zoom in to only Germany
map = Basemap(projection='merc', resolution='l',
llcrnrlat=left,
llcrnrlon=bot,
urcrnrlat=right,
urcrnrlon=top)
map.readshapefile('./DEU_adm/DEU_adm1', 'adm_1', drawbounds=True) # plots the state boundaries, read explanation below code
map.drawcoastlines()
map.fillcontinents(color='lightgray')
long1 = np.array([ 13.404954, 11.581981, 9.993682, 8.682127, 6.960279,
6.773456, 9.182932, 12.373075, 13.737262, 11.07675 ,
7.465298, 7.011555, 12.099147, 9.73201 , 7.628279,
8.801694, 10.52677 , 8.466039, 8.239761, 10.89779 ,
8.403653, 8.532471, 7.098207, 7.216236, 9.987608,
7.626135, 11.627624, 6.852038, 10.686559, 8.047179,
8.247253, 6.083887, 7.588996, 9.953355, 10.122765])
lat1 = np.array([ 52.520007, 48.135125, 53.551085, 50.110922, 50.937531,
51.227741, 48.775846, 51.339695, 51.050409, 49.45203 ,
51.513587, 51.455643, 54.092441, 52.375892, 51.36591 ,
53.079296, 52.268874, 49.487459, 50.078218, 48.370545,
49.00689 , 52.030228, 50.73743 , 51.481845, 48.401082,
51.960665, 52.120533, 51.47512 , 53.865467, 52.279911,
49.992862, 50.775346, 50.356943, 49.791304, 54.323293])
x, y = map(long1, lat1)
map.plot(x,y,'.') # Use the dot-marker or use a different marker, but specify the `markersize`.
How can i change the color of neighbour contries of germany.
The data that is at the basis for the states is obtained from a shapefile. These can be obtained from e.g. Global Administrative Areas (the ones from this website can can be used for non-commercial purposes only)

Related

How to draw sub-structures of a polycyclic aromatic which shows bond angles correctly?

thank you for reading my question.
Assume that I have a polycyclic aromatic (let's call it "parent molecule") as shown below:
smile = "c1ccc2ocnc2c1"
mol = Chem.MolFromSmiles(smile)
When I draw sub-structures of the parent molecule, I notice that the bond angles in sub-structures are different from the bond angles in the parent molecule. Following is the code that I use:
from rdkit import Chem
from rdkit.Chem.Draw import rdMolDraw2D
from IPython.display import SVG
smile_1 = 'c(cc)cc'
smile_2 = 'n(co)c(c)c'
m1 = Chem.MolFromSmiles(smile_1,sanitize=False)
Chem.SanitizeMol(m1, sanitizeOps=(Chem.SanitizeFlags.SANITIZE_ALL^Chem.SanitizeFlags.SANITIZE_KEKULIZE^Chem.SanitizeFlags.SANITIZE_SETAROMATICITY))
m2 = Chem.MolFromSmiles(smile_2,sanitize=False)
Chem.SanitizeMol(m2, sanitizeOps=(Chem.SanitizeFlags.SANITIZE_ALL^Chem.SanitizeFlags.SANITIZE_KEKULIZE^Chem.SanitizeFlags.SANITIZE_SETAROMATICITY))
mols = [m1, m2]
smiles = ["smile_1", "smile_2"]
molsPerRow=2
subImgSize=(200, 200)
nRows = len(mols) // molsPerRow
if len(mols) % molsPerRow:
nRows += 1
fullSize = (molsPerRow * subImgSize[0], nRows * subImgSize[1])
d2d = rdMolDraw2D.MolDraw2DSVG(fullSize[0], fullSize[1], subImgSize[0], subImgSize[1])
d2d.drawOptions().prepareMolsBeforeDrawing=False
d2d.DrawMolecules(mols, legends=smiles)
d2d.FinishDrawing()
SVG(d2d.GetDrawingText())
Which results in the following drawing:
As can be seen, the angles between several bonds in sub-structures are different from the parent molecule.
Is there any way to draw sub-structures with the same bond angles as parent molecule?
Any help is greatly appreciated.
You can set the original positions of your parent to the substructure.
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
rdDepictor.SetPreferCoordGen(True)
def getNiceSub(parent, sub):
# Get the coordinates of parent (also need to built a conformer)
mol = Chem.MolFromSmiles(parent)
rdDepictor.Compute2DCoords(mol)
# Get the coordinates of substructure to built a conformer
substruct = Chem.MolFromSmiles(sub, sanitize=False)
rdDepictor.Compute2DCoords(substruct)
# Get the index of the matched atoms
ms = mol.GetSubstructMatch(substruct)
# Get the positions of the matched atoms
conf1 = mol.GetConformer()
p = [list(conf1.GetAtomPosition(x)) for x in ms]
# Set the original positions of parent to substructure
conf2 = substruct.GetConformer()
for n in range(len(ms)):
conf2.SetAtomPosition(n, p[n])
return substruct
parent = 'c1ccc2ocnc2c1'
substructer = 'n(co)c(c)c'
nicesub = getNiceSub(parent, substructer)
parent
substructure

Leaflet - Tiled map shifted

I have two maps: A tiled satellite map from OpenMapTiles, which is stored locally and displayed in the background. I'd like to display another map above that. At the moment it consists of a simple world map, which I created in Python with mpl_toolkits.basemap and then split into tiles with gdal2tiles.py (later I would like to limit the overlay map to certain regions like USA). But if I display both maps on top of each other, they do not cover the same area (see below).
Shifted map after displaying it with Leaflet
Unfortunately I don't know anything about Leaflet except the tutorials. I have been looking for a solution for over a week and don't even have a clue what it could be. I really would appreciate your help.
The Python script:
# -*- coding: utf-8 -*-
import os
import math
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import subprocess # to execute shell commands
# Import settings
from settings import *
# 1. CREATE A BASEMAP
width = 4800
height = 4800
dpi = 120
plt.figure( figsize=(width/dpi, height/dpi) )
map = Basemap( projection='merc', resolution='c',
lat_0=51., lon_0=10.,
llcrnrlat=-85.051, urcrnrlat=85.051,
llcrnrlon=-180.000, urcrnrlon=180.000
)
map.fillcontinents(color='coral')
# Save the image
plt.axis('off')
filename = os.path.join(fileSettings.oPath, fileSettings.oFile)
plt.savefig( filename, dpi=float(dpi),
transparent=True,
bbox_inches='tight', pad_inches=0
)
# Call map tile generator
dirname = os.path.join(fileSettings.oPath, "tiles")
subprocess.check_output( "rm -rf " + dirname,
stderr=subprocess.STDOUT,
shell=True,
)
tilesize = 256
minZoom = 0
#maxZoom = 4
maxZoom = int(math.ceil( np.log2(max(width, height)/tilesize) )) # math.ceil: round up
try:
subprocess.check_output( "helpers/mapTileGenerator/gdal2tiles.py --leaflet --profile=raster --zoom=" + str(minZoom) + "-" + str(maxZoom) + " " + filename + " " + dirname,
stderr=subprocess.STDOUT,
shell=True,
)
print("Ready.")
except subprocess.CalledProcessError as e:
print("Error {}: {}".format(e.returncode, e.output))
The .js file:
var map;
function initMap() {
// Define zoom settings
var minZoom = 0, // The smallest zoom level.
maxZoom = 4, // The biggest zoom level.
zoomDelta = 1, // How many zoom levels to zoom in/out when using the zoom buttons or the +/- keys on the keyboard.
zoomSnap = 0; // Fractional zoom, e.g. if you set a value of 0.25, the valid zoom levels of the map will be 0, 0.25, 0.5, 0.75, 1., and so on.
// Example for locally stored map tiles:
var openMapTilesLocation = 'openMapTiles/tiles/{z}/{x}/{y}.png'; // Location of the map tiles.
var openMapTilesAttribution = 'Map data © OpenMapTiles Satellite contributors'; // Appropriate reference to the source of the map tiles.
// Example for including our self-created map tiles:
var myMapLocation = 'tiles/map/{z}/{x}/{y}.png'; // Location of the map tiles.
var myMapAttribution = 'Map data © ... contributors'; // Appropriate reference to the source of the tiles.
// Ceate two base layers
var satellite = L.tileLayer(openMapTilesLocation, { attribution: openMapTilesAttribution }),
myMap = L.tileLayer(myMapLocation, { attribution: myMapAttribution });
// Add the default layers to the map
map = L.map('map', { minZoom: minZoom,
maxZoom: maxZoom,
zoomDelta: zoomDelta, zoomSnap: zoomSnap,
crs: L.CRS.EPSG3857,
layers: [satellite, myMap], // Layers that are displayed at startup.
}
);
// Set the start position and zoom level
var startPosition = new L.LatLng(51., 10.); // The geographical centre of the map (latitude and longitude of the point).
map.setView(startPosition, maxZoom);
// Next, we’ll create two objects. One will contain our base layers and one will contain our overlays. These are just simple objects with key/value pairs. The key sets the text for the layer in the control (e.g. “Satellite”), while the corresponding value is a reference to the layer (e.g. satellite).
var baseMaps = {
"Satellite": satellite,
};
var overlayMaps = {
"MyMap": myMap,
};
// Now, all that’s left to do is to create a Layers Control and add it to the map. The first argument passed when creating the layers control is the base layers object. The second argument is the overlays object.
L.control.layers(baseMaps, overlayMaps).addTo(map);
}

How can I add markers on a bar graph in python?

I have made a horizontal bar graph, now I need to add markers on the bars. How can I do so?
The code I have so far is shown below:
def plot_comparison():
lengths = [11380, 44547, 166616, 184373, 193068, 258004, 369582, 462795, 503099, 581158, 660724, 671812, 918449]
y_pos = np.arange(len(length))
error = np.random.rand(len(length))
plt.barh(y_pos, length, xerr=error, align='center', alpha=0.4)
plt.yticks(y_pos, length)
plt.xlabel('Lengths')
plt.title('Comparison of different cuts')
plt.show()
You can simply add a plot command, plotting the y_pos against the lengths. Make sure to specify a maker and set linestyle to "" (or "none") otherwise the markers will be connected by straight lines.
The following code may be what you're after.
import matplotlib.pyplot as plt
import numpy as np
lengths = [11380, 44547, 166616, 184373, 193068, 258004, 369582, 462795, 503099, 581158, 660724, 671812, 918449]
y_pos = np.arange(len(lengths))
error = np.array(lengths)*0.08
plt.barh(y_pos, lengths, xerr=error, align='center', alpha=0.4)
plt.plot(lengths, y_pos, marker="D", linestyle="", alpha=0.8, color="r")
plt.yticks(y_pos, lengths)
plt.xlabel('Lengths')
plt.title('Comparison of different cuts')
plt.show()

How to obtain the contour plot data for each scatter points?

I have plotted a contour plot as background which represent the altitude of the area.
And 100 scatter points were set represent the real pollutant emission source. Is there a method to obtain the altitude of each point?
This is my code:
%matplotlib inline
fig=plt.figure(figsize=(16,16))
ax=plt.subplot()
xi,yi = np.linspace(195.2260,391.2260,50),
np.linspace(4108.9341,4304.9341,50)
height=np.array(list(csv.reader(open("/Users/HYF/Documents/SJZ_vis/Concentration/work/terr_grd.csv","rb"),delimiter=','))).astype('float')
cmap = cm.get_cmap(name='terrain', lut=None)
terrf = plt.contourf(xi, yi, height,100, cmap=cmap)
terr = plt.contour(xi, yi, height, 100,
colors='k',alpha=0.5
)
plt.clabel(terr, fontsize=7, inline=20)
ax.autoscale(False)
point= plt.scatter(dat_so2["xp"], dat_so2["yp"], marker='o',c="grey",s=40)
ax.autoscale(False)
for i in range(0,len(dat_so2["xp"]),1):
plt.text(dat_so2["xp"][i], dat_so2["yp"][i],
str(i),color="White",fontsize=16)
ax.set_xlim(225,275)
ax.set_ylim(4200,4260)
plt.show()
You can do this with scipy.interpolate.interp2d
For example, you could add to your code:
from scipy import interpolate
hfunc = interpolate.interp2d(xi,yi,height)
pointheights = np.zeros(dat_so2["xp"].shape)
for i,(x,y) in enumerate(zip(dat_so2["xp"],dat_so2["yp"])):
pointheights[i]=hfunc(x,y)
Putting this together with the rest of your script, and some sample data, gives this (I've simplified a couple of things here, but you get the idea):
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from scipy import interpolate
fig=plt.figure(figsize=(8,8))
ax=plt.subplot()
#xi,yi = np.linspace(195.2260,391.2260,50),np.linspace(4108.9341,4304.9341,50)
xi,yi = np.linspace(225,275,50),np.linspace(4200,4260,50)
# A made up function of height (in place of your data)
XI,YI = np.meshgrid(xi,yi)
height = (XI-230.)**2 + (YI-4220.)**2
#height=np.array(list(csv.reader(open("/Users/HYF/Documents/SJZ_vis/Concentration/work/terr_grd.csv","rb"),delimiter=','))).astype('float')
cmap = cm.get_cmap(name='terrain', lut=None)
terrf = plt.contourf(xi, yi, height,10, cmap=cmap)
terr = plt.contour(xi, yi, height, 10,
colors='k',alpha=0.5
)
plt.clabel(terr, fontsize=7, inline=20)
ax.autoscale(False)
# Some made up sample points
dat_so2 = np.array([(230,4210),(240,4220),(250,4230),(260,4240),(270,4250)],dtype=[("xp","f4"),("yp","f4")])
point= plt.scatter(dat_so2["xp"], dat_so2["yp"], marker='o',c="grey",s=40)
# The interpolation function
hfunc = interpolate.interp2d(xi,yi,height)
# Now, for each point, lets interpolate the height
pointheights = np.zeros(dat_so2["xp"].shape)
for i,(x,y) in enumerate(zip(dat_so2["xp"],dat_so2["yp"])):
pointheights[i]=hfunc(x,y)
print pointheights
ax.autoscale(False)
for i in range(0,len(dat_so2["xp"]),1):
plt.text(dat_so2["xp"][i], dat_so2["yp"][i],
str(i),color="White",fontsize=16)
# We can also add a height label to the plot
plt.text(dat_so2["xp"][i], dat_so2["yp"][i],
"{:4.1f}".format(pointheights[i]),color="black",fontsize=16,ha='right',va='top')
ax.set_xlim(225,275)
ax.set_ylim(4200,4260)
plt.show()

Find vtkImageData origin and size

I have an app with 3 viewports (3 vtkRenderers). Over everyone of them I have a vtkImageReslice. These vtkImageReslice can be zoomed, shifted, rotated, etc.
I get a task to draw a line (vtkLine or something) over every vtkImageReslice ... how can I know the origin and size of vtkImageReslice on every vtkRenderer ?
Knowing the origin and size of vtkRenderer is pretty simple:
int* pOrigin = m_pRenderer->GetOrigin();
int* pSize = m_pRenderer->GetSize();
TRACE("Origin: %d.%d, Size: %d.%d\n", pOrigin[0], pOrigin[1], pSize[0], pSize[1]);
On m_pRenderer I have a m_pReslice (vtkImageReslice) ... how can I know the origin and the size of m_pReslice to draw a line over it ?
I appreciate every hint, advice, anything ...
[Later edit]
I think I am not described well the matter, so I post here a picture:
the only thing that I have to know is the origin and the size of image data from an specific renderer ... that picture, could be shifted, rotated, zoomed, etc.
[Even later edit]
I attach another picture that illustrate what I am trying to do:
When I made a zoom to vtiImageActor, the horizontal green line must become wider:
You may think about widgets. There a lot of them VTK Widgets
e.g. the ImagePlaneWidget pipeline
vtkImagePlaneWidget myWidget = vtkImagePlaneWidget.New();
myWidget.SetInput(myDicomImageReader.GetOutput());
myWidget.SetPlaneOrientationToYAxes();
myWidget.SetSliceIndex(mySliceIndexNumber);
myWidget.SetInteractor(myInteractor);
myWidget.GetPlaneProperty().SetColor(1.0,0.0,0.0);
vtkOutlineFilter outlineFilter = vtkOutlineFilter.New();
outlineFilter.SetInputConnection(myDicomImageReader.GetOutputPort());
vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
mapper.SetInputConnection(outlineFilter.GetOutputPort();
vtkActor actor = vtkActor.New();
actor.SetMapper(mapper);
myImageViewer.GetRenderer().AddActor(actor);
RenderWindow.Render();
myWidget.On();
Well in my degree thesis I did a medical application to slice images and many other things, among were slicing and painting a line on vtk image actor.
I did it in python, I will put a piece of code here, maybe it will helpfull for you. This piece of code does slice and paint a line over this slice, of course, there are many class attributes, but I hope with this code you understand the essence.
self.renderXZ = vtk.vtkRenderer()
self.renderXZ.SetBackground(0,0,0)
self.interactorStyleXZ = vtk.vtkInteractorStyleImage()
self.xz.GetRenderWindow().AddRenderer(self.renderXZ)
self.xz.SetInteractorStyle(self.interactorStyleXZ)
#creating image actor
self.imageActorXZ = vtk.vtkImageActor()
self.imageActorXZ.SetDisplayExtent(self.imageXZ.GetWholeExtent())
#getting the dimensions
xMin, xMax, yMin, yMax, zMin, zMax = self.image.GetWholeExtent()
#changing slice
self.changeSliceXZ(yMax/2)
slice = self.imageActorXZ.GetSliceNumber()
max = self.imageActorXZ.GetWholeZMax()
self.renderXZ.AddActor(self.imageActorXZ)
self.xz.GetRenderWindow().SetSize(522,243)
XZ_XSize,XZ_YSize = self.renderXZ.GetSize()
#drawing a Line
rectMapper = self.drawLine(0, XZ_YSize/2, XZ_XSize, XZ_YSize/2)
self.HorizontalLineActorXZ = vtk.vtkActor2D()
self.HorizontalLineActorXZ.SetMapper(rectMapper)
self.renderXZ.AddActor2D(self.HorizontalLineActorXZ)
#and the changeSliceXZ function is this
def changeSliceXZ(self,sliceNumber):
slicer = vtkImageSlicer()
slicer.SetInput(self.image)
#putting the direction of the slice
slicer.SetSliceDirection(1)
slicer.SetSlice(sliceNumber)
slicer.Update()
self.imageXZ = slicer.GetOutput()
self.imageActorXZ.SetInput(self.imageXZ)
self.xz.GetRenderWindow().Render()
self.YSlice = sliceNumber
self.SliceNumber[1] = sliceNumber