Compare commits

22 Commits

Author SHA1 Message Date
SGCMarkus 7d0401d31d generate_plots: fix formatting and star count 2025-06-08 15:39:30 +02:00
SGCMarkus 95ce7917d9 Merge branch 'main' of https://gitea.markus.stammgruppe.eu/SGCMarkus/flaredetector 2025-06-08 15:38:40 +02:00
SGCMarkus ecf480c2de generate_latex_table: update printed tables 2025-06-08 15:37:40 +02:00
SGCMarkus 6514a6d125 Merge branch 'main' of https://gitea.markus.stammgruppe.eu/SGCMarkus/flaredetector 2025-05-31 16:54:33 +02:00
SGCMarkus b6c194cb6e CalcAllFlaresThread: set proper plot description sizes 2025-05-31 16:54:26 +02:00
SGCMarkus 9afe0993f6 generate_plots: fix flare number 2025-05-31 16:53:17 +02:00
SGCMarkus c1c58746e9 FlareSummaryPlotGUI: bring up to date 2025-05-31 16:52:41 +02:00
SGCMarkus c36c227e11 generate_plots: add option to adjust plot text sizes 2025-05-25 18:22:32 +02:00
SGCMarkus cd04b272ca fix period plot generation after rework 2025-05-25 14:24:42 +02:00
SGCMarkus a41edfcaa7 add latex table generation file 2025-05-21 17:59:23 +02:00
SGCMarkus 44d5da5975 generate_plots: fix multithreaded plot generation 2025-05-08 14:55:21 +02:00
SGCMarkus 7d574febcf generate_plots: use multiprocessing 2025-05-06 11:48:01 +02:00
SGCMarkus 43eb79bcc6 FlaredetectorWidget: properly label print 2025-05-06 11:46:45 +02:00
SGCMarkus 1fc9b82a1a generate plots: fix using wrong dataset for full period histogram 2025-04-27 21:22:04 +02:00
SGCMarkus 060cae2264 generate_plots: bring uptodate for changes, add max flare peak plots 2025-04-27 20:32:44 +02:00
SGCMarkus 54bd2e4bff add updated data package 2025-04-27 20:31:50 +02:00
SGCMarkus a7a816a892 CalcAllFlaresThread: add isValid flag to final output 2025-04-27 20:30:50 +02:00
SGCMarkus 4ad7974bb1 flaredetector: util: optimize: improve minima detection 2025-04-27 20:29:46 +02:00
SGCMarkus d930d7896b update code for optimized fold 2025-04-25 08:11:55 +02:00
SGCMarkus a13e32f35e astrodatagui: change default to pdcsap flux 2025-04-21 11:29:23 +02:00
SGCMarkus 10d1699d71 CalcAllFlaresThread: remove sap calculations, we dont use those 2025-04-11 13:48:21 +02:00
SGCMarkus c4a0dc766b Add UI option to optimize the lightcurve fold 2025-04-11 13:41:08 +02:00
11 changed files with 1278 additions and 777 deletions
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+84
View File
@@ -0,0 +1,84 @@
import pandas as pd
import numpy as np
from main.astrodatagui.db.StarsDB import StarDB
db: StarDB = StarDB.getInstance("stars.db")
starMainIDs = db.getAllStars()
resFull = []
resUsed = []
resUnused = []
fullData = pd.read_pickle("datav5.1.cff")
usedMstars = pd.read_csv("../large sized plots/2025-5-31-sine/M/M_starlist.csv", header=0, names=["StarName"])
usedKstars = pd.read_csv("../large sized plots/2025-5-31-sine/K/K_starlist.csv", header=0, names=["StarName"])
usedGstars = pd.read_csv("../large sized plots/2025-5-31-sine/G/G_starlist.csv", header=0, names=["StarName"])
usedFstars = pd.read_csv("../large sized plots/2025-5-31-sine/F/F_starlist.csv", header=0, names=["StarName"])
for mainID in starMainIDs:
altNames = db.getStarAltNames(mainID)
infos = db.getStarInfos(mainID)
kicName = "-"
ticName = "-"
spType = "-"
for name in altNames:
if name[0].startswith("TIC"):
ticName = name[0]
if name[0].startswith("KIC"):
kicName = name[0]
spType = infos["SpType"]
hasValidSineFit = fullData[(fullData["StarName"] == mainID) & (fullData["FitType"] == "sine")]["isValidFold"].any()
hasValidPolyFit = fullData[(fullData["StarName"] == mainID) & (fullData["FitType"] == "poly")]["isValidFold"].any()
hasValidLinearFit = fullData[(fullData["StarName"] == mainID) & (fullData["FitType"] == "linear")]["isValidFold"].any()
fitTypeString = []
if(hasValidSineFit): fitTypeString.append("sine")
if(hasValidPolyFit): fitTypeString.append("poly")
if(hasValidLinearFit): fitTypeString.append("linear")
fitTypeString = ', '.join(fitTypeString)
resFull.append({"MainID": mainID,
"Spectral Type": spType,
"TIC": ticName,
"KIC": kicName,
"Fit Types": fitTypeString})
if((usedMstars["StarName"] == mainID).any() or (usedKstars["StarName"] == mainID).any() or
(usedGstars["StarName"] == mainID).any() or (usedFstars["StarName"] == mainID).any()):
resUsed.append({"MainID": mainID,
"Spectral Type": spType,
"TIC": ticName,
"KIC": kicName,
"Fit Types": fitTypeString})
else:
resUnused.append({"MainID": mainID,
"Spectral Type": spType,
"TIC": ticName,
"KIC": kicName,
"Fit Types": fitTypeString})
resFull = pd.DataFrame(resFull)
resFull.sort_values(by=["Spectral Type", "MainID"])
resUsed = pd.DataFrame(resUsed)
resUsed.sort_values(by=["Spectral Type", "MainID"])
resUnused = pd.DataFrame(resUnused)
resUnused.sort_values(by=["Spectral Type", "MainID"])
for sptype in ["M", "K", "G", "F"]:
texFile = open(f"table_{sptype}_used.tex", "w")
tex = resUsed[resUsed["Spectral Type"].str.startswith(sptype)].sort_values(by=["Spectral Type", "MainID"]).to_latex(index=False)
texFile.write(tex)
texFile.close()
texFile = open(f"table_full.tex", "w")
tex = resFull.sort_values(by=["Spectral Type", "MainID"]).to_latex(index=False)
texFile.write(tex)
texFile.close()
texFile = open(f"table_unused.tex", "w")
tex = resUnused.sort_values(by=["Spectral Type", "MainID"]).to_latex(index=False)
texFile.write(tex)
texFile.close()
+631 -445
View File
File diff suppressed because it is too large Load Diff
+16 -2
View File
@@ -42,6 +42,9 @@ class AstrodataGUI(QtWidgets.QMainWindow):
self.cbPlotFlattenPlotEnable.stateChanged.connect(self.plotOptionsExclusiveCBChecked) self.cbPlotFlattenPlotEnable.stateChanged.connect(self.plotOptionsExclusiveCBChecked)
self.cbPlotFoldEnable.stateChanged.connect(self.plotOptionsExclusiveCBChecked) self.cbPlotFoldEnable.stateChanged.connect(self.plotOptionsExclusiveCBChecked)
self.cbPlotPeriodogramEnable.stateChanged.connect(self.plotOptionsExclusiveCBChecked) self.cbPlotPeriodogramEnable.stateChanged.connect(self.plotOptionsExclusiveCBChecked)
self.cbPlotFoldShowSpotModulation.stateChanged.connect(self.plotOptionsCBChecked)
self.gbPlotFoldOptimize.toggled.connect(self.plotOptionsCBChecked)
self.comboPlotFluxType.currentTextChanged.connect(self.plotOptionsComboBoxTextChanged) self.comboPlotFluxType.currentTextChanged.connect(self.plotOptionsComboBoxTextChanged)
self.comboPlotNormalizeUnit.currentTextChanged.connect(self.plotOptionsComboBoxTextChanged) self.comboPlotNormalizeUnit.currentTextChanged.connect(self.plotOptionsComboBoxTextChanged)
@@ -251,7 +254,10 @@ class AstrodataGUI(QtWidgets.QMainWindow):
self.flaredetectorPreview.setFoldedFitType(self.foldedFitType) self.flaredetectorPreview.setFoldedFitType(self.foldedFitType)
def updatePeriods(self, periods: list): def updatePeriods(self, periods: list):
self.edPlotFoldPeriod.setText(str(periods[0].value)) try:
self.edPlotFoldPeriod.setText(str(periods[0].value))
except:
self.edPlotFoldPeriod.setText(str(periods[0]))
def updateEpochPeriod(self, epoch: float): def updateEpochPeriod(self, epoch: float):
self.edPlotFoldEpochTime.setText(str(epoch)) self.edPlotFoldEpochTime.setText(str(epoch))
@@ -281,6 +287,11 @@ class AstrodataGUI(QtWidgets.QMainWindow):
case self.cbPlotBinEnable: case self.cbPlotBinEnable:
self.updateFlaredetectionWidgetBin() self.updateFlaredetectionWidgetBin()
case self.gbPlotFoldOptimize:
self.updateFlaredetectionWidgetFold()
case self.cbPlotFoldShowSpotModulation:
self.updateFlaredetectionWidgetFold()
def plotOptionsExclusiveCBChecked(self, state): def plotOptionsExclusiveCBChecked(self, state):
print(f"{self.sender().objectName()} is set to {state}") print(f"{self.sender().objectName()} is set to {state}")
if(state == QtCore.Qt.Checked): if(state == QtCore.Qt.Checked):
@@ -395,13 +406,16 @@ class AstrodataGUI(QtWidgets.QMainWindow):
def updateFlaredetectionWidgetFold(self): def updateFlaredetectionWidgetFold(self):
foldEnabled = self.cbPlotFoldEnable.isChecked() foldEnabled = self.cbPlotFoldEnable.isChecked()
optimizeEnabled = self.gbPlotFoldOptimize.isChecked()
showSpotModulationEnabled = self.cbPlotFoldShowSpotModulation.isChecked()
try: try:
period = float(self.edPlotFoldPeriod.text()) period = float(self.edPlotFoldPeriod.text())
epoch = float(self.edPlotFoldEpochTime.text()) epoch = float(self.edPlotFoldEpochTime.text())
except: except:
print(f"Invalid period/epoch detected, aborting") print(f"Invalid period/epoch detected, aborting")
return return
self.flaredetectorPreview.setFoldState(foldEnabled, period, epoch) self.flaredetectorPreview.setFoldState(foldEnabled, period, epoch, optimizeEnabled, showSpotModulationEnabled)
def updateFlaredetectionWidgetPeriodogram(self): def updateFlaredetectionWidgetPeriodogram(self):
periodogramEnabled = self.cbPlotPeriodogramEnable.isChecked() periodogramEnabled = self.cbPlotPeriodogramEnable.isChecked()
+66 -64
View File
@@ -15,6 +15,18 @@ from errno import EEXIST
from os import makedirs, path from os import makedirs, path
from datetime import datetime from datetime import datetime
SMALL_SIZE = 16
MEDIUM_SIZE = 18
BIGGER_SIZE = 20
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
def mkdir_p(mypath): def mkdir_p(mypath):
'''Creates a directory. equivalent to using mkdir -p on the command line''' '''Creates a directory. equivalent to using mkdir -p on the command line'''
@@ -42,38 +54,19 @@ def getFlareCount(filesDict):
mkdir_p(starFolder) mkdir_p(starFolder)
lc = lk.read(filesDict["FilePath"]) lc = lk.read(filesDict["FilePath"])
lc.flux = lc["sap_flux"]
lc.flux_err = lc["sap_flux_err"]
lc = lc.normalize()
sapPeaks, sapFits = calculateFlareFitsForLightcurve(lc.flatten())
sapValSec, sapTds = getTotalValidDataInSeconds(lc, "sap_flux")
sapPeriodogram = lc.to_periodogram()
sapPeakPeriod = sapPeriodogram.period[findMaxIndices(sapPeriodogram, num=4, distance=100, sortByHighest=True)[0]]
sapEpochTime = getEpochTime(lc)
sapFoldedLC = lc.fold(period=sapPeakPeriod, epoch_time=sapEpochTime)
sapPhase, sapSineFit, sapFitType = getFoldedBestFit(sapFoldedLC, fitType=filesDict["FitType"])
sapMinima, sapMaxima = getFoldedFitPeakValley(sapSineFit)
sapminPhasesBounds, sapmaxPhasesBounds = getPhaseRangesNearPeak((sapMinima, sapMaxima), sapPhase, returnPhaseValue=True)
sapFoldedPeaks = []
sapFoldedPeaksPhasePair = []
for peak in sapPeaks:
cycle, foldedIndex = convertStarndardIndexToFoldedIndex(sapFoldedLC, peak["StandardIndex"])
sapFoldedPeaks.append({"Cycle: ": cycle, "Index": foldedIndex})
sapFoldedPeaksPhasePair.append({"Phase": sapFoldedLC.phase[sapFoldedLC.cycle == cycle][foldedIndex], "Peak": peak})
lc.flux = lc["pdcsap_flux"] lc.flux = lc["pdcsap_flux"]
lc.flux_err = lc["pdcsap_flux_err"] lc.flux_err = lc["pdcsap_flux_err"]
lc = lc.normalize() lc = lc.normalize()
lc.plot() lc.plot()
plt.title(f"{starName} - normalized lightcurve") plt.title(f"{starName} - normalized lightcurve")
plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-lc.png") plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-lc.png", bbox_inches="tight")
plt.close() plt.close()
flattenedLc = lc.flatten() flattenedLc = lc.flatten()
flattenedLc.plot() flattenedLc.plot()
plt.title(f"{starName} - flattened lightcurve") plt.title(f"{starName} - flattened lightcurve")
plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-flattened_lc.png") plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-flattened_lc.png", bbox_inches="tight")
plt.close() plt.close()
pdcsapPeaks, pdcsapFits = calculateFlareFitsForLightcurve(flattenedLc, normalizedLC=lc) pdcsapPeaks, pdcsapFits = calculateFlareFitsForLightcurve(flattenedLc, normalizedLC=lc)
@@ -83,7 +76,7 @@ def getFlareCount(filesDict):
plt.plot(p["FlarePeakTime"].value, lc.flux[p["StandardIndex"]], "x", color="red") plt.plot(p["FlarePeakTime"].value, lc.flux[p["StandardIndex"]], "x", color="red")
plt.plot([], [], "x", color="red", label="Flare peaks") plt.plot([], [], "x", color="red", label="Flare peaks")
plt.legend() plt.legend()
plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-lc-marked_flares.png") plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-lc-marked_flares.png", bbox_inches="tight")
plt.close() plt.close()
flattenedLc.plot() flattenedLc.plot()
@@ -95,7 +88,7 @@ def getFlareCount(filesDict):
plt.plot(p["FlarePeakTime"].value, p["FlarePeak"], "x", color="red") plt.plot(p["FlarePeakTime"].value, p["FlarePeak"], "x", color="red")
plt.plot([], [], "x", color="red", label="Flare peaks") plt.plot([], [], "x", color="red", label="Flare peaks")
plt.legend() plt.legend()
plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-flattened_lc-marked_flares.png") plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-flattened_lc-marked_flares.png", bbox_inches="tight")
plt.close() plt.close()
pdcsapValSec, pdcsapTds = getTotalValidDataInSeconds(lc, "pdcsap_flux") pdcsapValSec, pdcsapTds = getTotalValidDataInSeconds(lc, "pdcsap_flux")
@@ -105,66 +98,75 @@ def getFlareCount(filesDict):
pdcsapPeriodogram.plot(view="period") pdcsapPeriodogram.plot(view="period")
plt.plot(pdcsapPeakPeriod, pdcsapPeriodogram.power[maxPeriodIndex], "x", color="red") plt.plot(pdcsapPeakPeriod, pdcsapPeriodogram.power[maxPeriodIndex], "x", color="red")
plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-periodogram-marked_max.png") plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-periodogram-marked_max.png", bbox_inches="tight")
plt.close() plt.close()
pdcsapEpochTime = getEpochTime(lc) #pdcsapEpochTime = getEpochTime(lc)
pdcsapFoldedLC = lc.fold(period=pdcsapPeakPeriod, epoch_time=pdcsapEpochTime) #pdcsapFoldedLC = lc.fold(period=pdcsapPeakPeriod, epoch_time=pdcsapEpochTime)
pdcsapPhase, pdcsapSineFit, pdcsapFitType = getFoldedBestFit(pdcsapFoldedLC, fitType=filesDict["FitType"]) #pdcsapPhase, pdcsapSineFit, pdcsapFitType = getFoldedBestFit(pdcsapFoldedLC, fitType=filesDict["FitType"])
pdcsapMinima, pdcsapMaxima = getFoldedFitPeakValley(pdcsapSineFit) optimizedFit = getOptimizedFold(lc.normalize(), filesDict["FitType"])
pdcsapminPhasesBounds, pdcsapmaxPhasesBounds = getPhaseRangesNearPeak((pdcsapMinima, pdcsapMaxima), pdcsapPhase, returnPhaseValue=True) #pdcsapMinima, pdcsapMaxima = getFoldedFitPeakValley(pdcsapSineFit)
pdcsapFoldedPeaks = [] #pdcsapminPhasesBounds, pdcsapmaxPhasesBounds = getPhaseRangesNearPeak((pdcsapMinima, pdcsapMaxima), pdcsapPhase, returnPhaseValue=True)
pdcsapFoldedPeaksPhasePair = [] pdcsapFoldedPeaks = []; pdcsapPeriodFoldedPeaks = []
pdcsapFoldedPeaksPhasePair = []; pdcsapPeriodFoldedPeaksPhasePair = []
pdcsapFoldedLC.scatter() optimizedFit["foldedLC"].scatter()
plt.title(f"{starName} - folded lightcurve") plt.title(f"{starName} - folded lightcurve")
plt.plot(pdcsapPhase, pdcsapSineFit, color="blue", label=f"{pdcsapFitType}-fit") plt.plot(optimizedFit["phase"], optimizedFit["fit"], color="blue", label=f"{optimizedFit['fitType']}-fit")
for peak in pdcsapPeaks: for peak in pdcsapPeaks:
cycle, foldedIndex = convertStarndardIndexToFoldedIndex(pdcsapFoldedLC, peak["StandardIndex"]) cycle, foldedIndex = convertStarndardIndexToFoldedIndex(optimizedFit["foldedLC"], peak["StandardIndex"])
pdcsapFoldedPeaks.append({"Cycle: ": cycle, "Index": foldedIndex}) pdcsapFoldedPeaks.append({"Cycle: ": cycle, "Index": foldedIndex})
pdcsapFoldedPeaksPhasePair.append({"Phase": pdcsapFoldedLC.phase[pdcsapFoldedLC.cycle == cycle][foldedIndex], "Peak": peak}) pdcsapFoldedPeaksPhasePair.append({"Phase": optimizedFit["foldedLC"].phase[optimizedFit["foldedLC"].cycle == cycle][foldedIndex], "Peak": peak})
plt.plot(pdcsapFoldedLC.phase[pdcsapFoldedLC.cycle == cycle][foldedIndex].value, plt.plot(optimizedFit["foldedLC"].phase[optimizedFit["foldedLC"].cycle == cycle][foldedIndex].value,
pdcsapFoldedLC.flux[pdcsapFoldedLC.cycle == cycle][foldedIndex], "x", color="red") optimizedFit["foldedLC"].flux[optimizedFit["foldedLC"].cycle == cycle][foldedIndex], "x", color="red")
plt.plot([], [], "x", color="red", label="Flare peaks") plt.plot([], [], "x", color="red", label="Flare peaks")
plt.legend() plt.legend()
plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-foldedLC-marked_fit_flares.png") plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-foldedLC-marked_fit_flares.png", bbox_inches="tight")
plt.close() plt.close()
if(optimizedFit["periodFoldedLC"] is not None):
optimizedFit["periodFoldedLC"].scatter()
plt.title(f"{starName} - folded lightcurve")
plt.plot(optimizedFit["periodFoldedPhase"], optimizedFit["periodFoldedFit"], color="blue", label=f"{optimizedFit['fitType']}-fit")
for peak in pdcsapPeaks:
cycle, foldedIndex = convertStarndardIndexToFoldedIndex(optimizedFit["periodFoldedLC"], peak["StandardIndex"])
pdcsapPeriodFoldedPeaks.append({"Cycle: ": cycle, "Index": foldedIndex})
pdcsapPeriodFoldedPeaksPhasePair.append({"Phase": optimizedFit["periodFoldedLC"].phase[optimizedFit["periodFoldedLC"].cycle == cycle][foldedIndex], "Peak": peak})
plt.plot(optimizedFit["periodFoldedLC"].phase[optimizedFit["periodFoldedLC"].cycle == cycle][foldedIndex].value,
optimizedFit["periodFoldedLC"].flux[optimizedFit["periodFoldedLC"].cycle == cycle][foldedIndex], "x", color="red")
plt.plot([], [], "x", color="red", label="Flare peaks")
plt.legend()
plt.savefig(f"{starFolder}/{starNameR}_{source}-{sequence}-periodFoldedLC-marked_fit_flares.png", bbox_inches="tight")
plt.close()
filesDict["sapPeaks"] = sapPeaks
filesDict["sapPeaksCount"] = len(sapPeaks)
filesDict["sapFits"] = sapFits
filesDict["sapValidTimespans"] = sapTds
filesDict["sapValidSeconds"] = sapValSec
filesDict["sapFoldedCycle"] = sapFoldedLC.cycle
#filesDict["sapFoldedPhase"] = sapFoldedLC.phase.value
#filesDict["sapFoldedFitPhase"] = sapPhase
filesDict["sapFoldedFitPhaseStarEnd"] = (sapFoldedLC.phase.value[0], sapFoldedLC.phase.value[-1])
filesDict["sapFoldedPeaksPhasePair"] = sapFoldedPeaksPhasePair
filesDict["sapPeriod"] = sapPeakPeriod.value
filesDict["sapPeriodMinima"] = sapMinima
filesDict["sapPeriodMinimaBoundaries"] = sapminPhasesBounds
filesDict["sapPeriodMaxima"] = sapMaxima
filesDict["sapPeriodMaximaBoundaries"] = sapmaxPhasesBounds
filesDict["pdcsapPeaks"] = pdcsapPeaks filesDict["pdcsapPeaks"] = pdcsapPeaks
filesDict["pdcsapPeaksCount"] = len(pdcsapPeaks) filesDict["pdcsapPeaksCount"] = len(pdcsapPeaks)
filesDict["pdcsapFits"] = pdcsapFits filesDict["pdcsapFits"] = pdcsapFits
filesDict["pdcsapValidTimespans"] = pdcsapTds filesDict["pdcsapValidTimespans"] = pdcsapTds
filesDict["pdcsapValidSeconds"] = pdcsapValSec filesDict["pdcsapValidSeconds"] = pdcsapValSec
filesDict["pdcsapFoldedCycle"] = sapFoldedLC.cycle filesDict["pdcsapFoldedEpoch"] = optimizedFit["epoch"]
#filesDict["pdcsapFoldedPhase"] = sapFoldedLC.phase.value filesDict["pdcsapFoldedCycle"] = optimizedFit["foldedLC"].cycle
#filesDict["pdcsapFoldedFitPhase"] = pdcsapPhase filesDict["pdcsapFoldedPhase"] = optimizedFit["foldedLC"].phase.value
filesDict["pdcsapFoldedFitPhaseStarEnd"] = (pdcsapFoldedLC.phase.value[0], pdcsapFoldedLC.phase.value[-1]) filesDict["pdcsapFoldedFitPhase"] = optimizedFit["phase"]
filesDict["pdcsapFoldedFit"] = optimizedFit["fit"]
filesDict["pdcsapFoldedFitPhaseStarEnd"] = (optimizedFit["foldedLC"].phase.value[0], optimizedFit["foldedLC"].phase.value[-1])
filesDict["pdcsapFoldedPeaksPhasePair"] = pdcsapFoldedPeaksPhasePair filesDict["pdcsapFoldedPeaksPhasePair"] = pdcsapFoldedPeaksPhasePair
filesDict["pdcsapPeriod"] = pdcsapPeakPeriod.value filesDict["pdcsapPeriod"] = optimizedFit["Period"]
filesDict["pdcsapPeriodMinima"] = pdcsapMinima filesDict["pdcsapSpotModulation"] = optimizedFit["SpotModulation"]
filesDict["pdcsapPeriodMinimaBoundaries"] = pdcsapminPhasesBounds filesDict['FitType'] = optimizedFit["fitType"]
filesDict["pdcsapPeriodMaxima"] = pdcsapMaxima
filesDict["pdcsapPeriodMaximaBoundaries"] = pdcsapmaxPhasesBounds filesDict["pdcsapPeriodFoldedCycle"] = optimizedFit["periodFoldedLC"].cycle if optimizedFit["periodFoldedLC"] is not None else None
filesDict["pdcsapPeriodFoldedPhase"] = optimizedFit["periodFoldedLC"].phase.value if optimizedFit["periodFoldedLC"] is not None else None
filesDict["pdcsapPeriodFoldedFitPhase"] = optimizedFit["periodFoldedPhase"]
filesDict["pdcsapPeriodFoldedFit"] = optimizedFit["periodFoldedFit"]
filesDict["pdcsapPeriodFoldedFitPhaseStarEnd"] = (optimizedFit["periodFoldedLC"].phase.value[0], optimizedFit["periodFoldedLC"].phase.value[-1]) if optimizedFit["periodFoldedLC"] is not None else (None, None)
filesDict["pdcsapPeriodFoldedPeaksPhasePair"] = pdcsapPeriodFoldedPeaksPhasePair
filesDict['periodFitType'] = optimizedFit["periodFitType"]
filesDict["isValidFold"] = optimizedFit["isValid"]
csvFile = open(f"{starFolder}/{starNameR}_{source}-{sequence}.csv", "a") csvFile = open(f"{starFolder}/{starNameR}_{source}-{sequence}.csv", "a")
csvFile.write("StarName,Spectral Type,Rotational Velocity,Rotenional Velocity Unit,Distance,Distance Unit,Source,Sequence,File Path,Initial folded Fit Type,Used folded Fit Type") csvFile.write("StarName,Spectral Type,Rotational Velocity,Rotenional Velocity Unit,Distance,Distance Unit,Source,Sequence,File Path,Initial folded Fit Type,Used folded Fit Type")
csvFile.write(f"{filesDict['StarName']},{filesDict['SpType']},{filesDict['RotVel']},{filesDict['RotVelUnit']},{filesDict['Distance']},{filesDict['DistanceUnit']},{filesDict['Source']},{filesDict['Sequence']},{filesDict['FilePath']},{filesDict['FitType']},{pdcsapFitType}") csvFile.write(f"{filesDict['StarName']},{filesDict['SpType']},{filesDict['RotVel']},{filesDict['RotVelUnit']},{filesDict['Distance']},{filesDict['DistanceUnit']},{filesDict['Source']},{filesDict['Sequence']},{filesDict['FilePath']},{filesDict['FitType']},{optimizedFit['fitType']}")
csvFile.close() csvFile.close()
del lc del lc
print(f"Finished {filesDict['StarName']}, {filesDict['Sequence']}") print(f"Finished {filesDict['StarName']}, {filesDict['Sequence']}")
+66 -164
View File
@@ -120,7 +120,7 @@ class FlareSummaryPlotGUI(QWidget):
self.cbSpTypeUnknown.setChecked(False) self.cbSpTypeUnknown.setChecked(False)
self.cbShowSAP = QCheckBox("SAP") self.cbShowSAP = QCheckBox("SAP")
self.cbShowSAP.setChecked(True) self.cbShowSAP.setChecked(False)
self.cbShowPDCSAP = QCheckBox("PDCSAP") self.cbShowPDCSAP = QCheckBox("PDCSAP")
self.cbShowPDCSAP.setChecked(True) self.cbShowPDCSAP.setChecked(True)
@@ -129,12 +129,12 @@ class FlareSummaryPlotGUI(QWidget):
self.buttonGridLayout.addWidget(self.btShowFlaresPerStar, 0, 2) self.buttonGridLayout.addWidget(self.btShowFlaresPerStar, 0, 2)
self.buttonGridLayout.addWidget(self.btShowFlaresPerStarNormalized, 0, 3) self.buttonGridLayout.addWidget(self.btShowFlaresPerStarNormalized, 0, 3)
self.buttonGridLayout.addWidget(self.btShowPeriods, 0, 4) self.buttonGridLayout.addWidget(self.btShowPeriods, 0, 4)
self.buttonGridLayout.addWidget(self.btNumMinimaMaxima, 0, 5) #self.buttonGridLayout.addWidget(self.btNumMinimaMaxima, 0, 5)
self.buttonGridLayout.addWidget(self.btNumMinimaMaximaNorm, 0, 6) #self.buttonGridLayout.addWidget(self.btNumMinimaMaximaNorm, 0, 6)
self.buttonGridLayout.addWidget(self.btShowFlaresInMinimaMaxima, 0, 7) #self.buttonGridLayout.addWidget(self.btShowFlaresInMinimaMaxima, 0, 7)
self.buttonGridLayout.addWidget(self.btShowFlaresInMinimaMaximaPerMinimaMaxima, 0, 8) #self.buttonGridLayout.addWidget(self.btShowFlaresInMinimaMaximaPerMinimaMaxima, 0, 8)
self.buttonGridLayout.addWidget(self.btShowFlaresBinnedOnPhase, 0, 9) #self.buttonGridLayout.addWidget(self.btShowFlaresBinnedOnPhase, 0, 9)
self.buttonGridLayout.addWidget(self.textNumBins, 0, 10) #self.buttonGridLayout.addWidget(self.textNumBins, 0, 10)
self.buttonGridLayout.addWidget(QLabel("Sources: "), 1, 0) self.buttonGridLayout.addWidget(QLabel("Sources: "), 1, 0)
self.buttonGridLayout.addWidget(self.cbKepler, 1, 1) self.buttonGridLayout.addWidget(self.cbKepler, 1, 1)
@@ -149,7 +149,7 @@ class FlareSummaryPlotGUI(QWidget):
self.buttonGridLayout.addWidget(self.cbSpTypeF, 2, 4) self.buttonGridLayout.addWidget(self.cbSpTypeF, 2, 4)
#self.buttonGridLayout.addWidget(self.cbSpTypeUnknown, 2, 6) #self.buttonGridLayout.addWidget(self.cbSpTypeUnknown, 2, 6)
self.buttonGridLayout.addWidget(self.cbShowSAP, 3, 0) #self.buttonGridLayout.addWidget(self.cbShowSAP, 3, 0)
self.buttonGridLayout.addWidget(self.cbShowPDCSAP, 3, 1) self.buttonGridLayout.addWidget(self.cbShowPDCSAP, 3, 1)
self.mainLayout.addLayout(self.buttonGridLayout) self.mainLayout.addLayout(self.buttonGridLayout)
@@ -243,27 +243,7 @@ class FlareSummaryPlotGUI(QWidget):
self.figure.canvas.draw_idle() self.figure.canvas.draw_idle()
def btShowFlaresPerStarClicked(self): def btShowFlaresPerStarClicked(self):
data = self.starFLareDictList.drop(columns=['Distance', data = self.starFLareDictList
'DistanceUnit',
'FilePath',
'RotVel',
'RotVelUnit',
'Sequence',
'pdcsapFits',
'pdcsapPeaks',
'sapFits',
'sapPeaks',
'sapPeriod',
'sapPeriodMinima',
'sapPeriodMinimaBoundaries',
'sapPeriodMaxima',
'sapPeriodMaximaBoundaries',
'pdcsapValidTimespans',
'pdcsapPeriod',
'pdcsapPeriodMinima',
'pdcsapPeriodMinimaBoundaries',
'pdcsapPeriodMaxima',
'pdcsapPeriodMaximaBoundaries'])
showSourceFilter = np.full(len(data), False) showSourceFilter = np.full(len(data), False)
@@ -277,9 +257,14 @@ class FlareSummaryPlotGUI(QWidget):
showTESS = data["Source"] == "TESS" showTESS = data["Source"] == "TESS"
showSourceFilter |= showTESS showSourceFilter |= showTESS
aggDic = {}
if(self.cbShowSAP.isChecked()):
aggDic["sapPeaksCount"] = "sum"
if(self.cbShowPDCSAP.isChecked()):
aggDic["pdcsapPeaksCount"] = "sum"
data = data[showSourceFilter].groupby(["StarName", "SpType"], data = data[showSourceFilter].groupby(["StarName", "SpType"],
as_index=False).agg({"sapPeaksCount": "sum", as_index=False).agg(aggDic)
"pdcsapPeaksCount": "sum"})
x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int) x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int)
if(self.cbSpTypeL.isChecked()): if(self.cbSpTypeL.isChecked()):
@@ -345,28 +330,7 @@ class FlareSummaryPlotGUI(QWidget):
self.figure.canvas.draw_idle() self.figure.canvas.draw_idle()
def btShowFlaresPerStarNormalizedClicked(self): def btShowFlaresPerStarNormalizedClicked(self):
data = self.starFLareDictList.drop(columns=['Distance', data = self.starFLareDictList
'DistanceUnit',
'FilePath',
'RotVel',
'RotVelUnit',
'Sequence',
'pdcsapFits',
'pdcsapPeaks',
'sapFits',
'sapValidTimespans',
'sapPeaks',
'sapPeriod',
'sapPeriodMinima',
'sapPeriodMinimaBoundaries',
'sapPeriodMaxima',
'sapPeriodMaximaBoundaries',
'pdcsapValidTimespans',
'pdcsapPeriod',
'pdcsapPeriodMinima',
'pdcsapPeriodMinimaBoundaries',
'pdcsapPeriodMaxima',
'pdcsapPeriodMaximaBoundaries'])
showSourceFilter = np.full(len(data), False) showSourceFilter = np.full(len(data), False)
@@ -380,11 +344,16 @@ class FlareSummaryPlotGUI(QWidget):
showTESS = data["Source"] == "TESS" showTESS = data["Source"] == "TESS"
showSourceFilter |= showTESS showSourceFilter |= showTESS
aggDic = {}
if(self.cbShowSAP.isChecked()):
aggDic["sapPeaksCount"] = "sum"
aggDic["sapValidSeconds"] = "sum"
if(self.cbShowPDCSAP.isChecked()):
aggDic["pdcsapPeaksCount"] = "sum"
aggDic["pdcsapValidSeconds"] = "sum"
data = data[showSourceFilter].groupby(["StarName", "SpType"], data = data[showSourceFilter].groupby(["StarName", "SpType"],
as_index=False).agg({"sapPeaksCount": "sum", as_index=False).agg(aggDic)
"pdcsapPeaksCount": "sum",
"sapValidSeconds": "sum",
"pdcsapValidSeconds": "sum"})
x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int) x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int)
if(self.cbSpTypeL.isChecked()): if(self.cbSpTypeL.isChecked()):
@@ -462,30 +431,7 @@ class FlareSummaryPlotGUI(QWidget):
self.figure.canvas.draw_idle() self.figure.canvas.draw_idle()
def btShowPeriodsClicked(self): def btShowPeriodsClicked(self):
data = self.starFLareDictList.drop(columns=['Distance', data = self.starFLareDictList
'DistanceUnit',
'FilePath',
'RotVel',
'RotVelUnit',
'Sequence',
'pdcsapFits',
'pdcsapPeaks',
'sapFits',
'sapValidTimespans',
'sapPeaks',
'sapPeriodMinima',
'sapPeriodMinimaBoundaries',
'sapPeriodMaxima',
'sapPeriodMaximaBoundaries',
'pdcsapValidTimespans',
'pdcsapPeriodMinima',
'pdcsapPeriodMinimaBoundaries',
'pdcsapPeriodMaxima',
'pdcsapPeriodMaximaBoundaries',
'sapPeaksCount',
'pdcsapPeaksCount',
'sapValidSeconds',
'pdcsapValidSeconds'])
showSourceFilter = np.full(len(data), False) showSourceFilter = np.full(len(data), False)
@@ -499,11 +445,14 @@ class FlareSummaryPlotGUI(QWidget):
showTESS = data["Source"] == "TESS" showTESS = data["Source"] == "TESS"
showSourceFilter |= showTESS showSourceFilter |= showTESS
print(data["sapPeriod"]) aggDic = {}
if(self.cbShowSAP.isChecked()):
aggDic["sapPeriod"] = "sum"
if(self.cbShowPDCSAP.isChecked()):
aggDic["pdcsapPeriod"] = "sum"
data = data[showSourceFilter].groupby(["StarName", "SpType"], data = data[showSourceFilter].groupby(["StarName", "SpType"],
as_index=False).agg({"sapPeriod": "mean", as_index=False).agg(aggDic)
"pdcsapPeriod": "mean"})
x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int) x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int)
if(self.cbSpTypeL.isChecked()): if(self.cbSpTypeL.isChecked()):
@@ -582,20 +531,7 @@ class FlareSummaryPlotGUI(QWidget):
pass pass
def btShowNumMinimaMaximaClicked(self): def btShowNumMinimaMaximaClicked(self):
data = self.starFLareDictList.drop(columns=['Distance', data = self.starFLareDictList
'DistanceUnit',
'FilePath',
'RotVel',
'RotVelUnit',
'Sequence',
'pdcsapFits',
'sapFits',
'sapValidTimespans',
'pdcsapValidTimespans',
'sapPeaksCount',
'pdcsapPeaksCount',
'sapValidSeconds',
'pdcsapValidSeconds'])
showSourceFilter = np.full(len(data), False) showSourceFilter = np.full(len(data), False)
@@ -609,13 +545,15 @@ class FlareSummaryPlotGUI(QWidget):
showTESS = data["Source"] == "TESS" showTESS = data["Source"] == "TESS"
showSourceFilter |= showTESS showSourceFilter |= showTESS
print(data["sapPeriod"]) aggDic = {}
if(self.cbShowSAP.isChecked()):
aggDic["sapPeriodMinima"] = "sum"
aggDic["sapPeriodMaxima"] = "sum"
if(self.cbShowPDCSAP.isChecked()):
aggDic["pdcsapPeriodMinima"] = "sum"
aggDic["pdcsapPeriodMaxima"] = "sum"
data = data[showSourceFilter].groupby(["StarName", "SpType"], data = data[showSourceFilter].groupby(["StarName", "SpType"],
as_index=False).agg({"sapPeriodMinima": sumArrayLengths, as_index=False).agg(aggDic)
"sapPeriodMaxima": sumArrayLengths,
"pdcsapPeriodMinima": sumArrayLengths,
"pdcsapPeriodMaxima": sumArrayLengths})
x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int) x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int)
if(self.cbSpTypeL.isChecked()): if(self.cbSpTypeL.isChecked()):
@@ -718,20 +656,7 @@ class FlareSummaryPlotGUI(QWidget):
pass pass
def btShowNumMinimaMaximaNormalizedClicked(self): def btShowNumMinimaMaximaNormalizedClicked(self):
data = self.starFLareDictList.drop(columns=['Distance', data = self.starFLareDictList
'DistanceUnit',
'FilePath',
'RotVel',
'RotVelUnit',
'Sequence',
'pdcsapFits',
'sapFits',
'sapValidTimespans',
'pdcsapValidTimespans',
'sapPeaksCount',
'pdcsapPeaksCount',
'sapValidSeconds',
'pdcsapValidSeconds'])
showSourceFilter = np.full(len(data), False) showSourceFilter = np.full(len(data), False)
@@ -745,13 +670,15 @@ class FlareSummaryPlotGUI(QWidget):
showTESS = data["Source"] == "TESS" showTESS = data["Source"] == "TESS"
showSourceFilter |= showTESS showSourceFilter |= showTESS
print(data["sapPeriod"]) aggDic = {}
if(self.cbShowSAP.isChecked()):
aggDic["sapPeriodMinima"] = "sum"
aggDic["sapPeriodMaxima"] = "sum"
if(self.cbShowPDCSAP.isChecked()):
aggDic["pdcsapPeriodMinima"] = "sum"
aggDic["pdcsapPeriodMaxima"] = "sum"
data = data[showSourceFilter].groupby(["StarName", "SpType"], data = data[showSourceFilter].groupby(["StarName", "SpType"],
as_index=False).agg({"sapPeriodMinima": sumArrayLengthsNorm, as_index=False).agg(aggDic)
"sapPeriodMaxima": sumArrayLengthsNorm,
"pdcsapPeriodMinima": sumArrayLengthsNorm,
"pdcsapPeriodMaxima": sumArrayLengthsNorm})
x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int) x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int)
if(self.cbSpTypeL.isChecked()): if(self.cbSpTypeL.isChecked()):
@@ -854,20 +781,7 @@ class FlareSummaryPlotGUI(QWidget):
pass pass
def btShowFlaresInMinimaMaximaClicked(self): def btShowFlaresInMinimaMaximaClicked(self):
data = self.starFLareDictList.drop(columns=['Distance', data = self.starFLareDictList
'DistanceUnit',
'FilePath',
'RotVel',
'RotVelUnit',
'Sequence',
'pdcsapFits',
'sapFits',
'sapValidTimespans',
'pdcsapValidTimespans',
'sapPeaksCount',
'pdcsapPeaksCount',
'sapValidSeconds',
'pdcsapValidSeconds'])
showSourceFilter = np.full(len(data), False) showSourceFilter = np.full(len(data), False)
@@ -881,8 +795,6 @@ class FlareSummaryPlotGUI(QWidget):
showTESS = data["Source"] == "TESS" showTESS = data["Source"] == "TESS"
showSourceFilter |= showTESS showSourceFilter |= showTESS
print(data["sapPeriod"])
finalData = [] finalData = []
#data = data[showSourceFilter].groupby(["StarName", "SpType"], #data = data[showSourceFilter].groupby(["StarName", "SpType"],
# as_index=False).agg({"sapPeriod": "mean", # as_index=False).agg({"sapPeriod": "mean",
@@ -1011,20 +923,7 @@ class FlareSummaryPlotGUI(QWidget):
pass pass
def btShowFlaresInMinimaMaximaPerMinimaMaximaClicked(self): def btShowFlaresInMinimaMaximaPerMinimaMaximaClicked(self):
data = self.starFLareDictList.drop(columns=['Distance', data = self.starFLareDictList
'DistanceUnit',
'FilePath',
'RotVel',
'RotVelUnit',
'Sequence',
'pdcsapFits',
'sapFits',
'sapValidTimespans',
'pdcsapValidTimespans',
'sapPeaksCount',
'pdcsapPeaksCount',
'sapValidSeconds',
'pdcsapValidSeconds'])
showSourceFilter = np.full(len(data), False) showSourceFilter = np.full(len(data), False)
@@ -1038,8 +937,6 @@ class FlareSummaryPlotGUI(QWidget):
showTESS = data["Source"] == "TESS" showTESS = data["Source"] == "TESS"
showSourceFilter |= showTESS showSourceFilter |= showTESS
print(data["sapPeriod"])
finalData = [] finalData = []
for ind, row in data[showSourceFilter].reset_index().iterrows(): for ind, row in data[showSourceFilter].reset_index().iterrows():
minimaCountSAP = getNumFlaresInBounds(row["sapFoldedPeaksPhasePair"], minimaCountSAP = getNumFlaresInBounds(row["sapFoldedPeaksPhasePair"],
@@ -1056,15 +953,20 @@ class FlareSummaryPlotGUI(QWidget):
"minimaCountPDCSAP": minimaCountPDCSAP, "maximaCountPDCSAP": maximaCountPDCSAP, "minimaCountPDCSAP": minimaCountPDCSAP, "maximaCountPDCSAP": maximaCountPDCSAP,
"minimasPDCSAP": len(row["pdcsapPeriodMinima"]), "maximasPDCSAP": len(row["pdcsapPeriodMaxima"])}) "minimasPDCSAP": len(row["pdcsapPeriodMinima"]), "maximasPDCSAP": len(row["pdcsapPeriodMaxima"])})
aggDic = {}
if(self.cbShowSAP.isChecked()):
aggDic["minimaCountSAP"] = "sum"
aggDic["maximaCountSAP"] = "sum"
aggDic["minimasSAP"] = "sum"
aggDic["maximasSAP"] = "sum"
if(self.cbShowPDCSAP.isChecked()):
aggDic["minimaCountPDCSAP"] = "sum"
aggDic["maximaCountPDCSAP"] = "sum"
aggDic["minimasPDCSAP"] = "sum"
aggDic["maximasPDCSAP"] = "sum"
data = pd.DataFrame(finalData).groupby(["StarName", "SpType"], data = pd.DataFrame(finalData).groupby(["StarName", "SpType"],
as_index=False).agg({"minimaCountSAP": "sum", as_index=False).agg(aggDic)
"maximaCountSAP": "sum",
"minimasSAP": "sum",
"maximasSAP": "sum",
"minimaCountPDCSAP": "sum",
"maximaCountPDCSAP": "sum",
"minimasPDCSAP": "sum",
"maximasPDCSAP": "sum"})
x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int) x = np.arange(start=1, stop=len(data)+1, step=1, dtype=int)
if(self.cbSpTypeL.isChecked()): if(self.cbSpTypeL.isChecked()):
+262 -78
View File
@@ -174,6 +174,21 @@
<string>Sequences/Target Table ID</string> <string>Sequences/Target Table ID</string>
</property> </property>
<layout class="QHBoxLayout" name="horizontalLayout_5"> <layout class="QHBoxLayout" name="horizontalLayout_5">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item> <item>
<layout class="QVBoxLayout" name="verticalLayout_2"> <layout class="QVBoxLayout" name="verticalLayout_2">
<item> <item>
@@ -255,12 +270,39 @@
<string>Plot options</string> <string>Plot options</string>
</property> </property>
<layout class="QVBoxLayout" name="verticalLayout_6"> <layout class="QVBoxLayout" name="verticalLayout_6">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>9</number>
</property>
<property name="topMargin">
<number>9</number>
</property>
<property name="rightMargin">
<number>9</number>
</property>
<property name="bottomMargin">
<number>9</number>
</property>
<item> <item>
<layout class="QHBoxLayout" name="horizontalLayout_4"> <layout class="QHBoxLayout" name="horizontalLayout_4">
<item> <item>
<layout class="QVBoxLayout" name="verticalLayout_10"> <layout class="QVBoxLayout" name="verticalLayout_10">
<item> <item>
<layout class="QGridLayout" name="gridLayout_11"> <layout class="QGridLayout" name="gridLayout_11">
<property name="leftMargin">
<number>9</number>
</property>
<property name="topMargin">
<number>9</number>
</property>
<property name="rightMargin">
<number>9</number>
</property>
<property name="bottomMargin">
<number>9</number>
</property>
<item row="0" column="0"> <item row="0" column="0">
<widget class="QLabel" name="label_19"> <widget class="QLabel" name="label_19">
<property name="sizePolicy"> <property name="sizePolicy">
@@ -284,12 +326,12 @@
</property> </property>
<item> <item>
<property name="text"> <property name="text">
<string>sap_flux</string> <string>pdcsap_flux</string>
</property> </property>
</item> </item>
<item> <item>
<property name="text"> <property name="text">
<string>pdcsap_flux</string> <string>sap_flux</string>
</property> </property>
</item> </item>
</widget> </widget>
@@ -346,6 +388,21 @@
<string>Normalize</string> <string>Normalize</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_6"> <layout class="QGridLayout" name="gridLayout_6">
<property name="leftMargin">
<number>9</number>
</property>
<property name="topMargin">
<number>9</number>
</property>
<property name="rightMargin">
<number>9</number>
</property>
<property name="bottomMargin">
<number>9</number>
</property>
<property name="spacing">
<number>6</number>
</property>
<item row="0" column="1"> <item row="0" column="1">
<widget class="QLabel" name="label_12"> <widget class="QLabel" name="label_12">
<property name="text"> <property name="text">
@@ -412,6 +469,21 @@
<string>Remove Outliers</string> <string>Remove Outliers</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_8"> <layout class="QGridLayout" name="gridLayout_8">
<property name="leftMargin">
<number>9</number>
</property>
<property name="topMargin">
<number>9</number>
</property>
<property name="rightMargin">
<number>9</number>
</property>
<property name="bottomMargin">
<number>9</number>
</property>
<property name="spacing">
<number>6</number>
</property>
<item row="0" column="0"> <item row="0" column="0">
<widget class="QCheckBox" name="cbPlotRemoveOutliersEnable"> <widget class="QCheckBox" name="cbPlotRemoveOutliersEnable">
<property name="text"> <property name="text">
@@ -464,6 +536,21 @@
<string>Remove nans/infs</string> <string>Remove nans/infs</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_10"> <layout class="QGridLayout" name="gridLayout_10">
<property name="leftMargin">
<number>9</number>
</property>
<property name="topMargin">
<number>9</number>
</property>
<property name="rightMargin">
<number>9</number>
</property>
<property name="bottomMargin">
<number>9</number>
</property>
<property name="spacing">
<number>6</number>
</property>
<item row="0" column="0"> <item row="0" column="0">
<widget class="QCheckBox" name="cbPlotRemoveNansEnable"> <widget class="QCheckBox" name="cbPlotRemoveNansEnable">
<property name="sizePolicy"> <property name="sizePolicy">
@@ -522,6 +609,21 @@
<bool>false</bool> <bool>false</bool>
</property> </property>
<layout class="QGridLayout" name="gridLayout_5"> <layout class="QGridLayout" name="gridLayout_5">
<property name="leftMargin">
<number>9</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>9</number>
</property>
<property name="bottomMargin">
<number>9</number>
</property>
<property name="spacing">
<number>6</number>
</property>
<item row="0" column="1"> <item row="0" column="1">
<widget class="QLabel" name="label_11"> <widget class="QLabel" name="label_11">
<property name="text"> <property name="text">
@@ -625,6 +727,21 @@
<string>Flatten</string> <string>Flatten</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_7"> <layout class="QGridLayout" name="gridLayout_7">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<property name="spacing">
<number>0</number>
</property>
<item row="0" column="1"> <item row="0" column="1">
<widget class="QLabel" name="label_14"> <widget class="QLabel" name="label_14">
<property name="text"> <property name="text">
@@ -706,84 +823,31 @@
<bool>false</bool> <bool>false</bool>
</property> </property>
<layout class="QGridLayout" name="gridLayout_3"> <layout class="QGridLayout" name="gridLayout_3">
<property name="leftMargin">
<number>9</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>9</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<property name="spacing">
<number>6</number>
</property>
<item row="0" column="0"> <item row="0" column="0">
<layout class="QGridLayout" name="gridLayout_2"> <layout class="QGridLayout" name="gridLayout_2">
<item row="2" column="0"> <item row="0" column="1">
<widget class="QLabel" name="label_8"> <widget class="QLabel" name="label_10">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>60</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>60</width>
<height>16777215</height>
</size>
</property>
<property name="text"> <property name="text">
<string>Epoch Time: </string> <string>Enable</string>
</property> </property>
</widget> </widget>
</item> </item>
<item row="1" column="0"> <item row="4" column="1">
<widget class="QLabel" name="label_7">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>60</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>60</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Period: </string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="edPlotFoldPeriod">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>60</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>60</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>1</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLineEdit" name="edPlotFoldEpochTime"> <widget class="QLineEdit" name="edPlotFoldEpochTime">
<property name="sizePolicy"> <property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed"> <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@@ -808,6 +872,31 @@
</property> </property>
</widget> </widget>
</item> </item>
<item row="3" column="0">
<widget class="QLabel" name="label_7">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>60</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>60</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Period: </string>
</property>
</widget>
</item>
<item row="0" column="0"> <item row="0" column="0">
<widget class="QCheckBox" name="cbPlotFoldEnable"> <widget class="QCheckBox" name="cbPlotFoldEnable">
<property name="text"> <property name="text">
@@ -815,11 +904,76 @@
</property> </property>
</widget> </widget>
</item> </item>
<item row="0" column="1"> <item row="3" column="1">
<widget class="QLabel" name="label_10"> <widget class="QLineEdit" name="edPlotFoldPeriod">
<property name="text"> <property name="sizePolicy">
<string>Enable</string> <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property> </property>
<property name="minimumSize">
<size>
<width>60</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>60</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>1</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_8">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>60</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>60</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Epoch Time: </string>
</property>
</widget>
</item>
<item row="1" column="0" colspan="2" alignment="Qt::AlignHCenter|Qt::AlignVCenter">
<widget class="QGroupBox" name="gbPlotFoldOptimize">
<property name="title">
<string>Optimize</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>false</bool>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_8">
<item>
<widget class="QCheckBox" name="cbPlotFoldShowSpotModulation">
<property name="text">
<string>Show Spot Modulation</string>
</property>
</widget>
</item>
</layout>
</widget> </widget>
</item> </item>
</layout> </layout>
@@ -856,6 +1010,21 @@
<string>Periodogram</string> <string>Periodogram</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_9"> <layout class="QGridLayout" name="gridLayout_9">
<property name="leftMargin">
<number>9</number>
</property>
<property name="topMargin">
<number>9</number>
</property>
<property name="rightMargin">
<number>9</number>
</property>
<property name="bottomMargin">
<number>9</number>
</property>
<property name="spacing">
<number>6</number>
</property>
<item row="0" column="1"> <item row="0" column="1">
<widget class="QLabel" name="label_20"> <widget class="QLabel" name="label_20">
<property name="text"> <property name="text">
@@ -966,6 +1135,21 @@
<string>Star infos</string> <string>Star infos</string>
</property> </property>
<layout class="QHBoxLayout" name="horizontalLayout_6"> <layout class="QHBoxLayout" name="horizontalLayout_6">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item> <item>
<layout class="QGridLayout" name="gridLayout"> <layout class="QGridLayout" name="gridLayout">
<item row="1" column="0"> <item row="1" column="0">
+41 -15
View File
@@ -51,14 +51,14 @@ class FlaredetectorWidget(QtWidgets.QWidget):
self.periodogramInfoGroupBox.setSizePolicy(sp) self.periodogramInfoGroupBox.setSizePolicy(sp)
self.mainLayout.addWidget(self.periodogramInfoGroupBox) self.mainLayout.addWidget(self.periodogramInfoGroupBox)
self.fluxType = "sap_flux" self.fluxType = "pdcsap_flux"
self.fluxErrType = "sap_flux_err" self.fluxErrType = "pdcsap_flux_err"
self.NormalizeState = {"Enabled": False, "Scale": "unscaled"} self.NormalizeState = {"Enabled": False, "Scale": "unscaled"}
self.RemoveOutliersState = {"Enabled": False, "Sigma": 5.0} self.RemoveOutliersState = {"Enabled": False, "Sigma": 5.0}
self.RemoveNansState = {"Enabled": False} self.RemoveNansState = {"Enabled": False}
self.BinState = {"Enabled": False, "Size": None} self.BinState = {"Enabled": False, "Size": None}
self.FlattenState = {"Enabled": False, "WindowLength": 101, "PolynomialOrder": 2} self.FlattenState = {"Enabled": False, "WindowLength": 101, "PolynomialOrder": 2}
self.FoldState = {"Enabled": False, "Period": 1, "EpochTime": 0} self.FoldState = {"Enabled": False, "Period": 1, "EpochTime": 0, "Optimize": False, "spotModulation": False}
self.PeriodogramState = {"Enabled": False, "Method": "lombscargle", "View": "frequency"} self.PeriodogramState = {"Enabled": False, "Method": "lombscargle", "View": "frequency"}
self.ShowQualityState = {"Enabled": False} self.ShowQualityState = {"Enabled": False}
@@ -156,8 +156,10 @@ class FlaredetectorWidget(QtWidgets.QWidget):
self.updateFit() self.updateFit()
self.updatePlot() self.updatePlot()
def setFoldState(self, enabled: bool, period: float, epoch: float): def setFoldState(self, enabled: bool, period: float, epoch: float, optimize: bool, spotModulation: bool):
self.FoldState["Enabled"] = enabled self.FoldState["Enabled"] = enabled
self.FoldState["Optimize"] = optimize
self.FoldState["SpotModulation"] = spotModulation
if(period < 0): if(period < 0):
print(f"Negative period detected, setting default 1") print(f"Negative period detected, setting default 1")
period = 1 period = 1
@@ -246,8 +248,28 @@ class FlaredetectorWidget(QtWidgets.QWidget):
lc = self.currentFlattenLC lc = self.currentFlattenLC
label += " - flattened" label += " - flattened"
if(self.FoldState["Enabled"]): if(self.FoldState["Enabled"]):
lc = lc.fold(period=self.FoldState["Period"], if(self.FoldState["Optimize"]):
epoch_time=self.FoldState["EpochTime"]) optimizedFold = getOptimizedFold(lc.normalize(), self.foldedFitType)
if(self.FoldState["SpotModulation"]):
lc = optimizedFold["foldedLC"]
self.periodsCalculated.emit([optimizedFold["SpotModulation"]])
foldOptimizePhase = optimizedFold["phase"]
foldOptimizeFit = optimizedFold["fit"]
elif(not self.FoldState["SpotModulation"] and optimizedFold["periodFoldedLC"] is not None):
lc = optimizedFold["periodFoldedLC"]
self.periodsCalculated.emit([optimizedFold["Period"]])
foldOptimizePhase = optimizedFold["periodFoldedPhase"]
foldOptimizeFit = optimizedFold["periodFoldedFit"]
else:
lc = optimizedFold["foldedLC"]
self.periodsCalculated.emit([optimizedFold["SpotModulation"]])
foldOptimizePhase = optimizedFold["phase"]
foldOptimizeFit = optimizedFold["fit"]
print("SpotModulation", self.FoldState["SpotModulation"])
self.epochCalculated.emit(optimizedFold["epoch"])
else:
lc = lc.fold(period=self.FoldState["Period"],
epoch_time=self.FoldState["EpochTime"])
label += " - folded" label += " - folded"
if(self.PeriodogramState["Enabled"]): if(self.PeriodogramState["Enabled"]):
lc = lc.to_periodogram(method=self.PeriodogramState["Method"]) lc = lc.to_periodogram(method=self.PeriodogramState["Method"])
@@ -271,15 +293,19 @@ class FlaredetectorWidget(QtWidgets.QWidget):
cycle, foldedIndex = convertStarndardIndexToFoldedIndex(lc, peak["StandardIndex"]) cycle, foldedIndex = convertStarndardIndexToFoldedIndex(lc, peak["StandardIndex"])
self.figureAxis.plot(lc.phase[lc.cycle == cycle][foldedIndex].value, self.figureAxis.plot(lc.phase[lc.cycle == cycle][foldedIndex].value,
lc.flux[lc.cycle == cycle][foldedIndex], "x", color="red") lc.flux[lc.cycle == cycle][foldedIndex], "x", color="red")
try: if(self.FoldState["Optimize"]):
phase, sineFit, _ = getFoldedBestFit(lc, fitType=self.foldedFitType) self.figureAxis.plot(foldOptimizePhase, foldOptimizeFit, color="red")
self.figureAxis.plot(phase, sineFit, color="red")
print(phase, sineFit) else:
minPhasesBoundsIndices, maxPhasesBoundsIndices = getPhaseRangesNearPeak(getFoldedFitPeakValley(sineFit), phase) try:
plotPhaseRangesNearPeak((minPhasesBoundsIndices, maxPhasesBoundsIndices), phase, ax=self.figureAxis) phase, sineFit, _ = getFoldedBestFit(lc, fitType=self.foldedFitType)
except Exception as e: self.figureAxis.plot(phase, sineFit, color="red")
print("Failed to get fit") print(phase, sineFit)
print(e) #minPhasesBoundsIndices, maxPhasesBoundsIndices = getPhaseRangesNearPeak(getFoldedFitPeakValley(sineFit), phase)
#plotPhaseRangesNearPeak((minPhasesBoundsIndices, maxPhasesBoundsIndices), phase, ax=self.figureAxis)
except Exception as e:
print("Failed to get fit")
print(e)
elif(self.PeriodogramState["Enabled"]): elif(self.PeriodogramState["Enabled"]):
lc.plot(label=label, ax=self.figureAxis, view=self.PeriodogramState["View"]) lc.plot(label=label, ax=self.figureAxis, view=self.PeriodogramState["View"])
if(self.PeriodogramState["View"] == "period"): if(self.PeriodogramState["View"] == "period"):
+104 -1
View File
@@ -1,7 +1,8 @@
import numpy as np import numpy as np
from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import Polynomial
from scipy.signal import find_peaks, argrelextrema from scipy.signal import find_peaks, argrelextrema, periodogram
from scipy.optimize import curve_fit from scipy.optimize import curve_fit
import itertools
def findMaxIndices(lc, num=3, distance=100, height=(None, None), sortByHighest=False): def findMaxIndices(lc, num=3, distance=100, height=(None, None), sortByHighest=False):
if(hasattr(lc, "power")): if(hasattr(lc, "power")):
@@ -391,3 +392,105 @@ def plotPhaseRangesNearPeak(indices, phase, ax=None):
def getEpochTime(lc): def getEpochTime(lc):
return lc.time.value[argrelextrema(np.asarray(lc.flux.value), np.less, order=500)[0]][0] return lc.time.value[argrelextrema(np.asarray(lc.flux.value), np.less, order=500)[0]][0]
def getOptimizedFold(normalizedLC, preferedFoldedFitType):
isValid = False
periodogramLS = normalizedLC.to_periodogram(method="lombscargle")
periodogramBLS = normalizedLC.to_periodogram(method="boxleastsquares")
lsPeriods = periodogramLS.period[findMaxIndices(periodogramLS, num=4, distance=100, sortByHighest=True)]
blsPeriods = periodogramBLS.period[findMaxIndices(periodogramBLS, num=4, distance=100, sortByHighest=True)]
period = -100
spotModulation = -100
for lsP, blsP in itertools.product(lsPeriods, blsPeriods):
if(abs(lsP.value - blsP.value) < max(lsP.value, blsP.value)*0.05):
period = np.average([lsP.value, blsP.value])
print("Period found: ", period)
break
else:
print("No matching LS/BLS peak -> use highest LS")
period = lsPeriods[0].value
spotModulation = period
epoch = getEpochTime(normalizedLC)
tries = 0
periodFoldedLC = None
periodFoldedPhase = None
periodFoldedFit = None
periodFitType = None
while(tries < 30):
tries += 1
foldedLC = normalizedLC.fold(period=spotModulation, epoch_time=epoch)
phase, fit, fitType = getFoldedBestFit(foldedLC, fitType=preferedFoldedFitType)
phaseLength = abs(phase[0]) + abs(phase[-1])
fitMaximaArgs = argrelextrema(np.asarray(fit), np.greater)[0]
spotModulationBefore = spotModulation
if(len(fitMaximaArgs) > 1):
print("fitMaximaArgs > 1: ", fitMaximaArgs)
print(fitMaximaArgs[0], len(phase)*0.1, fitMaximaArgs[1], len(phase)*0.9)
print(fitMaximaArgs[0] > len(phase)*0.1, fitMaximaArgs[1] < len(phase)*0.9)
if(len(fitMaximaArgs) == 2 and fitMaximaArgs[0] > len(phase)*0.1 and fitMaximaArgs[1] < len(phase)*0.9):
halfPeriod = period/2
for lsP, blsP in zip(lsPeriods, blsPeriods):
if(abs(lsP.value - halfPeriod) < period*0.05):
spotModulation = lsP.value
print("lsP.value", lsP.value)
break
elif(abs(blsP.value - halfPeriod) < period*0.05):
spotModulation = blsP.value
print("blsP.value", blsP.value)
break
else:
print("2 fit peaks, but no spot modulation")
if(spotModulationBefore != spotModulation):
periodFoldedLC = foldedLC
periodFoldedPhase = phase
periodFoldedFit = fit
periodFitType = fitType
foldedLC = normalizedLC.fold(period=spotModulation, epoch_time=epoch)
phase, fit, fitType = getFoldedBestFit(foldedLC, fitType=preferedFoldedFitType)
phaseLength = abs(phase[0]) + abs(phase[-1])
fitMinimaArgs = argrelextrema(np.asarray(fit), np.less)[0]
fitMinima = phase[0]
fitMinimaArg = 0
newFitMinimaArgs = []
for args in fitMinimaArgs:
print("Phases: ", fit[0], fit[len(phase)-1], fit[args])
if(fit[0] < fit[args] and fit[len(fit)-1] < fit[args]):
print("Found new minima")
newFitMinimaArgs.append(0)
newFitMinimaArgs.append(args)
newFitMinimaArgs = set(newFitMinimaArgs)
print(newFitMinimaArgs)
for args in newFitMinimaArgs:
if(abs(phase[args]) < abs(fitMinima) and fit[args] < fit[fitMinimaArg]):
fitMinima = phase[args]
fitMinimaArg = args
if(abs(fitMinima) < phaseLength*0.01):
isValid = True
break;
else:
epoch += fitMinima
return {"Period": period,
"SpotModulation": spotModulation,
"lsPeriods": lsPeriods,
"blsPeriods": blsPeriods,
"foldedLC": foldedLC,
"phase": phase,
"fit": fit,
"periodFoldedLC": periodFoldedLC,
"periodFoldedPhase": periodFoldedPhase,
"periodFoldedFit": periodFoldedFit,
"periodFitType": periodFitType,
"fitType": fitType,
"epoch": epoch,
"isValid": isValid}
+5 -5
View File
@@ -58,11 +58,11 @@ nonKicStars = pd.DataFrame(nonKicStars)
print(kicNames) print(kicNames)
#print(nonKicStars) #print(nonKicStars)
KeplerM = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/M-type-superflares.csv") #KeplerM = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/M-type-superflares.csv")
KeplerK = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/K-type-superflares.csv") #KeplerK = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/K-type-superflares.csv")
KeplerG = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/G-type-superflares.csv") #KeplerG = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/G-type-superflares.csv")
KeplerF = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/F-type-superflares.csv") #KeplerF = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/F-type-superflares.csv")
KeplerA = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/A-type-superflares.csv") #KeplerA = pd.read_csv("D:/Masterthesis/ressources/akthukair_AFD/Results/A-type-superflares.csv")
#kicBasedSP = [] #kicBasedSP = []
#for fullKIC in kicNames["kicName"].values: #for fullKIC in kicNames["kicName"].values: