mayavi surf() how do I show colorbar? - python

I can not figure out how to get the colorbar to show. I don't have much experience using mayavi, so I'm not sure what steps I need to to take to be able to figure this out?
Anyone else have similar problems
My code is shown below:
from tkFileDialog import askopenfilename
from StringIO import StringIO
import numpy as np
from mayavi import mlab
#getting the data from a txt file
filename = askopenfilename()
type(filename)
fileAsStr =''
data = []
count= 0
atData=False
with open(filename,'r') as f:
for line in f:
if line.startswith("Note"):
title = line
title = title.strip("Note:")
title = title.strip()
print title
if atData and not line.startswith('Total'): #after the second one begin reading file
line = line.replace(' ','')
#data.append(line)
fileAsStr = fileAsStr + line
if line.startswith('-----'):
count = count +1
if count == 2:
atData = True
dataStrIO = StringIO(fileAsStr)
dataArray = np.loadtxt(dataStrIO, delimiter=',')
dataDim = dataArray.shape
dx = dataArray[0:dataDim[0], 3]
dy = dataArray[0:dataDim[0], 4]
dz = dataArray[0:dataDim[0], 5]
bTotal = dataArray[0:dataDim[0],9]
firstNum = dy[0]
count = 0
while firstNum == dy[count]:
count = count + 1
print 'count=' + str(count)
#arranging the arrays into an acceptable format
from itertools import islice
def solve(lis, n):
it = iter(lis)
return [list(islice(it,n)) for _ in xrange(len(lis)/n)]
dx = np.transpose(solve(dx, count))
dy = np.transpose(solve(dy, count))
dz = solve(dz, count)
bTotal = solve(bTotal, count)
bTotal = np.log10(bTotal)
#making the plot
mlab.options.backend = 'envisage'
surf = mlab.surf(dx,dy, bTotal,warp_scale=2)
mlab.axes(surf, x_axis_visibility= True, y_axis_visibility = True,
z_axis_visibility = True, xlabel='x axis (mm)', ylabel='y axis (mm)',
zlabel ='z axis (mm)', nb_labels=10)
mlab.axes.label_text_property.font_size = 5
mlab.title(title, line_width = .5, height = 1)
mlab.colorbar( title = "magnetic field (Tesla)")

I believe you are missing an mlab.show() command at the end of your script.

Related

Data from three .txt files - loop together to one, and make a plot?

