Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add logging capability #133

Merged
merged 1 commit into from
Dec 14, 2021
Merged
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: 1 addition & 2 deletions QtBrainChartGUI/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
import os, sys
from QtBrainChartGUI.mainwindow import MainWindow


def main():
print("inside main")
parser = argparse.ArgumentParser(description='iSTAGING Data Visualization and Preparation')
parser.add_argument('--data_file', type=str, help='Data file containing data frame.', default=None, required=False)
parser.add_argument('--harmonization_model_file', type=str, help='Harmonization model file.', default=None, required=False)
Expand All @@ -29,6 +27,7 @@ def main():
harmonizationModelFile=harmonization_model_file,
SPAREModelFile=SPARE_model_file)
mw.show()

sys.exit(app.exec_())

if __name__ == '__main__':
Expand Down
34 changes: 34 additions & 0 deletions QtBrainChartGUI/core/iStagingLogger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# This Python file uses the following encoding: utf-8
"""
contact: software@cbica.upenn.edu
Author: Ashish Singh
Copyright (c) 2018 University of Pennsylvania. All rights reserved.
Use of this source code is governed by license located in license file: https://github.com/CBICA/iSTAGING-Tools/blob/main/LICENSE
"""

import logging
import sys, os
from logging.handlers import TimedRotatingFileHandler
#FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(message)s")
FORMATTER = logging.Formatter("[%(asctime)s — %(name)s — %(filename)s: Line:%(lineno)s — %(funcName)20s() ] — %(levelname)s — %(message)s")
LOG_FILE = os.path.expanduser(os.path.join('~', '.NiBAx','NiBAx.log'))

def get_console_handler():
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(FORMATTER)
return console_handler

def get_file_handler():
if not os.path.exists(os.path.dirname(LOG_FILE)):
os.makedirs(os.path.dirname(LOG_FILE))
file_handler = TimedRotatingFileHandler(LOG_FILE, when='midnight')
file_handler.setFormatter(FORMATTER)
return file_handler

def get_logger(logger_name):
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG) # better to have too much log than not enough
logger.addHandler(get_console_handler())
logger.addHandler(get_file_handler())
logger.propagate = False
return logger
4 changes: 4 additions & 0 deletions QtBrainChartGUI/core/model/datamodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
import joblib
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5 import QtCore
from QtBrainChartGUI.core import iStagingLogger

logger = iStagingLogger.get_logger(__name__)

class DataModel(QObject):
"""This class holds the data model."""
Expand Down Expand Up @@ -68,6 +71,7 @@ def GetMUSEDictionaries(self):
def SetData(self,d):
"""Setter for data"""
self.data = d
logger.info('Data changed in datamodel')
self.data_changed.emit()


Expand Down
13 changes: 12 additions & 1 deletion QtBrainChartGUI/mainwindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,17 @@
from PyQt5.QtWidgets import QAction
import pandas as pd
from QtBrainChartGUI.core.baseplugin import BasePlugin
from QtBrainChartGUI.core import iStagingLogger

logger = iStagingLogger.get_logger(__name__)

class MainWindow(QtWidgets.QMainWindow):
def __init__(self, dataFile=None, harmonizationModelFile=None, SPAREModelFile=None):
super(MainWindow,self).__init__()

#log
logger.info('New NiBAx session starting...')

self.SetupUi()
self.SetupConnections()

Expand All @@ -43,7 +50,8 @@ def __init__(self, dataFile=None, harmonizationModelFile=None, SPAREModelFile=No
po.datamodel = self.datamodel
po.SetupConnections()
self.Plugins[plugin.name] = po
print("plugins: ", plugin.name)

logger.info("Loaded Plugins: %s", self.Plugins.keys())

#organize plugins in order:Data -> Characteristics -> Age Trends -> Harmonization -> SPARE-*
for num in range(len(self.Plugins)):
Expand Down Expand Up @@ -71,6 +79,9 @@ def __init__(self, dataFile=None, harmonizationModelFile=None, SPAREModelFile=No
self.ui.actionHelp.setMenuRole(QAction.NoRole)
self.ui.actionAbout.setMenuRole(QAction.NoRole)

def __del__(self):
logger.info('NiBAx session ending...')

def SetupConnections(self):
self.actionAbout.triggered.connect(self.OnAboutClicked)
self.actionHelp.triggered.connect(self.OnHelpClicked)
Expand Down
8 changes: 5 additions & 3 deletions QtBrainChartGUI/plugins/data/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
from QtBrainChartGUI.plugins.data.dataio import DataIO
import dtale
from QtBrainChartGUI.core.baseplugin import BasePlugin
from QtBrainChartGUI.core import iStagingLogger

logger = iStagingLogger.get_logger(__name__)

class PandasModel(QtCore.QAbstractTableModel):
def __init__(self, data, parent=None):
Expand Down Expand Up @@ -89,17 +92,16 @@ def PopulateTable(self):
model = PandasModel(self.datamodel.data.head(20))
self.dataView.setModel(model)



def OnDataChanged(self):
self.PopulateTable()


def ReadData(self,filename):
#read input data
dio = DataIO()
d = dio.ReadPickleFile(filename)

logger.info('New data read from file: %s', filename)

#also read MUSE dictionary
MUSEDictNAMEtoID, MUSEDictIDtoNAME = dio.ReadMUSEDictionary()
self.datamodel.SetMUSEDictionaries(MUSEDictNAMEtoID, MUSEDictIDtoNAME)
Expand Down
9 changes: 7 additions & 2 deletions QtBrainChartGUI/plugins/data/dataio.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
import pandas as pd
import joblib
import os, sys
from QtBrainChartGUI.core import iStagingLogger

logger = iStagingLogger.get_logger(__name__)

class DataIO:
def __init__(self):
Expand All @@ -24,15 +27,17 @@ def SavePickleFile(self,data,filename):

def ReadMUSEDictionary(self):
# Load MUSE dictionary file
MUSEDict = os.path.join(os.path.dirname(__file__), 'MUSE_ROI_Dictionary.csv')
MUSEDict = pd.read_csv(MUSEDict)
MUSEDictfile = os.path.join(os.path.dirname(__file__), 'MUSE_ROI_Dictionary.csv')
MUSEDict = pd.read_csv(MUSEDictfile)

# Create lookup from name to ID and vice-versa
# e.g. name to ID: Hippocampus right -> MUSE_Volume_48
MUSEDictNAMEtoID = dict(zip(MUSEDict['ROI_NAME'], MUSEDict['ROI_COL']))
# e.g. ID to name; MUSE_Volume_48 -> Hippocampus right
MUSEDictIDtoNAME = dict(zip(MUSEDict['ROI_COL'], MUSEDict['ROI_NAME']))

logger.info('MUSE dictionary read from file: %s', MUSEDictfile)

return MUSEDictNAMEtoID, MUSEDictIDtoNAME


Expand Down