<commit_before>#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
DICOM reader

Example:

$ dcmreaddata -d sample_data -o head.mat
"""

import sys
import os
import dicom
import numpy as np
from optparse import OptionParser
from scipy.io import savemat

import logging
logger = logging.getLogger(__name__)

def obj_from_file(filename='annotation.yaml', filetype='yaml'):
    """
    Read object from file
    """
    if filetype == 'yaml':
        import yaml
        f = open(filename, 'r')
        obj = yaml.load(f)
    elif filetype == 'pickle':
        import pickle
        f = open(filename, 'rb')
        obj = pickle.load(f)
    else:
        logger.error('Unknown filetype')

    f.close()

    return obj

def obj_to_file(obj, filename='annotation.yaml', filetype='yaml'):
    """
    Writes annotation in file
    """
    if filetype == 'yaml':
        import yaml
        f = open(filename, 'w')
        yaml.dump(obj, f)
    elif filetype == 'pickle':
        import pickle
        f = open(filename, 'wb')
        pickle.dump(obj, f, -1)
    else:
        logger.error('Unknown filetype')

    f.close

class DicomReader():
    def __init__(self, dirpath=None, initdir='.', qt_app=None):
        self.valid = False
        self.dirpath = dirpath
        self.dcmdir = self.get_dir()

        if len(self.dcmdir) > 0:
            self.valid = True
            counts, bins = self.status_dir()

            
            if len (bins) > 1:
                if qt_app is not None:
                    from PyQt4.QtGui import QInputDialog
                    sbins = ', '.join([str(ii) for ii in bins])
                    snstring, ok = QInputDialog.getText(qt_app, 'Select serie:',
                                                        'Select serie [%s]:' % sbins,
                                                        text='%d' % bins[0])
                else:
                    series_info = self.dcmdirstats()
                    self.print_series_info(series_info)
                    snstring = raw_input ('Select Serie: ')

                sn = int(snstring)

            else:
                sn = bins[0]

            self.dcmlist = self.get_sortedlist(SeriesNumber=sn)

    def validData(self):
        return self.valid
        
    def get_metaData(self, ifile=0):
        """
        Get metadata.
        Voxel size is obtained from PixelSpacing and difference of 
        SliceLocation of two neighboorhoding slices (first have index ifile).
        """

        data = dicom.read_file(self.dcmlist[ifile])
        try:
            data2 = dicom.read_file(self.dcmlist[ifile+1])
            voxeldepth = float(np.abs(data.SliceLocation - data2.SliceLocation ))
        except:
            logger.warning('Problem with voxel depth. Using SliceThickness')
            voxeldepth = float(data.SliceThickness)

        
        pixelsizemm = data.PixelSpacing<commit_msg>selectw series in DicomReader constructor<commit_after>#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
DICOM reader

Example:

$ dcmreaddata -d sample_data -o head.mat
"""

import sys
import os
import dicom
import numpy as np
from optparse import OptionParser
from scipy.io import savemat

import logging
logger = logging.getLogger(__name__)

def obj_from_file(filename='annotation.yaml', filetype='yaml'):
    """
    Read object from file
    """
    if filetype == 'yaml':
        import yaml
        f = open(filename, 'r')
        obj = yaml.load(f)
    elif filetype == 'pickle':
        import pickle
        f = open(filename, 'rb')
        obj = pickle.load(f)
    else:
        logger.error('Unknown filetype')

    f.close()

    return obj

def obj_to_file(obj, filename='annotation.yaml', filetype='yaml'):
    """
    Writes annotation in file
    """
    if filetype == 'yaml':
        import yaml
        f = open(filename, 'w')
        yaml.dump(obj, f)
    elif filetype == 'pickle':
        import pickle
        f = open(filename, 'wb')
        pickle.dump(obj, f, -1)
    else:
        logger.error('Unknown filetype')

    f.close

class DicomReader():
    def __init__(self, dirpath=None, initdir='.', qt_app=None, series_number = None):
        self.valid = False
        self.dirpath = dirpath
        self.dcmdir = self.get_dir()
        self.series_number = series_number

        if len(self.dcmdir) > 0:
            self.valid = True
            counts, bins = self.status_dir()

            
            if len (bins) > 1:
                if self.series_number == None:
                    if qt_app is not None:
                        from PyQt4.QtGui import QInputDialog
                        sbins = ', '.join([str(ii) for ii in bins])
                        snstring, ok = QInputDialog.getText(qt_app, 'Select serie:',
                                                            'Select serie [%s]:' % sbins,
                                                            text='%d' % bins[0])
                    else:
                        series_info = self.dcmdirstats()
                        self.print_series_info(series_info)
                        snstring = raw_input ('Select Serie: ')

                    sn = int(snstring)
                else:
                    sn = self.series_number

            else:
                sn = bins[0]

            self.dcmlist = self.get_sortedlist(SeriesNumber=sn)

    def validData(self):
        return self.valid
        
    def get_metaData(self, ifile=0):
        """
        Get metadata.
        Voxel size is obtained from PixelSpacing and difference of 
        SliceLocation of two neighboorhoding slices (first have index ifile).
        """

        data = dicom.read_file(self.dcmlist[ifile])
        try:
            data2 = dicom.read_file(self.dcmlist[ifile+1])
            voxeldepth = float(np.abs(data.SliceLocation - data2.SliceLocation ))
        except:
            logger.warning('Problem with voxel depth. Using SliceThickness')
            voxeldepth = float(data.SliceThickness)

        
        pixelsizemm = data.PixelSpacing
{'fraction_non_alphanumeric': 0.10384233189797946, 'fraction_numerical': 0.00364359059291156, 'mean_word_length': 1.6816163410301954, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3348968', 'n_tokens_mistral': 1807, 'n_tokens_neox': 1727, 'n_words': 437}