I want to end up with a scatterplot that differentiates color between different values.
First i need to analyze my data. Problem is i have a FE-Model, that exports element numbers coupled with 4 nodes. These 4 nodes have 4 coordinate sets, but if 4 elements share 1 node, it will only give 1 coordinate set for these 4 nodes.
I end up with three .txt files.
.txt with element number (and data i am analyzing for the plot)
.txt with the element number and node numbers.
.txt with node coordinates.
Is it possible to make a loop that connects these datapoints?
I would like to include an example, but i have not yet made one.
I have tried something like this
from numpy import loadtxt
from fpdf import FPDF
Sek = ['Sektion_100']
I = 0
HeaderY =['nr.','LC','Element nr.','Myy','Nyy','MRd_y','URy']
HeaderX =['nr.','LC','Element nr.','Mxx','Nxx','MRd_x','URx']
#load the excel file
#header = loadtxt"Loads\Area_233.txt", unpack=False, skiprows=1)
pdf = FPDF(orientation = 'P', unit = 'mm', format = 'A4')
MaxURx =[]
MaxURy =[]
data = loadtxt("Loads/Sektion_150.txt", unpack=False, skiprows=1)
nr = data[:,1]
Mxx = data[:,2]
Nxx = -data[:,4]
Myy = data[:,3]
Nyy = -data[:,5]
topologi = loadtxt("Loads/Sektion_150_topologi.txt", unpack=False, skiprows=1)
nr1 = topologi[:,0]
node1 = topologi[:,1]
node2 = topologi[:,2]
node3 = topologi[:,3]
node4 = topologi[:,4]
knuder = loadtxt("Loads/Sektion_150_knuder.txt", unpack=False, skiprows=1)
nr2 = knuder[:,0]
x = knuder[:,1]
y = knuder[:,2]
z = knuder[:,3]
Picture of dataset
I have included a picture of my dataset here. In "Sektion_150_Knuder" NR = Node number.
I hope anyone have some pointers in the right direction to solve this problem.
I found the answer.
import xlwings as xw
import matplotlib.pyplot as plt
from math import pi
from numpy import loadtxt
import numpy as np
from fpdf import FPDF
import matplotlib as mpl
from matplotlib.ticker import ScalarFormatter
Sek = ['Sektion_100','Sektion_110','Sektion_120','Sektion_130','Sektion_140','Sektion_150']
I = 0
HeaderY =['nr.','LC','Element nr.','Myy','Nyy','MRd_y','URy']
HeaderX =['nr.','LC','Element nr.','Mxx','Nxx','MRd_x','URx']
#load the excel file
#header = loadtxt"Loads\Area_233.txt", unpack=False, skiprows=1)
pdf = FPDF(orientation = 'P', unit = 'mm', format = 'A4')
MaxURx =[]
MaxURy =[]
Elem = np.array(loadtxt("Element/Sektion_100_elements.txt", unpack=False, skiprows=1))
Node = np.array(loadtxt("Element/Sektion_100_nodes.txt", unpack=False, skiprows=1))
#Elem = np.array(loadtxt("Element/"+Sek+"_elements.txt", unpack=False, skiprows=1))
#Node = np.array(loadtxt("Element/"+Sek+"_nodes.txt", unpack=False, skiprows=1))
data = loadtxt("Loads/Sektion_100.txt", unpack=False, skiprows=1)
Mxx = data[:,2]
Nxx = -data[:,4]
Myy = data[:,3]
Nyy = -data[:,5]
R1x = []
R2x = []
MRdx = []
URx = []
R1y = []
R2y = []
MRdy = []
URy = []
min_nx = int(round(max(min(Nxx),-300),-1)-10)
max_nx = int(round(max(Nxx),-1)+10)
min_ny = int(round(min(Nyy),-1)-10)
max_ny = int(round(max(Nyy),-1)+10)
xrange = range(min_nx, max_nx+50, round((max_nx+50-min_nx)/20))
yrange = range(min_ny, max_ny+50, round((max_ny+50-min_ny)/20))
x2 =range(0,len(data),1)
wbx =xw.Book("Capacity\\Sektion_100_L.xlsm", None, True)
sht_x1 = wbx.sheets["Beregning"]
for i in xrange:
kx = sht_x1.range("N25").value = i
Q1x = sht_x1["AV24"].value
Q2x = sht_x1["BC24"].value
R1x+=[Q1x]
R2x+=[Q2x]
for i in x2:
if Myy[i] <= 0:
mrdx = np.interp(Nxx[i],xrange,R1x)
urx = Mxx[i] / mrdx
else:
mrdx = np.interp(Nxx[i],xrange,R2x)
urx = Mxx[i] / mrdx
MRdx += [round(mrdx,2)]
URx += [round(urx,2)]
TabelX=np.c_[data[:,[0,1,2,4]],MRdx,URx]
sort_tabelX = np.flipud(TabelX[TabelX[:,5].argsort()])
LimX = 25
for i in x2:
if sort_tabelX[i,5] > 1.05 :
LimX = i+2
else:
break
LimX = max(25,LimX)
TABx=np.c_[list(range(1,LimX+1)),sort_tabelX[0:LimX,:]]
TABx2 = np.unique(TABx[:,2])
print(TABx2)
print(len(TABx2))
#OUE=np.array(TABx2)
#np.savetxt("array1.txt", TABx2)
# %%
NumOUE = len(TABx2)
NumElem = len(Elem)
EleRange = range(0,NumElem)
OUERange = range(0,NumOUE)
EO = np.searchsorted(Elem[:,0], TABx2)
print(EO)
EleCorOx =[]
EleCorOy =[]
EleCorOz =[]
EleCorUx =[]
EleCorUy =[]
EleCorUz =[]
for i in EleRange:
Na = np.searchsorted(Node[:,0],Elem[i,1])
Nb = np.searchsorted(Node[:,0],Elem[i,2])
Nc = np.searchsorted(Node[:,0],Elem[i,3])
Nd = np.searchsorted(Node[:,0],Elem[i,4])
print(Na,Nb,Nc,Nd)
if i in EO:
EleCorOx += [(Node[Na,1] + Node[Nb,1] + Node[Nc,1] + Node[Nd,1])/4]
EleCorOy += [(Node[Na,2] + Node[Nb,2] + Node[Nc,2] + Node[Nd,2])/4]
EleCorOz += [(Node[Na,3] + Node[Nb,3] + Node[Nc,3] + Node[Nd,3])/4]
else:
EleCorUx += [(Node[Na,1] + Node[Nb,1] + Node[Nc,1] + Node[Nd,1])/4]
EleCorUy += [(Node[Na,2] + Node[Nb,2] + Node[Nc,2] + Node[Nd,2])/4]
EleCorUz += [(Node[Na,3] + Node[Nb,3] + Node[Nc,3] + Node[Nd,3])/4]
fig = plt.figure()
fig.set_size_inches(20,10)
ax = fig.add_subplot(projection='3d')
ax.scatter3D(EleCorUx,EleCorUy,EleCorUz,color = 'Blue')
ax.scatter3D(EleCorOx,EleCorOy,EleCorOz,color = 'red')
ax.set_zlim(0,27000)
plt.show()
This code is for showing Sektion 100. Small changes gives me the plots for 110, 120, 130 and so on.
If anyone can use it.

Plotted Images in Matplotlib Continue to get smaller, Final pdf doesn't show all plots

I'm trying to get multiple plots into a single figure. Having them in one column has been the approach I have been using but it isn't necessary. The problem I've been running into is that my figures will graph and each figure will be slightly smaller than the previous one. Additionally, the pdf I save from the figure is oddly proportioned and doesn't show all of the subplots. My commenting is slightly funky because I've been testing and cobbling from some of my old projects as well as the internet so don't look into it too much.
Here is my full code:
import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from tkinter import *
from tkinter import filedialog
import pandas as pds
from tqdm import tqdm as tq
from pathlib import Path
#%%Create Button Function for data input
def get_file_path():
global file_path
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("Excel Files", "*.xlsx"),))
l1 = Label(window, text = "File path: " + file_path).pack()
window = Tk()
width = window.winfo_screenwidth()
height = window.winfo_screenheight()
def close():
window.destroy()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
b2 = Button(window, text = "OK", command = close).pack()
window.geometry("%dx%d" % (width, height))
window.mainloop()
print(file_path)
#%%Read Excel File
ds = pds.read_excel(io = file_path, usecols = "A,D", skiprows = 1, keep_default_na = False)
#%%usv incident beggining times in seconds
usvTimes = ds["Begin Time (s)"].tolist()
#beginning times for tones in seconds
toneStart = ds["Tone Time Markers"].tolist()
toneStart2 = ds["Tone Time Markers"].tolist()
#%%creates empty lists to be used by loops later
graphStart = []
graphEnd = []
#%%creates the first parameter of the x value for each graph
print("Calculating GraphStart")
for num in tq(toneStart):
try:
int(float(num))
except:
pass
else:
graphStart.append(num - 30)
print("Complete")
#%%creates the second parameter of the x value for each graph
print("Calculating GraphEnd")
for num in tq(toneStart2):
try:
int(float(num))
except:
pass
else:
graphEnd.append(num + 30)
print("Complete")
#%%Makes usvTimes usable
print("Calculating USVTimeStamps")
for num in tq(usvTimes):
try:
int(float(num))
except:
pass
print("Complete")
#%%pair beggining and end parameter into a full list
graphpair = zip(graphStart,graphEnd)
#%%Zip x and y coordinates together
graphx = list(graphpair)
#%%create graphs
print("Creating Graphs")
myPath = str(Path.home() / "Downloads")
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
for index, num in tq(enumerate(graphx)):
x,y = num
leftbound = x
rightbound = y
graphnum = index + 1
a = []
for x in usvTimes:
try:
x + 0
except:
pass
else:
if leftbound <= x <= rightbound:
a.append(x)
plt.figure()
plt.subplot(graphnum,1,graphnum)
plt.hlines(1, leftbound, rightbound)
plt.eventplot(a, orientation='horizontal', colors='b')
plt.xlabel("Time in Recording (s)")
plt.ylabel("Arbitrary Axis (Abu)")
else:
pass
plt.savefig(myPath + "/Eventplot" + ".pdf")
print("Graphs Complete")

Annotating images from h5 file

