Apache Solr heatmap : How to convert in usable coordinate int2d array returned by heatmap - reactjs

I'm using faceting heatmap on a spatial field which then returns a 2d array like this
"counts_ints2D",
[
null,
null,
null,
null,
[
0,
8,
4,
0,
0,
0,
0,
0,
0,
...
I want to locate those cluster on the map but the problem is that I don't know how to convert that 2d array in geo coordinates.
There's absolutely no documentation out there showing what to do with those integer.
Can somebody give some guidance ?

Going with the data you gave for Glasgow, and using the formula given in the comments, lets explore the coordinates in a python repl:
# setup
>>> minX = -180
>>> maxX = 180
>>> minY = -53.4375
>>> maxY = 74.53125
>>> columns = 256
>>> rows = 91
# calculate widths
>>> bucket_width = (maxX - minX) / columns
>>> bucket_width
1.40625
>>> bucket_height = (maxY - minY) / rows
>>> bucket_height
1.40625
# calculate area for bucket in heatmap facet for x = 124, y = 13
# point in lower left coordinate
>>> lower_left = {
... 'lat': maxY - (13 + 1) * bucket_height,
... 'lon': minX + 124 * bucket_width,
... }
>>> lower_left
{'lat': 54.84375, 'lon': -5.625}
# point in upper right
>>> upper_right = {
... 'lat': maxY - (13 + 1) * bucket_height + bucket_height,
... 'lon': minX + 124 * bucket_width + bucket_width,
... }
>>> upper_right
{'lat': 56.25, 'lon': -4.21875}
Let's graph these points on a map, courtesy of open street map. We generate a small CSV snippet we can import on umap (select the up arrow, choose 'csv' as the type and enter content into the text box). To our coordinates to show:
>>> bbox = [
... "lat,lon,description",
... str(lower_left['lat']) + "," + str(lower_left['lon']) + ",ll",
... str(upper_right['lat']) + "," + str(lower_left['lon']) + ",ul",
... str(upper_right['lat']) + "," + str(upper_right['lon']) + ",uu",
... str(lower_left['lat']) + "," + str(upper_right['lon']) + ",lu",
... ]
>>> print("\n".join(bbox))
lat,lon,description
54.84375,-5.625,ll
56.25,-5.625,ul
56.25,-4.21875,uu
54.84375,-4.21875,lu
After pasting these points into the import box creating the layer, we get this map:
Map based on Open Street Map data through uMap. This area encloses Glasgow as you expected.

Here's some code that takes 180th meridian (date line) wrapping into account:
$columns = $heatmap['columns'];
$rows = $heatmap['rows'];
$minX = $heatmap['minX'];
$maxX = $heatmap['maxX'];
$minY = $heatmap['minY'];
$maxY = $heatmap['maxY'];
$counts = $heatmap['counts_ints2D'];
// If our min longitude is greater than max longitude, we're crossing
// the 180th meridian (date line).
$crosses_meridian = $minX > $maxX;
// Bucket width needs to be calculated differently when crossing the
// meridian since it wraps.
$bucket_width = $crosses_meridian
? $bucket_width = (360 - abs($maxX - $minX)) / $columns
: $bucket_width = ($maxX - $minX) / $columns;
$bucket_height = ($maxY - $minY) / $rows;
$points = [];
foreach ($counts as $rowIndex => $row) {
if (!$row) continue;
foreach ($row as $columnIndex => $column) {
if (!$column) continue;
$point = []
$point['count'] = $column;
// Put the count in the middle of the bucket (adding a half height and width).
$point['lat'] = $maxY - (($rowIndex + 1) * $bucket_height) + ($bucket_height / 2);
$point['lng'] = $minX + ($columnIndex * $bucket_width) + ($bucket_width / 2);
// We crossed the meridian, so wrap back around to negative.
if ($point['lng'] > 180) {
$point['lng'] = -1 * (180 - ($point['lng'] % 180));
}
$points[] = $point;
}
}

Related

Make strategy with arrays in Pine

I'm trying to make a strategy of an indicator, but I get the error: Line 73: Cannot call 'operator >' with argument 'expr0'='call 'alertcondition' (void)'. An argument of 'void' type was used but a 'const float' is expected. How can I change the code to get a correct boolean if statement for the trade entry? I'm very new to pine, hopefully someone can help me.
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//#version=5
// Umgeschrieben von JSt
strategy("Watson Strategie Nadaraya-Watson Envelope [JSt]",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
length = input.float(500,'Window Size',maxval=500,minval=0)
h = input.float(8.,'Bandwidth')
mult = input.float(3.)
src = input.source(close,'Source')
up_col = input.color(#39ff14,'Colors',inline='col')
dn_col = input.color(#ff1100,'',inline='col')
//----
n = bar_index
var k = 2
var upper = array.new_line(0)
var lower = array.new_line(0)
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_color(l,col)
line.set_width(l,2)
if barstate.isfirst
for i = 0 to length/k-1
array.push(upper,line.new(na,na,na,na))
array.push(lower,line.new(na,na,na,na))
//----
line up = na
line dn = na
//----
cross_up = 0.
cross_dn = 0.
if barstate.islast
y = array.new_float(0)
sum_e = 0.
for i = 0 to length-1
sum = 0.
sumw = 0.
for j = 0 to length-1
w = math.exp(-(math.pow(i-j,2)/(h*h*2)))
sum += src[j]*w
sumw += w
y2 = sum/sumw
sum_e += math.abs(src[i] - y2)
array.push(y,y2)
mae = sum_e/length*mult
for i = 1 to length-1
y2 = array.get(y,i)
y1 = array.get(y,i-1)
up := array.get(upper,i/k)
dn := array.get(lower,i/k)
lset(up,n-i+1,y1 + mae,n-i,y2 + mae,up_col)
lset(dn,n-i+1,y1 - mae,n-i,y2 - mae,dn_col)
if src[i] > y1 + mae and src[i+1] < y1 + mae
label.new(n-i,src[i],'▼',color=#00000000,style=label.style_label_down,textcolor=dn_col,textalign=text.align_center)
if src[i] < y1 - mae and src[i+1] > y1 - mae
label.new(n-i,src[i],'▲',color=#00000000,style=label.style_label_up,textcolor=up_col,textalign=text.align_center)
cross_up := array.get(y,0) + mae
cross_dn := array.get(y,0) - mae
// TestUP = ta.crossover(src,cross_up) > 0
alertcondition(ta.crossover(src,cross_up),'Down','Down')
alertcondition(ta.crossunder(src,cross_dn),'Up','Up')
//---- Alarm für Webhook -----
plot(cross_up, color=#000000, transp=100) //Für den Alert, jedoch Darstellungsfehler → Transparent
plot(cross_dn, color=#000000, transp=100)
plotchar(cross_up, title="cross_up%", char="", location=location.top, color = color.green) // Damit der Wert in der Statusleiste dargestellt wird
plotchar(cross_dn, title="cross_dn%", char="", location=location.top, color = color.red)
//-------------------
// Start Date
// STEP 1. Create inputs that configure the backtest's date range
useDateFilter = input.bool(true, title="Begin Backtest at Start Date",
group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 Jan 2021"),
title="Start Date", group="Backtest Time Period",
tooltip="This start date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
// STEP 2. See if current bar happens on, or later than, the start date
inTradeWindow = not useDateFilter or time >= backtestStartDate
// ---------------
// Enter a long position when the entry rule is triggered
if inTradeWindow and ta.crossover(src,cross_up) > 0
strategy.entry('Long', strategy.long)
// Exit the Long position when the exit rule is triggered
if close > strategy.position_avg_price + 50
strategy.close("Long", comment = "TP")
else if close < strategy.position_avg_price - 50
strategy.close("Long", comment = "SL")
I tried the ta.crossover(src,cross_up) to compare it to zero, but it doesn't work.
ta.crossover() returns a bool value.
ta.crossover(source1, source2) → series bool
So, comparing its return value with some number does not make any sense and the compiler will complain: ta.crossover(src,cross_up) > 0.
You should just do:
if inTradeWindow and ta.crossover(src,cross_up)
strategy.entry('Long', strategy.long)

Map Layer Issues in ggplot2

I'm having a few issues with finalizing my map for a report. I think I'm warm on the solutions, but haven't quite figured them out. I would really appreciate any help on solutions so that I can finally move on!
1) The scale bar will NOT populate in the MainMap code and the subsequent Figure1 plot. This is "remedied" in the MainMap code if I comment out the "BCWA_land" map layer. However, when I retain the "BCWA_land" map layer it will eliminate the scale bar and produces this error:
Warning message: Removed 3 rows containing missing values (geom_text).
And this is the code:
MainMap <- ggplot(QOI) +
geom_sf(aes(fill = quadID)) +
scale_fill_manual(values = c("#6b8c42",
"#70b2ae",
"#d65a31")) +
labs(fill = "Quadrants of Interest",
caption = "Figure 1: Map depicting the quadrants in the WSDOT project area as well as other quadrants of interest in the Puget Sound area.")+
ggtitle("WSDOT Project Area and Quadrants of Interest") +
scalebar(x.min = -123, x.max = -122.8, y.min = 47, y.max = 47.1, location = "bottomleft",
transform = TRUE, dist = 10, dist_unit = "km", st.size = 3, st.bottom = TRUE, st.dist = 0.1) +
north(data = QOI, location = "topleft", scale = 0.1, symbol = 12, x.min = -123, y.min = 48.3, x.max = -122.7, y.max = 48.4) +
theme_bw()+
theme(panel.grid= element_line(color = "gray50"),
panel.background = element_blank(),
panel.ontop = TRUE,
legend.text = element_text(size = 11, margin = margin(l = 3), hjust = 0),
legend.position = c(0.95, 0.1),
legend.justification = c(0.85, 0.1),
legend.background = element_rect(colour = "#3c4245", fill = "#f4f4f3"),
axis.title = element_blank(),
plot.title = element_text(face = "bold", colour = "#3c4245", hjust = 0.5, margin = margin(b=10, unit = "pt")),
plot.caption = element_text(face = "italic", colour = "#3c4245", margin = margin(t = 7), hjust = 0, vjust = 0.5)) +
geom_sf(data = BCWA_land) + #this is what I've tried to comment out to determine the scale bar problem
xlim (-123.1, -121.4) +
ylim (47.0, 48.45)
MainMap
InsetRect <- data.frame(xmin=-123.2, xmax=-122.1, ymin=47.02, ymax=48.45)
InsetMap <- ggplotGrob( ggplot( quads) +
geom_sf(aes(fill = "")) +
scale_fill_manual(values = c("#eefbfb"))+
geom_sf(data = BCWA_land) +
scale_x_continuous(expand = c(0,0), limits = c(-124.5, -122.0)) +
scale_y_continuous(expand = c(0,0), limits = c(47.0, 49.5)) +
geom_rect(data = InsetRect,aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax),
color="#3c4245",
size=1.25,
fill=NA,
inherit.aes = FALSE) +
theme_bw()+
theme(legend.position = "none",
panel.grid = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.margin = margin(0,0,0,0)))
InsetMap
Figure1 <- MainMap +
annotation_custom(grob = InsetMap, xmin = -122.2, xmax = -121.3,
ymin = 47.75, ymax = 48.5)
Figure1
As you can see I'm not getting this issue or error for my north arrow so I'm not really sure what is happening with the scale bar!
This problem is probably a little too OCD, however I REALLY don't want the gridlines to show up on the InsetMap, and was hoping that the InsetMap would overlay on top of the MainMap, without gridlines as I had those parameters set to element_blank() in the InsetMap code.
Here is an image of my plot. If you would like the data for this, please let me know. Because these are shapefiles, the data is unwieldy and not super conducive to SO's character limit for a post...
If anyone has any insight into a solution(s) I would so so appreciate that!! Thanks for your time!
The issue was the
xlim (-123.1, -121.4) +
ylim (47.0, 48.45)
call that I made. Instead, I used coord_sf(xlim = c(min, max), ylim = c(min, max)). I thought that this would be helpful to someone who might be in my position later on!
Essentially the difference between setting the limits of to the graph using just the x/y lim calls is that that truncates the data that is available in your dataset, whereas the coord_sf call simply "focuses" your graph on that extent if you will without altering the data you have available in your dataset.

Convert pinescript v2 to v4

I found 2 scripts in tradingview and added them to my script, however, it didn't work. I lost a lot of time. Can someone help me convert them to version 4? Thank you. Have a nice day!!!
//#version=2
////////////////////////////////////////////////////////////
// Copyright by HPotter v1.0 09/03/2018
// Linear Regression Intercept is one of the indicators calculated by using the
// Linear Regression technique. Linear regression indicates the value of the Y
// (generally the price) when the value of X (the time series) is 0. Linear
// Regression Intercept is used along with the Linear Regression Slope to create
// the Linear Regression Line. The Linear Regression Intercept along with the Slope
// creates the Regression line.
////////////////////////////////////////////////////////////
study(title="Line Regression Intercept", overlay = true)
Length = input(14, minval=1)
xSeria = input(title="Source", type=source, defval=close)
xX = Length * (Length - 1) * 0.5
xDivisor = xX * xX - Length * Length * (Length - 1) * (2 * Length - 1) / 6
xXY = 0
for i = 0 to Length-1
xXY := xXY + (i * xSeria[i])
xSlope = (Length * xXY - xX * sum(xSeria, Length)) / xDivisor
xLRI = (sum(xSeria, Length) - xSlope * xX) / Length
plot(xLRI, color=blue, title="LRI")
//Author - Rajandran R
//www.marketcalls.in
study("Supertrend V1.0 - Buy or Sell Signal", overlay = true)
Factor=input(3, minval=1,maxval = 100)
Pd=input(7, minval=1,maxval = 100)
Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
TrendUp=close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown=close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend = close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl = Trend==1? TrendUp: TrendDown
linecolor = Trend == 1 ? green : red
plot(Tsl, color = linecolor , style = line , linewidth = 2,title = "SuperTrend")
plotshape(cross(close,Tsl) and close>Tsl , "Up Arrow", shape.triangleup,location.belowbar,green,0,0)
plotshape(cross(Tsl,close) and close<Tsl , "Down Arrow", shape.triangledown , location.abovebar, red,0,0)
//plot(Trend==1 and Trend[1]==-1,color = linecolor, style = circles, linewidth = 3,title="Trend")
plotarrow(Trend == 1 and Trend[1] == -1 ? Trend : na, title="Up Entry Arrow", colorup=lime, maxheight=60, minheight=50, transp=0)
plotarrow(Trend == -1 and Trend[1] == 1 ? Trend : na, title="Down Entry Arrow", colordown=red, maxheight=60, minheight=50, transp=0)
//#version=4
////////////////////////////////////////////////////////////
// Copyright by HPotter v1.0 09/03/2018
// Linear Regression Intercept is one of the indicators calculated by using the
// Linear Regression technique. Linear regression indicates the value of the Y
// (generally the price) when the value of X (the time series) is 0. Linear
// Regression Intercept is used along with the Linear Regression Slope to create
// the Linear Regression Line. The Linear Regression Intercept along with the Slope
// creates the Regression line.
////////////////////////////////////////////////////////////
study(title="Line Regression Intercept", overlay=true)
Length = input(14, minval=1)
xSeria = input(title="Source", type=input.source, defval=close)
xX = Length * (Length - 1) * 0.5
xDivisor = xX * xX - Length * Length * (Length - 1) * (2 * Length - 1) / 6
xXY = 0.
for i = 0 to Length - 1 by 1
xXY := xXY + i * xSeria[i]
xXY
xSlope = (Length * xXY - xX * sum(xSeria, Length)) / xDivisor
xLRI = (sum(xSeria, Length) - xSlope * xX) / Length
plot(xLRI, color=color.blue, title="LRI")
//#version=4
//Author - Rajandran R
//www.marketcalls.in
study("Supertrend V1.0 - Buy or Sell Signal", overlay=true)
Factor = input(3, minval=1, maxval=100)
Pd = input(7, minval=1, maxval=100)
Up = hl2 - Factor * atr(Pd)
Dn = hl2 + Factor * atr(Pd)
TrendUp = Up
TrendUp := close[1] > TrendUp[1] ? max(Up, TrendUp[1]) : Up
TrendDown = Dn
TrendDown := close[1] < TrendDown[1] ? min(Dn, TrendDown[1]) : Dn
Trend = int(na)
Trend := close > TrendDown[1] ? 1 : close < TrendUp[1] ? -1 : nz(Trend[1], 1)
Tsl = Trend == 1 ? TrendUp : TrendDown
linecolor = Trend == 1 ? color.green : color.red
plot(Tsl, color=linecolor, style=plot.style_line, linewidth=2, title="SuperTrend")
plotshape(cross(close, Tsl) and close > Tsl, "Up Arrow", shape.triangleup, location.belowbar, color.green, 0, 0)
plotshape(cross(Tsl, close) and close < Tsl, "Down Arrow", shape.triangledown, location.abovebar, color.red, 0, 0)
//plot(Trend==1 and Trend[1]==-1,color = linecolor, style = circles, linewidth = 3,title="Trend")
plotarrow(Trend == 1 and Trend[1] == -1 ? Trend : na, title="Up Entry Arrow", colorup=color.lime, maxheight=60, minheight=50, transp=0)
plotarrow(Trend == -1 and Trend[1] == 1 ? Trend : na, title="Down Entry Arrow", colordown=color.red, maxheight=60, minheight=50, transp=0)

Intercept values of two lines plotted with an array

I am trying to get the values intercept of two lines, t70_bot_inf and t70_top_0, and would like to mark it with a horizontal and vertical line. Are there any modules with could help me with this? I have tried Shapley which was unfortunately unsuccessful. Cheers!
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#global values
sigma_ct_inf = 0
sigma_ct_0 = 0
sigma_c_inf = 30
sigma_c_0 = 12
beta = 0.8
#values T 70
A = 359000
Wb = 40830202.33
Wt = 72079066.94
Mmin = 701.17
Mmax = 978.52
#Magnel Diagram
e = np.arange(-200, 1001)
t70_top_0 = pd.Series({'y': ((e - (Wt / A)) / ((Mmin * 10 ** 6) + sigma_ct_0 * Wt)) * 10 ** 6})
t70_bot_0 = pd.Series({'y': ((e + (Wb / A)) / ((Mmin * 10 ** 6) + sigma_c_0 * Wb)) * 10 ** 6})
t70_top_inf = pd.Series({'y': (((e - (Wt / A)) * beta) / ((Mmax * 10 ** 6) - sigma_c_inf * Wt)) * 10 ** 6})
t70_bot_inf = pd.Series({'y': (((e + (Wb / A)) * beta) / ((Mmax * 10 ** 6) - sigma_ct_inf * Wb)) * 10 ** 6})
bot = np.min([t70_bot_0['y'], t70_bot_inf['y']], axis=0)
top = np.max([t70_top_0['y'], t70_top_inf['y']], axis=0)
fig, ax = plt.subplots()
ax.set_title('Magnel Diagram, T-70')
ax.plot(e, t70_top_0['y'], lw=0.5, label='Top, t = 0')
ax.plot(e, t70_bot_0['y'], lw=0.5, label='Bottom, t = 0')
ax.plot(e, t70_top_inf['y'], lw=0.5, label='Top, t = \u221E')
ax.plot(e, t70_bot_inf['y'], lw=0.5, label='Bottom, t = \u221E')
ax.fill_between(e, bot, top, where=top < bot, color='r', alpha=0.4)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.ylabel('1/P0 [1/MN]')
plt.xlabel('Eccentricity [mm]')
ax.grid()
plt.legend()
plt.show()

Matlab : How to highlight GLYCINE residues in my Ramachandran plot? [duplicate]

This question already has an answer here:
MATLAB : What is the mistake in my Ramachandran plot?
(1 answer)
Closed 8 years ago.
I am trying matlab to plot ramachandran plot, without using built in command. I have succeeded too. Now I wanted to spot the GLYCINEs alone in the scatter array. Any ideas how to do this? (link to 1UBQ.pdb file : http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId=1UBQ)
% Program to plot Ramanchandran plot of Ubiquitin
close all; clear ; clc; % close all figure windows, clear variables, clear screen
pdb1 ='/home/devanandt/Documents/VMD/1UBQ.pdb';
p=pdbread(pdb1); % read pdb file corresponding to ubiquitin protein
atom={p.Model.Atom.AtomName};
n_i=find(strcmp(atom,'N')); % Find indices of atoms
ca_i=find(strcmp(atom,'CA'));
c_i=find(strcmp(atom,'C'));
X = [p.Model.Atom.X];
Y = [p.Model.Atom.Y];
Z = [p.Model.Atom.Z];
X_n = X(n_i(2:end)); % X Y Z coordinates of atoms
Y_n = Y(n_i(2:end));
Z_n = Z(n_i(2:end));
X_ca = X(ca_i(2:end));
Y_ca = Y(ca_i(2:end));
Z_ca = Z(ca_i(2:end));
X_c = X(c_i(2:end));
Y_c = Y(c_i(2:end));
Z_c = Z(c_i(2:end));
X_c_ = X(c_i(1:end-1)); % the n-1 th C (C of cabonyl)
Y_c_ = Y(c_i(1:end-1));
Z_c_ = Z(c_i(1:end-1));
V_c_ = [X_c_' Y_c_' Z_c_'];
V_n = [X_n' Y_n' Z_n'];
V_ca = [X_ca' Y_ca' Z_ca'];
V_c = [X_c' Y_c' Z_c'];
V_ab = V_n - V_c_;
V_bc = V_ca - V_n;
V_cd = V_c - V_ca;
phi=0;
for k=1:numel(X_c)
n1=cross(V_ab(k,:),V_bc(k,:))/norm(cross(V_ab(k,:),V_bc(k,:)));
n2=cross(V_bc(k,:),V_cd(k,:))/norm(cross(V_bc(k,:),V_cd(k,:)));
x=dot(n1,n2);
m1=cross(n1,(V_bc(k,:)/norm(V_bc(k,:))));
y=dot(m1,n2);
phi=cat(2,phi,-atan2d(y,x));
end
phi=phi(1,2:end);
X_n_ = X(n_i(2:end)); % (n+1) nitrogens
Y_n_ = Y(n_i(2:end));
Z_n_ = Z(n_i(2:end));
X_ca = X(ca_i(1:end-1));
Y_ca = Y(ca_i(1:end-1));
Z_ca = Z(ca_i(1:end-1));
X_n = X(n_i(1:end-1));
Y_n = Y(n_i(1:end-1));
Z_n = Z(n_i(1:end-1));
X_c = X(c_i(1:end-1));
Y_c = Y(c_i(1:end-1));
Z_c = Z(c_i(1:end-1));
V_n_ = [X_n_' Y_n_' Z_n_'];
V_n = [X_n' Y_n' Z_n'];
V_ca = [X_ca' Y_ca' Z_ca'];
V_c = [X_c' Y_c' Z_c'];
V_ab = V_ca - V_n;
V_bc = V_c - V_ca;
V_cd = V_n_ - V_c;
psi=0;
for k=1:numel(X_c)
n1=cross(V_ab(k,:),V_bc(k,:))/norm(cross(V_ab(k,:),V_bc(k,:)));
n2=cross(V_bc(k,:),V_cd(k,:))/norm(cross(V_bc(k,:),V_cd(k,:)));
x=dot(n1,n2);
m1=cross(n1,(V_bc(k,:)/norm(V_bc(k,:))));
y=dot(m1,n2);
psi=cat(2,psi,-atan2d(y,x));
end
psi=psi(1,2:end);
scatter(phi,psi)
box on
axis([-180 180 -180 180])
title('Ramachandran Plot for Ubiquitn Protein','FontSize',16)
xlabel('\Phi^o','FontSize',20)
ylabel('\Psi^o','FontSize',20)
grid
The output is :
EDIT : Is my plot correct? Biopython: How to avoid particular amino acid sequences from a protein so as to plot Ramachandran plot? has an answer which has slightly different plot.
The modified code is as below :
% Program to plot Ramanchandran plot of Ubiquitin with no glycines
close all; clear ; clc; % close all figure windows, clear variables, clear screen
pdb1 ='/home/devanandt/Documents/VMD/1UBQ.pdb';
p=pdbread(pdb1); % read pdb file corresponding to ubiquitin protein
atom={p.Model.Atom.AtomName};
n_i=find(strcmp(atom,'N')); % Find indices of atoms
ca_i=find(strcmp(atom,'CA'));
c_i=find(strcmp(atom,'C'));
X = [p.Model.Atom.X];
Y = [p.Model.Atom.Y];
Z = [p.Model.Atom.Z];
X_n = X(n_i(2:end)); % X Y Z coordinates of atoms
Y_n = Y(n_i(2:end));
Z_n = Z(n_i(2:end));
X_ca = X(ca_i(2:end));
Y_ca = Y(ca_i(2:end));
Z_ca = Z(ca_i(2:end));
X_c = X(c_i(2:end));
Y_c = Y(c_i(2:end));
Z_c = Z(c_i(2:end));
X_c_ = X(c_i(1:end-1)); % the n-1 th C (C of cabonyl)
Y_c_ = Y(c_i(1:end-1));
Z_c_ = Z(c_i(1:end-1));
V_c_ = [X_c_' Y_c_' Z_c_'];
V_n = [X_n' Y_n' Z_n'];
V_ca = [X_ca' Y_ca' Z_ca'];
V_c = [X_c' Y_c' Z_c'];
V_ab = V_n - V_c_;
V_bc = V_ca - V_n;
V_cd = V_c - V_ca;
phi=0;
for k=1:numel(X_c)
n1=cross(V_ab(k,:),V_bc(k,:))/norm(cross(V_ab(k,:),V_bc(k,:)));
n2=cross(V_bc(k,:),V_cd(k,:))/norm(cross(V_bc(k,:),V_cd(k,:)));
x=dot(n1,n2);
m1=cross(n1,(V_bc(k,:)/norm(V_bc(k,:))));
y=dot(m1,n2);
phi=cat(2,phi,-atan2d(y,x));
end
phi=phi(1,2:end);
X_n_ = X(n_i(2:end)); % (n+1) nitrogens
Y_n_ = Y(n_i(2:end));
Z_n_ = Z(n_i(2:end));
X_ca = X(ca_i(1:end-1));
Y_ca = Y(ca_i(1:end-1));
Z_ca = Z(ca_i(1:end-1));
X_n = X(n_i(1:end-1));
Y_n = Y(n_i(1:end-1));
Z_n = Z(n_i(1:end-1));
X_c = X(c_i(1:end-1));
Y_c = Y(c_i(1:end-1));
Z_c = Z(c_i(1:end-1));
V_n_ = [X_n_' Y_n_' Z_n_'];
V_n = [X_n' Y_n' Z_n'];
V_ca = [X_ca' Y_ca' Z_ca'];
V_c = [X_c' Y_c' Z_c'];
V_ab = V_ca - V_n;
V_bc = V_c - V_ca;
V_cd = V_n_ - V_c;
psi=0;
for k=1:numel(X_c)
n1=cross(V_ab(k,:),V_bc(k,:))/norm(cross(V_ab(k,:),V_bc(k,:)));
n2=cross(V_bc(k,:),V_cd(k,:))/norm(cross(V_bc(k,:),V_cd(k,:)));
x=dot(n1,n2);
m1=cross(n1,(V_bc(k,:)/norm(V_bc(k,:))));
y=dot(m1,n2);
psi=cat(2,psi,-atan2d(y,x));
end
psi=psi(1,2:end);
res=strsplit(p.Sequence.ResidueNames,' ');
angle =[phi;psi];
angle(:,find(strcmp(res,'GLY'))-1)=[];
scatter(angle(1,:),angle(2,:))
box on
axis([-180 180 -180 180])
title('Ramachandran Plot for Ubiquitn Protein','FontSize',16)
xlabel('\Phi^o','FontSize',20)
ylabel('\Psi^o','FontSize',20)
grid
which gives output (with no GLY) as below :
I would change this code block to use logical indexing
res=strsplit(p.Sequence.ResidueNames,' ');
angle =[phi;psi];
angle(:,find(strcmp(res,'GLY'))-1)=[];
Instead:
residues = strsplit(p.Sequency.ResidueNames,' ');
glycine = ismember(residues,'GLY');
angle = [phi;psi];
angleNoGLY= angle(:,~glycine);
Doing it this way, if you wanted to highlight glycine (or any other residue) you can easily call it out:
angleGLY = angle(:,glycine);
plot(angleNoGLY(1,:),angleNoGLY(2,:),'ob')
line(angleGLY(1,:),angleGLY(2,:),'Marker','o','Color','r','LineStyle','none')

Resources