Skip to content

Commit

Permalink
wrapping in docstrings
Browse files Browse the repository at this point in the history
small fix to timebase plotting in binary_system.py
  • Loading branch information
Matthias Fabry committed Jan 27, 2023
1 parent 782ce5c commit 609dc62
Show file tree
Hide file tree
Showing 8 changed files with 328 additions and 258 deletions.
230 changes: 147 additions & 83 deletions modules/binary_system.py

Large diffs are not rendered by default.

22 changes: 11 additions & 11 deletions modules/data_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import numpy as np

import modules.constants as cst

import modules.spinOS_io as spl
import modules.utils as util

Expand All @@ -46,7 +45,7 @@ def buildSets(self):
for dataset in self.datasets['AS']:
dataset.setData()
self.setDefWeight()
self.gui.def_as_weight.set(self.defWeight)
self.gui.def_as_weight.set(np.round(self.defWeight, 4))

def getBuiltRV1s(self):
data = None
Expand Down Expand Up @@ -191,19 +190,19 @@ def setDefWeight(self):
else:
numrv1 = sum(
(
len(dataset.getData()) if dataset.getData() is not None
else 0
for dataset in
self.datasets['RV1']))
len(dataset.getData()) if dataset.getData() is not None
else 0
for dataset in
self.datasets['RV1']))
if not self.hasRV2():
numrv2 = 0
else:
numrv2 = sum(
(
len(dataset.getData()) if dataset.getData() is not None
else 0
for dataset in
self.datasets['RV2']))
len(dataset.getData()) if dataset.getData() is not None
else 0
for dataset in
self.datasets['RV2']))
self.defWeight = numas / (numrv1 + numrv2 + numas)


Expand All @@ -230,7 +229,7 @@ def __init__(self, dataman, tab, book, filename, name=None, tpe='AS'):
command=self.selAll).grid()
but = ttk.Frame(newset)
ttk.Button(but, text='+', command=self.addentry).grid()
ttk.Button(but, text='Rename', command=self.setName)\
ttk.Button(but, text='Rename', command=self.setName) \
.grid(row=0, column=1)
but.pack()
self.data = None
Expand Down Expand Up @@ -276,6 +275,7 @@ def getData(self) -> np.ndarray:
def selAll(self):
for entry in self.entries:
entry.include.set(self.selall.get())
self.dataman.buildSets()


class RVDataSet(DataSet):
Expand Down
257 changes: 124 additions & 133 deletions modules/gui.py

Large diffs are not rendered by default.