.Hi all, I have 70k images saved into .h5 file and now with this script I want to read from that file and annotate text instances into .json file. When I run this script it takes very long time to annotate 1 image (cca 2h).
When I do this with 15 images then the script works fine and annotate all 15 images about a few seconds.
Now with 70k images -> .h5 file is 51gb.
I don't know is problem in code or the h5 file is too big? Because code works fine with small amount of images, but I'm working on some project where I need 70k or 700k images.
from __future__ import division
import os
import os.path as osp
from re import U
import numpy as np
import matplotlib.pyplot as plt
import h5py
from common import *
import json
import cv2
import numpy as np
from itertools import cycle
import js2py
#from gen import brojac
#from synthgen import imnames
global x
global y
def write_json(data, filename='annotation.json'):
with open(filename,'w') as file:
json.dump(data,file,indent=4)
DATA_PATH = 'results'
DB_FNAME = osp.join(DATA_PATH,'SynthText.h5')
def get_data():
return h5py.File(DB_FNAME,'r')
def viz_textbb(text_im, imageName, charBB_list, wordBB, textToList, alpha=1.0):
"""
text_im : image containing text
charBB_list : list of 2x4xn_i bounding-box matrices
wordBB : 2x4xm matrix of word coordinates
"""
#print("k",z, type(z))
plt.close(1)
plt.figure(1)
plt.imshow(text_im)
H,W = text_im.shape[:2]
global imnames
#print("MOLIIIM",wordBB)
#DODANO IZ MAIN-a
#**********************************************
db = h5py.File('results/SynthText.h5', 'r')
dsets = sorted(db['data'].keys())
for k in dsets:
db = get_data()
imnames = sorted(db['data'].keys())
start = 0
count = 0
coordinate = []
coordinate1 = []
name = []
name1 = []
final = []
upperList = []
downList = []
counter = 0
FinalFinal = []
imageData = { }
dictList = []
for eachWord in textToList:
length = len(eachWord)
for i in range(0,4):
for j in range(start,length+start):
coordinate.append([charBB_list[0][0][i][j], charBB_list[0][1][i][j]])
coordinate1.append((charBB_list[0][0][i][j], charBB_list[0][1][i][j]))
name.append(coordinate)
name1.append(coordinate1)
coordinate = []
for j in range(0, length):
for i in range(len(name)) :
#print(i,j, name[i][j]) ## koordinate da se snađem, treba
final.append(name[i][j])
#print(name)
#NEŠTA ZA CRTANJE, NEBITNO
if(i == 0 or i == 1):
upperList.append(name[i][j])
if(i == 2):
downList.append(name[i+1][j])
if(i == 3):
downList.append(name[i-1][j])
down = reversed(downList)
joinList = [*upperList,*down,upperList[0]]
FinalFinal.append(joinList)
imageData['transcription']=eachWord
imageData['language']="Latin"
imageData['illegibility']=False
imageData['points']=final
dictionary_copy = imageData.copy()
dictList.append(dictionary_copy)
del(dictionary_copy)
finalToList = np.array(final)
name=[]
final = []
upperList = []
downList = []
start = len(eachWord) + start
#del(dictList[0])
finalDict = {f'gt_{imageName}':dictList}
#print(type(finalDict)) --> dict
#print(imageName,finalDict)
#print(finalDict)
#print(len(textToList))
#print(textToList)
with open("annotation.json") as json_file:
data=json.load(json_file)
temp=data["annotations"]
#temp.append(finalDict)
temp.update(finalDict)
#temp['annotations'] = finalDict
write_json(data)
json_file.close()
for list in FinalFinal:
x,y = zip(*list)
plt.plot(x,y)
#print(x,y)
# points = tuple(zip(x,y))
# # boundaries of the bounding box
# left, right = min(points, key=lambda p: p[0]), max(points, key=lambda p: p[0])
# bottom, top = min(points, key=lambda p: p[1]), max(points, key=lambda p: p[1])
# # area
# base = right[0] - left[0]
# height = top[1] - bottom[1]
# A = base * height
#print(A)
for i in range(len(charBB_list)):
# #print(charBB_list) #ispisuje x-eve za jedan vrh svih instanci pojedinih slova, pa drugi, 3. i 4. i onda posebno y-one
bbs = charBB_list[i]
ni = bbs.shape[-1]
for j in range(ni):
bb = bbs[:,:,j]
bb = np.c_[bb,bb[:,0]] #ako se doda ,bb[:,0] -> printa isto kao i gornji lijevi
#plt.plot(bb[0,:], bb[1,:], 'r', alpha=alpha)
# plot the word-BB:
for i in range(wordBB.shape[-1]):
bb = wordBB[:,:,i] #koordinate wordBB-a
bb = np.c_[bb,bb[:,0]] #spaja skroz lijevu, TREBA
#plt.plot(bb[0,:], bb[1,:], 'g', alpha=alpha)
# visualize the indiv vertices:
vcol = ['r','g','b','k']
#for j in range(4):
#plt.scatter(bb[0,j],bb[1,j],color=vcol[j])
#print(bb) # ----> KOORDINATE wordBB-a
#print(bb[1,j])
plt.gca().set_xlim([0,W-1])
plt.gca().set_ylim([H-1,0])
plt.show(block=False)
def main(db_fname):
db = h5py.File(db_fname, 'r')
dsets = sorted(db['data'].keys())
print ("total number of images : ", colorize(Color.RED, len(dsets), highlight=True))
for k in dsets:
rgb = db['data'][k][...]
charBB = db['data'][k].attrs['charBB']
wordBB = db['data'][k].attrs['wordBB']
txt = db['data'][k].attrs['txt']
textToList = (db['data'][k].attrs['txt']).tolist()
#print(textToList)
viz_textbb(rgb, k,[charBB], wordBB, textToList)
print ("image name : ", colorize(Color.RED, k, bold=True))
print (" ** no. of chars : ", colorize(Color.YELLOW, charBB.shape[-1]))
print (" ** no. of words : ", colorize(Color.YELLOW, wordBB.shape[-1]))
print (" ** text : ", colorize(Color.GREEN, txt))
#print("To know", z[1], type(z[1]))
# OTKOMATI OVO DOLJE AKO ŽELIM STISKAT ENTER
# if 'q' in input("next? ('q' to exit) : "):
# break
db.close()
if __name__=='__main__':
main('results/SynthText.h5')

