Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ exclude = [
"__pycache__",
"build",
"bella/version.py",
"bella/type_III_fitter/read_wi_wa_l2_60s_data.py",
]

[lint]
Expand Down Expand Up @@ -32,6 +33,8 @@ extend-ignore = [
]
"__init__.py" = ["E402", "F401", "F403"]
"test_*.py" = ["B011", "D", "E402", "PGH001", "S101"]
"bella/multilaterate/bayes_positioner.py" = ["F841"]


[lint.pydocstyle]
convention = "numpy"
10 changes: 5 additions & 5 deletions bella/multilaterate/bayes_positioner.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def sample(self, toa, draws=2000, tune=2000, chains=4,cores=4, init='jitter+adap

# assert correct number of observations
if len(toa) != len(stations):
raise Exception("ERROR: number of observations must match number of stations! (%i, %i)"%(len(toa), len(stations)))
raise Exception(f"ERROR: number of observations must match number of stations! ({len(toa)}, {len(stations)})")

# assert max toa is not larger than t_lim
if np.max(toa) > t_lim:
Expand Down Expand Up @@ -167,7 +167,7 @@ def triangulate(coords, times,t_cadence=60,v_sd=3E5, chains=4, cores=4, N_SAMPLE
print(summary)


if traceplot==True:
if traceplot is True:
# trace plot
left = 0.04 # the left side of the subplots of the figure
right = 0.972 # the right side of the subplots of the figure
Expand Down Expand Up @@ -331,7 +331,7 @@ def triangulate(coords, times,t_cadence=60,v_sd=3E5, chains=4, cores=4, N_SAMPLE
ax[3, 1].set_ylim([t_sampled-2.9*t_sd_sampled, t_sampled+2.9*t_sd_sampled])
# plt.show(block=False)

if savetraceplot == True:
if savetraceplot is True:
t0 = times[0]
if traceplotdir=="":
direct = mkdirectory("./Traceplots/")
Expand All @@ -345,7 +345,7 @@ def triangulate(coords, times,t_cadence=60,v_sd=3E5, chains=4, cores=4, N_SAMPLE
print(f"saved {direct}/traceplot_{traceplotfn}")


if showplot==True:
if showplot is True:
plt.show(block=False)
else:
plt.close()
Expand All @@ -370,7 +370,7 @@ def triangulate(coords, times,t_cadence=60,v_sd=3E5, chains=4, cores=4, N_SAMPLE
plt.xlabel(r"'HEE - X / $R_{\odot}$'")
plt.ylabel(r"'HEE - Y / $R_{\odot}$'")
# plt.savefig("bayes_positioner_result2.jpg", bbox_inches='tight', pad_inches=0.01, dpi=300)
if showplot==True:
if showplot is True:
plt.show(block=False)
else:
plt.close()
Expand Down
29 changes: 15 additions & 14 deletions bella/multilaterate/bayesian_tracker.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@

# Standard Library imports
import os
import sys
# General
import logging
import datetime as dt
Expand All @@ -17,12 +16,15 @@
import numpy as np
import pymc3 as pm
import solarmap
# Local imports
from bayes_positioner import *
from scipy.ndimage import median_filter

from astropy.constants import R_sun, au, c

# Local imports
import sys
sys.path.insert(1, '/Users/canizares/Library/CloudStorage/OneDrive-Personal/Work/0_PhD/Projects/BELLA_Projects/TCDSolarBELLA')
from bella.multilaterate.bayes_positioner import triangulate


@contextmanager
def suppress_stdout():
Expand Down Expand Up @@ -52,7 +54,6 @@ def parallel_pos_map(x1,y1,stations,xrange,yrange,xres,yres, cores=1, traceplots

x_true = np.array([x1 * R_sun.value, y1 * R_sun.value]) # true source position (m)
v_true = c.value # speed of light (m/s)
t0_true = 100 # source time. can be any constant, as long as it is within the uniform distribution prior on t0
d_true = np.linalg.norm(stations - x_true, axis=1)
t1_true = d_true / v_true # true time of flight values
# t_obs = t1_true-t0_true# true time difference of arrival values
Expand All @@ -72,7 +73,7 @@ def parallel_pos_map(x1,y1,stations,xrange,yrange,xres,yres, cores=1, traceplots
# print(f"t1_pred: {t1_pred}")
# print(f"stations: {stations}")

if traceplotsave == True:
if traceplotsave is True:
traceplotpath = f"./traceplots/{date_str}/traceplot_{xrange[0]}_{xrange[1]}_{yrange[0]}_{yrange[1]}_{xres}_{yres}"
mkdirectory(traceplotpath)

Expand All @@ -96,12 +97,11 @@ def parallel_pos_map(x1,y1,stations,xrange,yrange,xres,yres, cores=1, traceplots
res = np.array([delta_obs, np.nan, np.nan])
tloop1 = dt.datetime.now()

except:
delta_obs = 200
print(f"SIM FAILED at P({x1},{y1}), SKIPPED")
res = np.array([delta_obs, x1, y1])

except Exception as e:
print(f"Error at P({x1},{y1}): {str(e)}")
res = np.array([600, x1, y1]) # Fallback error handling
tloop1 = dt.datetime.now()
pass

tloopinseconds = (tloop1 - tloop0).total_seconds()
print(f"Time Loop : {tloop1 - tloop0} : {tloopinseconds}s ")
Expand All @@ -128,8 +128,9 @@ def parallel_tracker(freq,t_obs, stations ):
res = np.array([xy, np.nan, np.nan])

tloop1 = dt.datetime.now()
except:
except Exception as e:
xy = 0
print(f"ERROR: {e}")
print(f"SIM FAILED at Freq = {freq} MHz, SKIPPED")
res = np.array([xy, freq])
tloop1 = dt.datetime.now()
Expand Down Expand Up @@ -178,12 +179,12 @@ def plot_map_simple(delta_obs, xmapaxis, ymapaxis, stations,vmin=0,vmax=30, save
ax.set_ylabel(r"'HEE - Y / $R_{\odot}$'", fontsize=22)
ax.set_title(title, fontsize=22)

if savefigure == True:
if savefigure is True:
figdir = f"{figdir}/{date_str}"
mkdirectory(figdir)
plt.savefig(figdir+f"/bayes_positioner_map_{xmapaxis[0]}_{xmapaxis[-1]}_{ymapaxis[0]}_{ymapaxis[-1]}_{xres}_{yres}_{N_STATIONS}.jpg", bbox_inches='tight', pad_inches=0.01, dpi=300)

if showfigure == True:
if showfigure is True:
plt.show(block=False)
else:
plt.close(fig)
Expand All @@ -208,7 +209,7 @@ def savetrackedtypeiii(results, dir="./Data/", date_str="date", profile="PROFILE
title = f"TRACKING_{date_str}_results_{N_STATIONS}stations_{profile}.pkl"


direct = mkdirectory(dir)
mkdirectory(dir)

stringpath = dir+f'{title}'
with open(stringpath, 'wb') as outp:
Expand Down
44 changes: 23 additions & 21 deletions bella/multilaterate/bella_plotter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import sys
import math
import logging
import datetime as dt
Expand All @@ -12,7 +11,6 @@
import numpy as np
import scipy.io
import solarmap
from bayes_positioner import *
from matplotlib import cm
from matplotlib.ticker import FormatStrFormatter, LogFormatter
# import pymc3 as pm
Expand All @@ -22,6 +20,10 @@
# import arviz as az
from astropy.constants import R_sun, au

import sys
# sys.path.insert(1, '/Users/canizares/Library/CloudStorage/OneDrive-Personal/Work/0_PhD/Projects/BELLA_Projects/TCDSolarBELLA')
# from bella.multilaterate.bayes_positioner import *

plt.rcParams.update({'font.size': 18})
plt.rcParams["font.family"] = "Times New Roman"

Expand Down Expand Up @@ -81,9 +83,9 @@ def plot_map_simple_withTracked(delta_obs, trackedtypeIII, xmapaxis, ymapaxis, s
sd = sd_vals/R_sun.value


xres = xmapaxis[1]-xmapaxis[0]
yres = ymapaxis[1]-ymapaxis[0]
N_STATIONS = len(stations)
xmapaxis[1]-xmapaxis[0]
ymapaxis[1]-ymapaxis[0]
len(stations)


# PARKER SPIRAL
Expand Down Expand Up @@ -128,7 +130,7 @@ def plot_map_simple_withTracked(delta_obs, trackedtypeIII, xmapaxis, ymapaxis, s
i+=1


if parker_spiral == True:
if parker_spiral is True:
ax.plot(x_parker,y_parker,"k--")
ax.plot(x_parker_plus,y_parker_plus,"k--", markersize=0.5)
ax.plot(x_parker_minus,y_parker_minus,"k--")
Expand All @@ -144,7 +146,7 @@ def plot_map_simple_withTracked(delta_obs, trackedtypeIII, xmapaxis, ymapaxis, s

# # ELLIPSES
colors = cm.turbo(list(np.linspace(0,1.0,len(xy))))
if confidence ==True:
if confidence is True:
i = 0
ell_track_uncertainty = matplotlib.patches.Ellipse(xy=(xy[i, 0], xy[i, 1]),
width=2 * sd[i, 0], height=2 * sd[i, 1],
Expand Down Expand Up @@ -204,12 +206,12 @@ def plot_map_simple_withTracked(delta_obs, trackedtypeIII, xmapaxis, ymapaxis, s
ax.set_ylabel(r"HEE - Y (R$_\odot$)", fontsize=22)
ax.set_title(title, fontsize=22)

if savefigure == True:
if savefigure is True:
figdir = f"{figdir}/{date_str}"
mkdirectory(figdir)
plt.savefig(figdir+filename, bbox_inches='tight', pad_inches=0.01, dpi=300)

if showfigure == True:
if showfigure is True:
plt.show(block=False)
else:
plt.close(fig)
Expand All @@ -225,9 +227,9 @@ def plot_bella_map(fig,ax,delta_obs, xmapaxis, ymapaxis, stations,
linecolor = "k"):


xres = xmapaxis[1]-xmapaxis[0]
yres = ymapaxis[1]-ymapaxis[0]
N_STATIONS = len(stations)
xmapaxis[1]-xmapaxis[0]
ymapaxis[1]-ymapaxis[0]
len(stations)

# fig, ax = plt.subplots(1,1,figsize=(11,11))
# plt.subplots_adjust(top=1, bottom=0)
Expand Down Expand Up @@ -258,7 +260,7 @@ def plot_bella_map(fig,ax,delta_obs, xmapaxis, ymapaxis, stations,
ax.set_ylim(ymapaxis[0], ymapaxis[-1])

# fig.subplots_adjust(right=0.9)
if showcolorbar == True:
if showcolorbar is True:
cbar_ax = fig.add_axes(cbar_axes) # [left, bottom, width, height]
fig.colorbar(im_0, cax=cbar_ax)
cbar_ax.set_ylabel(r'BELLA uncertainty (R$_\odot$)', fontsize=18)
Expand All @@ -269,7 +271,7 @@ def plot_bella_map(fig,ax,delta_obs, xmapaxis, ymapaxis, stations,
if "sun" in objects:
ax.plot(0, 0, 'yo', label="Sun", markersize=10, markeredgecolor ='k')

if showlegend == True:
if showlegend is True:
ax.legend(loc=1)

ax.set_xlabel(r"HEE - X (R$_\odot$)", fontsize=20)
Expand Down Expand Up @@ -299,7 +301,7 @@ def plot_tracked_typeIII(fig, ax, trackedtypeIII, confidence=False, showcolorbar
# colors = cm.turbo(list(np.linspace(0,1.0,len(xy))))


if confidence ==True:
if confidence is True:
i = 0
ell_track_uncertainty = matplotlib.patches.Ellipse(xy=(xy[i, 0], xy[i, 1]),
width=2*sd[i, 0], height=2*sd[i, 1],
Expand All @@ -316,7 +318,7 @@ def plot_tracked_typeIII(fig, ax, trackedtypeIII, confidence=False, showcolorbar

im_track = ax.scatter(xy[:,0], xy[:,1],c = tracked_freqs, cmap=cmap, marker=marker, edgecolors=edgecolors, s=s, label=label, norm=norm,zorder=zorder)

if showcolorbar == True:
if showcolorbar is True:
if cbar_sep_ax:
cbar_ax2 = fig.add_axes(cbar_axes) # [left, bottom, width, height]
formatter = LogFormatter(10, labelOnlyBase=False)
Expand Down Expand Up @@ -354,7 +356,7 @@ def plot_typeIII_sim(fig, ax, trackedtypeIII, confidence=False, showcolorbar=Tru
colors = cmap_func(np.linspace(0, 1.0, len(xy)))

# colors = cm.turbo(list(np.linspace(0,1.0,len(xy))))
if confidence ==True:
if confidence is True:
i = 0
ell_track_uncertainty = matplotlib.patches.Ellipse(xy=(xy[i, 0], xy[i, 1]),
width=2*sd[i, 0], height=2*sd[i, 1],
Expand All @@ -373,10 +375,10 @@ def plot_typeIII_sim(fig, ax, trackedtypeIII, confidence=False, showcolorbar=Tru
ax.add_patch(ell_track_uncertainty)

if showtruesources:
im_true = ax.scatter(xy_true[:,0], xy_true[:,1], cmap=cmap, marker="o", edgecolors=edgecolors, c="yellow", s=s, label="True Sources", norm=norm,zorder=zorder-1)
ax.scatter(xy_true[:,0], xy_true[:,1], cmap=cmap, marker="o", edgecolors=edgecolors, c="yellow", s=s, label="True Sources", norm=norm,zorder=zorder-1)
im_track = ax.scatter(xy[:,0], xy[:,1], cmap=cmap, marker=marker, edgecolors=edgecolors, s=s, label=label, norm=norm,zorder=zorder)

if showcolorbar == True:
if showcolorbar is True:
cbar_ax2 = fig.add_axes(cbar_axes) # [left, bottom, width, height]
formatter = LogFormatter(10, labelOnlyBase=False)
fig.colorbar(im_track, cax=cbar_ax2, format=formatter)
Expand Down Expand Up @@ -720,7 +722,7 @@ def __init__(self, xy_true, xy_detected, sd_detected):
ax.tick_params(axis='both', which='major', labelsize=18)
plt.show(block = False)

if savefigs == True:
if savefigs is True:
dir = mkdirectory("./Figures/")
if trackedfile[-11:-4] != 'SCATTER':
plt.savefig(dir+'BELLA_map0.png', dpi=300)
Expand Down Expand Up @@ -817,7 +819,7 @@ def __init__(self, xy_true, xy_detected, sd_detected):
# plt.show(block = False)
#
# savefigs = True
# if savefigs == True:
# if savefigs is True:
# plt.savefig('/Users/canizares/OneDrive/Work/0_PhD/Projects/2012_06_07_WSTASTB/BELLA_map_mosaic.png', dpi=300)
#
#
Loading