Skip to content
This repository has been archived by the owner on Nov 26, 2023. It is now read-only.

Commit

Permalink
replace print with logging
Browse files Browse the repository at this point in the history
  • Loading branch information
kushalkolar committed Mar 10, 2021
1 parent caa43c5 commit 0ed5651
Show file tree
Hide file tree
Showing 15 changed files with 106 additions and 40 deletions.
12 changes: 8 additions & 4 deletions mesmerize/analysis/data_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
from ..common.configuration import get_environment
from tqdm import tqdm
from functools import lru_cache
import logging


logger = logging.getLogger()


class _HistoryTraceExceptions(Exception):
Expand Down Expand Up @@ -591,14 +595,14 @@ def from_proj(cls, proj_path: str, dataframe: pd.DataFrame, sub_dataframe_name:
"""
df = dataframe.copy()
print('Collecting image metadata')
logger.info('Collecting image metadata')
tqdm().pandas()
df[['meta', 'stim_maps']] = df.progress_apply(lambda r: Transmission._load_files(proj_path, r), axis=1)

Transmission._load_imginfo.cache_clear()

try:
print('Collecting curve data')
logger.info('Collecting curve data')
df['_RAW_CURVE'] = df['ROI_State'].progress_apply(
lambda r: r['curve_data'][1]
)
Expand All @@ -608,7 +612,7 @@ def from_proj(cls, proj_path: str, dataframe: pd.DataFrame, sub_dataframe_name:
"the project dataframe where the curve data are missing")

try:
print('Collecting curve data')
logger.info('Collecting curve data')
df['_SPIKES'] = df['ROI_State'].progress_apply(
lambda r: r['spike_data'][1] if (r['spike_data'] is not None) else None
)
Expand All @@ -617,7 +621,7 @@ def from_proj(cls, proj_path: str, dataframe: pd.DataFrame, sub_dataframe_name:
warn('spikes or data not found, probably is probably from Mesmerize version < 0.2')

try:
print('Collecting dfof data')
logger.info('Collecting dfof data')
df['_DFOF'] = df['ROI_State'].progress_apply(
lambda r: r['dfof_data'][1] if (r['dfof_data'] is not None) else None
)
Expand Down
12 changes: 11 additions & 1 deletion mesmerize/common/qdialogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,17 @@ def fn(self, *args, **kwargs):
return func(self, *args, **kwargs)
except Exception as e:
tb = traceback.format_exc()
args = (self, title, msg + f'\n\n{e.__class__.__name__}: {e}\n\n{tb}', QMessageBox.Ok)
args = \
(
self,
title,
msg +\
f'\n\n'
f'{e.__class__.__name__}: {e}'
f'\n\n{tb}',
QMessageBox.Ok,
QMessageBox.Information
)
if help_func is not None and QMessageBox.warning(*args, QMessageBox.Help) == QMessageBox.Help:
help_func(e, tb)
else:
Expand Down
6 changes: 5 additions & 1 deletion mesmerize/pyqtgraphCore/flowchart/library/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
from ...widgets.KwargPlainTextEdit import KwargPlainTextEdit
from ....analysis import organize_dataframe_columns
# from PyQt5.QtWidgets import QLineEdit as LineEdit
import logging


logger = logging.getLogger()


def generateUi(opts):
Expand Down Expand Up @@ -181,7 +185,7 @@ def changed(self):
self.sigStateChanged.emit(self)
out = f"Processing node: {self.name()}\n"

sys.stdout.write(out)
logger.info(out)

def process(self, **kwargs):#In, display=True):
In = kwargs['In']
Expand Down
6 changes: 5 additions & 1 deletion mesmerize/viewer/core/viewer_work_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
from uuid import uuid4
from uuid import UUID as UUID_type
from typing import Optional, Tuple
import logging


logger = logging.getLogger()


class ViewerWorkEnv:
Expand Down Expand Up @@ -136,7 +140,7 @@ def clear(self):
self.origin_file = ''
self._saved = True
self.changed_items = []
print('Work environment dumped!')
logger.info('Work environment dumped!')

def restore_rois_from_states(self):
if (self.roi_manager is not None) and (self.roi_states is not None):
Expand Down
6 changes: 5 additions & 1 deletion mesmerize/viewer/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@
import pandas as pd
from typing import Optional, Union
from uuid import UUID as UUID_type
import logging


logger = logging.getLogger()

_custom_modules_dir = configuration.get_sys_config()['_MESMERIZE_CUSTOM_MODULES_DIR']
_custom_modules_package_name = os.path.basename(os.path.dirname(_custom_modules_dir))
Expand Down Expand Up @@ -344,7 +348,7 @@ def open_workEnv_editor(self):
try:
changes = objecteditor.oedit(self.vi.viewer.workEnv)
except:
print(traceback.format_exc())
logger.info((traceback.format_exc()))
# QtWidgets.QMessageBox.de(self, 'Unable to open work environment editor',
# 'The following error occured while trying to open the work environment editor:'
# '\n', traceback.format_exc())
Expand Down
11 changes: 8 additions & 3 deletions mesmerize/viewer/modules/batch_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,18 @@
elif IS_WINDOWS:
from win32api import TerminateProcess, CloseHandle

import logging


logger = logging.getLogger()


class ModuleGUI(QtWidgets.QWidget):
"""GUI for the Batch Manager"""
listwchanged = QtCore.pyqtSignal()

def __init__(self, parent, run_batch: list = None, testing: bool = False):
print('starting batch mananger')
logger.info('starting batch mananger')
QtWidgets.QWidget.__init__(self, parent)
self._testing = testing
self.ui = Ui_Form()
Expand Down Expand Up @@ -157,7 +162,7 @@ def init_batch(self, run_batch):
return
else:
path = run_batch[0]
print('Opening batch: ' + path)
logger.info('Opening batch: ' + path)

dfpath = os.path.join(path, 'dataframe.batch')
if os.path.isfile(dfpath):
Expand All @@ -171,7 +176,7 @@ def init_batch(self, run_batch):
self.set_workdir(True) # does a check to see if the workdir is writable upon batch manager initiation

if run_batch is not None:
print('Running from item ' + run_batch[1])
logger.info('Running from item ' + run_batch[1])
# ix = self.df.index[self.df['uuid'] == uuid.UUID(run_batch[1])]
# i = int(ix.to_native_types()[0])
i = self.get_item_index(run_batch[1])
Expand Down
6 changes: 5 additions & 1 deletion mesmerize/viewer/modules/caiman_dfof.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
from .roi_manager_modules.managers import ManagerCNMFROI, ManagerVolCNMF, ManagerVolMultiCNMFROI
import numpy as np
from tqdm import tqdm
import logging


logger = logging.getLogger()


# just need the function signature
Expand Down Expand Up @@ -162,7 +166,7 @@ def _set_data_multi2d(

dfofs = np.vstack(roi_manager.cnm_dfof)

print(
logger.info(
f"dfof shape:\t{dfofs.shape}\n"
f"roi_list len:\t{len(roi_manager.roi_list)}"
)
Expand Down
8 changes: 6 additions & 2 deletions mesmerize/viewer/modules/caiman_motion_correction.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
from math import ceil
from itertools import product
from typing import *
import logging


logger = logging.getLogger()


class ModuleGUI(QtWidgets.QDockWidget):
Expand Down Expand Up @@ -219,7 +223,7 @@ def view_output_projections(self):

proj = self.ui.comboBoxProjectionsOption.currentText()

print("Calculating projections, please wait...")
logger.info("Calculating projections, please wait...")

self.currrent_projections = Parallel(n_jobs=cpu_count(), verbose=5)(
delayed(ModuleGUI._get_projection)(proj, batch_path, item_uuid) for item_uuid in item_uuids
Expand All @@ -233,7 +237,7 @@ def plot_output_projections(self):
if self.currrent_projections is None:
raise AttributeError("Projections not calculated")

print("Plotting projections")
logger.info("Plotting projections")
if self.projections_plot_widget is None:
self.projections_plot_widget = MatplotlibWidget()
else:
Expand Down
6 changes: 5 additions & 1 deletion mesmerize/viewer/modules/cnmf.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
from shutil import copy
import os
from copy import deepcopy
import logging


logger = logging.getLogger()


class ModuleGUI(QtWidgets.QDockWidget):
Expand Down Expand Up @@ -197,7 +201,7 @@ def add_to_batch(self, params: dict = None) -> UUID:
return

if d['use_seeds']:
print("Copying component seed file")
logger.info("Copying component seed file")
copy(seed_path, os.path.join(batch_manager.batch_path, f'{u}.ain'))

self.vi.viewer.status_bar_label.showMessage('Done adding CNMF: ' + name + ' to batch!')
Expand Down
6 changes: 5 additions & 1 deletion mesmerize/viewer/modules/cnmf_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
from shutil import copy
import os
from copy import deepcopy
import logging


logger = logging.getLogger()


class ModuleGUI(QtWidgets.QDockWidget):
Expand Down Expand Up @@ -196,7 +200,7 @@ def add_to_batch(self, params: dict = None) -> UUID:
return

if d['use_seeds']:
print("Copying component seeds files")
logger.info("Copying component seeds files")
copy(seed_path, os.path.join(bm.batch_path, f'{u}.ain'))

if d['keep_memmap']:
Expand Down
10 changes: 7 additions & 3 deletions mesmerize/viewer/modules/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
import os
import skvideo.io
from .pytemplates.exporter_pytemplate import *
import logging


logger = logging.getLogger()


# adapted from https://github.com/ver228/tierpsy-tracker/blob/master/tierpsy/analysis/compress/compressVideo.py
Expand Down Expand Up @@ -81,7 +85,7 @@ def export(self):

seq = self.viewer.workEnv.imgdata.seq

print('Normalizing image for 8bit video output')
logger.info('Normalizing image for 8bit video output')
norm = normalize_image(seq, vmin, vmax)

# RGB LUT
Expand All @@ -103,10 +107,10 @@ def export(self):
'-filter:v': f"setpts={pts}*PTS",
'-vcodec': codec
}
print("Creating ffmpeg writer")
logger.info("Creating ffmpeg writer")
writer = skvideo.io.FFmpegWriter(f'{path}.{extn}', outputdict=output_params)

print("Writing video")
logger.info("Writing video")
for i in tqdm(range(norm.shape[2])):
frame = norm[:, :, i]
# use the LUT to create RGB pseudocolored image
Expand Down

0 comments on commit 0ed5651

Please sign in to comment.