pandas data-frame continuously update

please see the pandas based Patten scanner, here i am using csv as data source and loading the same in to data.
since data is loading from csv file, i have to reload/rerun the script every 5 min to read the updated csv file hence repeating the plot every 5min.
is there any way to use df.update to avoid reloading of the script and prevent the reloading of plot again and again.
import pandas as pd
import numpy as np
from scipy.signal import argrelextrema
import matplotlib.pyplot as plt
from harmonic_functions import *
import uuid
from csv import DictReader
data = pd.read_csv('temp.csv')
data.time = pd.to_datetime(data.time,format='%d.%m.%Y %H:%M:%S.%f')
data.index = data['time']
# data = data.drop_duplicates(keep=False)
price = data.close.copy()
err_allowed = 10.0/100
pnl = []
trade_dates=[]
correct_pats=0
pats=0
# plt.ion()
for i in range (100,len(price)):
current_idx,current_pat,start,end = peak_detect(price.values[:i],order=7)
XA = current_pat[1] - current_pat[0]
AB = current_pat[2] - current_pat[1]
BC = current_pat[3] - current_pat[2]
CD = current_pat[4] - current_pat[3]
moves = [XA,AB,BC,CD]
gart = is_gartley(moves,err_allowed)
butt = is_butterfly(moves,err_allowed)
bat = is_bat(moves,err_allowed)
crab = is_crab(moves,err_allowed)
shark = is_shark(moves,err_allowed)
trio = is_trio(moves,err_allowed)
cyph = is_cyph(moves,err_allowed)
three_dives = is_3dives(moves, err_allowed)
fivezero = is_50(moves, err_allowed)
altbat = is_altbat(moves, err_allowed)
deepcrab = is_deepcrab(moves, err_allowed)
dragon = is_dragon(moves, err_allowed)
snorm = is_snorm(moves, err_allowed)
harmonics = np.array([gart,butt,bat,crab,shark,trio,cyph,three_dives,fivezero,altbat,deepcrab,dragon,snorm])
labels = ['Garterly','Butterfly','Bat','Crab','Shark','Trio','Cypher','3Dives','5Zero','AltBat','DeepCrab','Dragon','Snorm']
if np.any(harmonics == 1) or np.any(harmonics == -1):
for j in range (0,len(harmonics)):
if harmonics[j] == 1 or harmonics[j]==-1:
pats+=1
sense = 'Bearish ' if harmonics[j]==-1 else 'Bullish '
label = sense + labels[j] + ' found'
print(label)
print(price.values[start])
plt.title(label)
plt.plot(np.arange(start,i+5),price.values[start:i+5])
plt.scatter(current_idx,current_pat,c='r')
filename = str(uuid.uuid1())[:8]
print(current_pat)
print(current_idx)
# with open('temp.csv', mode='r') as csv_file:
# file = DictReader(csv_file, delimiter=',')
# close = str(current_pat[4])
# print(current_pat)
# rows = [row for row in file if row['close'] in close]
# closetime = rows[-1]['ID']
# print(closetime)
write1 = str(current_idx)
write2 = str(current_pat)
write = write1 + ',' + write2
print(write)
with open("datadb", "r+") as file:
for line in file:
if write in line:
break
else: # not found, we are at the eof
file.write(f"{write}\n") # append missing data
print(filename)
plt.savefig(filename)
plt.close(filename)
# plt.show()
plt.clf()