17 changes: 11 additions & 6 deletions modules/minimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,17 @@ def LMminimizer(guess_dict: dict, data_dict: dict, method: str = 'leastsq',
if not AS:
for key in 'i', 'Omega', 'mt':
params[key].set(vary=False)
elif AS and ('q' in params.valuesdict().keys()) \
and params.valuesdict()['q'] != 0:
params['i'] \
.set(expr='180-180/pi*asin(sqrt(1-e**2)*k1*(q+1)/q*'
'(p*86400/(2*pi*6.67430e-20*mt*1.9885e30))**(1/3))')

elif AS:
for key in 'k1', 'gamma1', 'k2', 'gamma2':
params[key].set(vary=False)
else:
raise ValueError('No data supplied! Cannot minimize.')
raise ValueError('No data supplied! Cannot minimize.\n')

# build a minimizer object
minimizer = lm.Minimizer(fcn2min, params,
Expand All @@ -165,9 +171,8 @@ def LMminimizer(guess_dict: dict, data_dict: dict, method: str = 'leastsq',
print('this minimization method not implemented')
return
toc = time.time()
print('Minimization Complete in {} s!\n'.format(toc - tic))
print('Minimization Complete in {} s!\n'.format(np.round(toc - tic, 3)))
lm.report_fit(result.params)
print('\n')
rms_rv1, rms_rv2, rms_as = 0, 0, 0
system = BinarySystem(result.params.valuesdict())
if RV1:
Expand All @@ -178,16 +183,16 @@ def LMminimizer(guess_dict: dict, data_dict: dict, method: str = 'leastsq',
if RV2:
# Same for RV2
rms_rv2 = np.sqrt(np.sum(
(system.secondary.radial_velocity_of_hjds(
rv2s[:, 0]) - rv2s[:, 1]) ** 2) / len(rv2s[:, 1]))
(system.secondary.radial_velocity_of_hjds(
rv2s[:, 0]) - rv2s[:, 1]) ** 2) / len(rv2s[:, 1]))
if AS:
# same for AS
omc2E = np.sum(
(system.relative.east_of_hjds(aas[:, 0]) - aas[:, 1]) ** 2)
omc2N = np.sum(
(system.relative.north_of_hjds(aas[:, 0]) - aas[:, 2]) ** 2)
rms_as = np.sqrt((omc2E + omc2N) / LAS)
print('Minimization complete, check parameters tab for resulting orbit!')
print('Minimization complete, check parameters tab for resulting orbit!\n')
return result, rms_rv1, rms_rv2, rms_as


Expand Down
15 changes: 8 additions & 7 deletions modules/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,15 +227,16 @@ def init_plots(self):
plt.close(self.rv_fig)
if self.as_fig is not None:
plt.close(self.as_fig)

self.rv_fig = plt.figure(num='RV curve')
move_figure(self.rv_fig, int(0.37 * self.gui.w) + 10, 0)

self.as_fig = plt.figure(num='Apparent orbit')
move_figure(self.as_fig, int(0.37 * self.gui.w) + 10,
int(0.5 * self.gui.h + 10))

self.rv_ax = self.rv_fig.add_subplot(111)
self.as_ax = self.as_fig.add_subplot(111, aspect=1)

move_figure(self.rv_fig, int(int(0.37 * self.gui.w) + 10), 0)
move_figure(self.as_fig, int(int(0.37 * self.gui.w) + 10),
int(int(0.5 * self.gui.h) + 10))

self.rv_ax.grid(self.do_grids.get())
self.setup_rv_ax()
self.as_ax.axhline(linestyle=':', color='black')
Expand All @@ -247,8 +248,7 @@ def init_plots(self):
self.rv_fig.tight_layout()
self.as_fig.tight_layout()
plt.ion() # important: this lets mpl release the event loop to tk,
# ie plt.show() doesn't
# block
# ie plt.show() doesn't block app
plt.show()

def setup_rv_ax(self):
Expand Down Expand Up @@ -436,6 +436,7 @@ def _determine_time_bounds(self):
data = self.gui.datamanager.getBuiltRV2s()
m = min(m, min(data[:, 0]))
mm = max(mm, max(data[:, 0]))
print('time bounds', m, mm)
return m, mm

def plot_gamma1(self):
Expand Down
16 changes: 10 additions & 6 deletions modules/spinOS_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ def guess_loader(wd: str, guessfile: str) -> dict:
"""
parses the guess file and determines values and flags for each guess
:param wd: the working directory
:param guessfile: pathname (relative to wd) pointing to the file containing guesses
:param guessfile: pathname (relative to wd) pointing to the file
containing guesses
:return: dictionary containing the guesses and flags for each parameter
"""
wd = check_slash(wd)
guesses = np.genfromtxt(wd + guessfile, dtype=None, filling_values=np.nan, usecols=(0, 1, 2),
encoding='utf-8')
guesses = np.genfromtxt(wd + guessfile, dtype=None, filling_values=np.nan,
usecols=(0, 1, 2), encoding='utf-8')
guessdict = dict()
for i in range(12):
guessdict[guesses[i][0]] = (guesses[i][1], guesses[i][2])
Expand All @@ -54,7 +55,8 @@ def data_loader(wd: str, filetypes: list, filenames: list) -> dict:
"""
loads data from files into a dictionary
:param wd: working directory where the files are
:param filetypes: data types to load, must be 'RV1file', 'RV2file', or 'ASfile'
:param filetypes: data types to load, must be 'RV1file', 'RV2file',
or 'ASfile'
:param filenames: names of the files in question
:return: data in a dictionary
"""
Expand Down Expand Up @@ -95,7 +97,8 @@ def data_loader(wd: str, filetypes: list, filenames: list) -> dict:

def convert_error_ellipse(major, minor, angle):
"""
Converts error ellipses to actual east and north errors by a sampling the error ellipse monte-carlo style and
Converts error ellipses to actual east and north errors by a sampling
the error ellipse monte-carlo style and
then taking the variance in the east and north directions.
:param major: length of the major axis of the error ellipse
:param minor: length of the minor axis of the error ellipse
Expand All @@ -107,7 +110,8 @@ def convert_error_ellipse(major, minor, angle):
sina = np.sin(angle)
temp_major = np.random.randn(num) * major
temp_minor = np.random.randn(num) * minor
rotated_temp = np.matmul(np.array([[cosa, sina], [-sina, cosa]]), [temp_major, temp_minor])
rotated_temp = np.matmul(np.array([[cosa, sina], [-sina, cosa]]),
[temp_major, temp_minor])
east_error = np.std(rotated_temp[0])
north_error = np.std(rotated_temp[1])
return east_error, north_error
Expand Down
23 changes: 14 additions & 9 deletions modules/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ class VerticalScrolledFrame:
ie it needs a master and layout and it can be a master.
:width:, :height:, :bg: are passed to the underlying Canvas
:bg: and all other keyword arguments are passed to the inner Frame
note that a widget layed out in this frame will have a self.master 3 layers deep,
(outer Frame, Canvas, inner Frame) so
if you subclass this there is no built in way for the children to access it.
You need to provide the controller separately.
note that a widget layed out in this frame will have a self.master 3
layers deep, (outer Frame, Canvas, inner Frame) so
if you subclass this there is no built in way for the children to access
it. You need to provide the controller separately.
"""

def __init__(self, master, **kwargs):
Expand All @@ -46,7 +46,8 @@ def __init__(self, master, **kwargs):

self.vsb = tk.Scrollbar(self.outer, orient=tk.VERTICAL)
self.vsb.pack(fill=tk.Y, side=tk.RIGHT)
self.canvas = tk.Canvas(self.outer, highlightthickness=0, width=width, height=height, bg=bg)
self.canvas = tk.Canvas(self.outer, highlightthickness=0, width=width,
height=height, bg=bg)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.canvas['yscrollcommand'] = self.vsb.set
# mouse scroll does not seem to work with just "bind"; You have
Expand All @@ -59,16 +60,20 @@ def __init__(self, master, **kwargs):
self.vsb['command'] = self.canvas.yview

self.inner = ttk.Frame(self.canvas, bg=bg)
# pack the inner Frame into the Canvas with the topleft corner 4 pixels offset
self.canvas_window = self.canvas.create_window((4, 4), window=self.inner, anchor='nw',
# pack the inner Frame into the Canvas with the topleft corner 4
# pixels offset
self.canvas_window = self.canvas.create_window((4, 4),
window=self.inner,
anchor='nw',
tags='self.inner')
self.inner.bind("<Configure>", self._on_frame_configure)

self.outer_attr = set(dir(tk.Widget))

def __getattr__(self, item):
if item in self.outer_attr:
# geometry attributes etc (eg pack, destroy, tkraise) are passed on to self.outer
# geometry attributes etc (eg pack, destroy, tkraise) are passed
# on to self.outer
return getattr(self.outer, item)
else:
# all other attributes (_w, children, etc) are passed to self.inner
Expand All @@ -93,7 +98,7 @@ def _unbind_mouse(self, event=None):
self.canvas.unbind_all("<MouseWheel>")

def _on_mousewheel(self, event):
"""Linux uses event.num; Windows / Mac uses event.delta"""
# Linux uses event.num; Windows / Mac uses event.delta
if event.num == 4 or event.delta > 0:
self.canvas.yview_scroll(-1, "units")
elif event.num == 5 or event.delta < 0:
Expand Down
6 changes: 3 additions & 3 deletions rsc/spinOS.mplstyle
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ font.serif : Computer Modern Roman # Times Roman?

# figure options
axes.labelsize : medium
legend.fontsize : 8
legend.fontsize : 5
legend.frameon : False
figure.dpi : 200
figure.dpi : 150
axes.formatter.use_mathtext : True
figure.autolayout : True
figure.figsize : 7, 2.5
figure.figsize : 7, 2.9
lines.markersize : 4
lines.linewidth : 1.0

Expand Down

0 comments on commit 609dc62

Please sign in to comment.