How do I get the graph to open a new window when run?

I would like for the resulting graph to be in a new window. I know the phrase, %matplotlib inline puts the graph in the console, but if I remove it it gives me the error
FigureCanvasMac' object has no attribute 'get_renderer.
Is there a way I can go around this?
import re
import ftplib
import os
from urllib.request import urlopen
import json
import matplotlib
%matplotlib inline
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
import numpy as np
import pylab
import re
import sunpy.time
import numpy as np
from numpy.random import *
from matplotlib.patches import Rectangle
from adjustText import adjust_text
import pandas as pd
from scipy import interpolate
import sys
info = []
parsedFilename = []
dateAndTime = []
xcen = []
ycen = []
sciObj = []
xfov = []
yfov = []
matchingAR = []
def getNumberOfEntries(theJSON):
return len(dateAndTime)
def getInfo(counter, theJSON):
cont = True
while cont:
try:
dateAndTime.append(theJSON["Events"][counter]["date"])
xcen.append(float("%.2f" % theJSON["Events"][counter]["xCen"]))
ycen.append(float("%.2f" % theJSON["Events"][counter]["yCen"]))
xfov.append(float("%.2f" % theJSON["Events"][counter]["raster_fovx"]))
yfov.append(float("%.2f" % theJSON["Events"][counter]["raster_fovy"]))
sciObj.append(theJSON["Events"][counter]["sciObjectives"])
counter = counter + 1
getInfo(counter, theJSON)
except IndexError:
cont = False
break
def setXMax(theJSON):
xmax = xcen[0]
for i in range (0, getNumberOfEntries(theJSON)):
if xcen[i] > xmax:
xmax = xcen[i]
return round(xmax + 150,-1)
def setXMin(theJSON):
xmin = xcen[0]
for i in range (0, getNumberOfEntries(theJSON)):
if xcen[i] < xmin:
xmin = xcen[i]
return round(xmin - 150, -1)
def setYMax(theJSON):
ymax = ycen[0]
for i in range (0, getNumberOfEntries(theJSON)):
if ycen[i] > ymax:
ymax = ycen[i]
return round(ymax + 150, -1)
def setYMin(theJSON):
ymin = ycen[0]
for i in range (0, getNumberOfEntries(theJSON)):
if ycen[i] < ymin:
ymin = ycen[i]
return round(ymin - 150, -1)
# def sort():
# for i in range(len(dateAndTime)):
# for j in range(len(xcen)-1, i, -1):
# if ( xcen[j] < xcen[j-1]):
# temp1 = dateAndTime[j]
# dateAndTime[j] = dateAndTime[j-1]
# dateAndTime[j-1] = temp1
# temp2 = xcen[j]
# xcen[j] = xcen[j-1]
# xcen[j-1] = temp2
# temp3 = ycen[j]
# ycen[j] = ycen[j-1]
# ycen[j-1] = temp3
# temp4 = xfov[j]
# xfov[j] = xcen[j-1]
# xfov[j-1]=temp4
# temp5 = yfov[j]
# yfov[j] = ycen[j-1]
# yfov[j-1]=temp5
# temp6 = sciObj[j]
# sciObj[j] = sciObj[j-1]
# sciObj[j-1] = temp6
def sort():
for i in range(len(dateAndTime)):
for j in range(len(dateAndTime)-1, i, -1):
if ( dateAndTime[j] < dateAndTime[j-1]):
temp1 = dateAndTime[j]
dateAndTime[j] = dateAndTime[j-1]
dateAndTime[j-1] = temp1
temp2 = xcen[j]
xcen[j] = xcen[j-1]
xcen[j-1] = temp2
temp3 = ycen[j]
ycen[j] = ycen[j-1]
ycen[j-1] = temp3
temp4 = xfov[j]
xfov[j] = xcen[j-1]
xfov[j-1]=temp4
temp5 = yfov[j]
yfov[j] = ycen[j-1]
yfov[j-1]=temp5
temp6 = sciObj[j]
sciObj[j] = sciObj[j-1]
sciObj[j-1] = temp6
def createAnnotations(theJSON):
annotations = []
for i in range(getNumberOfEntries(theJSON)):
annotations.append('(' + str(xcen[i])+ ', '+ str(ycen[i]) + ')')
return annotations
def fixAnnotations(annotations):
texts = []
for xt, yt, s in zip(xcen, ycen, annotations):
texts.append(plt.text(xt, yt, s))
return texts
def plot(theJSON):
fig, ax = plt.subplots(figsize=(30, 20))
circle = Circle((0, 0), 980, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5)
ax.add_patch(circle)
plt.plot(xcen, ycen, color="red")
plt.plot(xcen, ycen, 'ro', color = 'blue')
plt.xlim([setXMin(theJSON), setXMax(theJSON)])
plt.ylim([setYMin(theJSON), setYMax(theJSON)])
ax.set_xticks(np.arange(setXMin(theJSON), setXMax(theJSON), 50))
ax.set_yticks(np.arange(setYMin(theJSON), setYMax(theJSON), 50))
for i in range(getNumberOfEntries(theJSON)):
if xfov[i] != 0:
xStart = xcen[i] - xfov[i]/20
yStart = ycen[i] - yfov[i]/20
ax.add_patch(Rectangle((xStart, yStart), xfov[i]/10, yfov[i]/10, facecolor='none'))
texts = fixAnnotations(createAnnotations(theJSON))
f = interpolate.interp1d(xcen, ycen)
x = np.linspace(min(xcen), max(ycen), 1000)
y = f(x)
adjust_text(texts, x, y, arrowprops=dict(arrowstyle="->", color='r', lw=2.0), autoalign='y', only_move={'points':'y', 'text':'y'}, expand_points=(1.2, 1.4), force_points=0.40)
plt.grid()
plt.show()
main(False)
def searchOnceMore(searchAgain):
if searchAgain == True:
noaaNmbr = input('Enter desired active region: ')
return noaaNmbr
else:
continueSearch = input('Would you like to search again?(yes/no)')
if continueSearch == 'yes':
noaaNmbr = input('Enter desired active region:')
return noaaNmbr
elif continueSearch == 'no':
sys.exit(0)
else:
print('please enter "yes" or "no"')
searchOnceMore(False)
def main(searchAgain):
noaaNmbr = searchOnceMore(searchAgain)
urlData = "http://www.lmsal.com/hek/hcr?cmd=search-events3&outputformat=json&instrument=IRIS&noaanum="+ noaaNmbr +"&hasData=true"
webUrl = urlopen(urlData)
counter = 0
if (webUrl.getcode()==200):
data = webUrl.read().decode('utf-8')
theJSON = json.loads(data)
getInfo(counter, theJSON)
else:
print ("You done messed up!!!")
sort()
for i in range (getNumberOfEntries(theJSON)):
print(dateAndTime[i])
print("(", xcen[i], ", ", ycen[i], ")")
print(sciObj[i])
print(' ')
if getNumberOfEntries(theJSON) != 0:
plot(theJSON)
else:
print('No observations for active region ' + noaaNmbr)
main()
main(True)
I have also used python and would suggest using John Zelle's graphic file. http://mcsp.wartburg.edu/zelle/python/
It's much more easier to understand and use in my opinion.
To open a new graph window:
Win1 = GraphWin("Graph Window 1", 100,100)
win2 = GraphWin("Graph Window 2", 100,150)
You can also open the python file to understand how it works. It might help understanding how to open a graph window your way. I only know how to open a new Graph Window through this file sorry, I hope it helps anyway!

Categories