Ejemplo n.º 1
0
 def __init__(self, filename):
     self.filename = filename
     self.dt = DictTools()
     ft = FileTools()
     self.file = ft.processFile(filename)
     self.transition_matrix = {}
     self.first_words = {}
     self.second_words = {}
Ejemplo n.º 2
0
    def save_log(self):

        if self.display_length is None:
            self.clear()
            raise LookupError("Please display sequence first!")

        if self.file_name is None:
            self._get_file_name()

        if self.keep_display == True:
            self.file_name += '-complete'
        elif self.keep_display == False:
            self.file_name += '-incomplete'

        # set up log object
        directory = os.path.join(self.log_dir, 'visual_display_log')
        if not (os.path.isdir(directory)):
            os.makedirs(directory)

        logFile = dict(self.seq_log)
        displayLog = dict(self.__dict__)
        displayLog.pop('seq_log')
        displayLog.pop('sequence')
        logFile.update({'presentation': displayLog})

        file_name = self.file_name + ".pkl"

        # generate full log dictionary
        path = os.path.join(directory, file_name)
        ft.saveFile(path, logFile)
        print("\nLog file generated successfully. Log file path: ")
        print('{}'.format(path))
        if self.is_save_sequence:
            tf.imsave(os.path.join(directory, self.file_name + '.tif'),
                      self.sequence.astype(np.float32))
            print('\nSequence file generated successfully. File path: ')
            print('{}'.format(os.path.join(directory,
                                           self.file_name + '.tif')))

        backupFileFolder = self._get_backup_folder()
        if backupFileFolder is not None:
            if not (os.path.isdir(backupFileFolder)):
                os.makedirs(backupFileFolder)
            backupFilePath = os.path.join(backupFileFolder, file_name)
            ft.saveFile(backupFilePath, logFile)

            if self.is_save_sequence:
                tf.imsave(
                    os.path.join(backupFileFolder, self.file_name + '.tif'),
                    self.sequence.astype(np.float32))
            print(
                "\nBackup log file generated successfully. Backup log file path: "
            )
            print('{}'.format(backupFilePath))
        else:
            print("\nDid not find backup path, no backup was saved.")
    def save_log(self):

        if self.display_length is None:
            self.clear()
            raise LookupError("Please display sequence first!")

        if self.file_name is None:
            self._get_file_name()

        if self.keep_display == True:
            self.file_name += '-complete'
        elif self.keep_display == False:
            self.file_name += '-incomplete'

        # set up log object
        directory = os.path.join(self.log_dir, 'visual_display_log')
        if not (os.path.isdir(directory)):
            os.makedirs(directory)

        logFile = dict(self.seq_log)
        displayLog = dict(self.__dict__)
        displayLog.pop('seq_log')
        displayLog.pop('sequence')
        logFile.update({'presentation': displayLog})

        file_name = self.file_name + ".pkl"

        # generate full log dictionary
        path = os.path.join(directory, file_name)
        ft.saveFile(path, logFile)
        print("\nLog file generated successfully. Log file path: ")
        print('{}'.format(path))
        if self.is_save_sequence:
            tf.imsave(os.path.join(directory, self.file_name + '.tif'),
                      self.sequence.astype(np.float32))
            print('\nSequence file generated successfully. File path: ')
            print('{}'.format(os.path.join(directory, self.file_name + '.tif')))

        backupFileFolder = self._get_backup_folder()
        if backupFileFolder is not None:
            if not (os.path.isdir(backupFileFolder)):
                os.makedirs(backupFileFolder)
            backupFilePath = os.path.join(backupFileFolder, file_name)
            ft.saveFile(backupFilePath, logFile)

            if self.is_save_sequence:
                tf.imsave(os.path.join(backupFileFolder, self.file_name + '.tif'),
                          self.sequence.astype(np.float32))
            print("\nBackup log file generated successfully. Backup log file path: ")
            print('{}'.format(backupFilePath))
        else:
            print("\nDid not find backup path, no backup was saved.")
Ejemplo n.º 4
0
 def save(self, data, fullname='../data/temp/temp.npy', log=True):
     fullname = FT.newname(fullname)
     np.save(fullname, data)
     self._temp_list.append(fullname)
     if log:
         with open(self._log, 'a') as f:
             f.write(time.strftime('%X') + " <> SAVED: " + fullname + '\n')
    def __init__(self, log_path):

        self.log_dict = ft.loadFile(log_path)

        if not self.log_dict['presentation']['is_by_index']:
            raise NotImplementedError('The visual stimuli display should be indexed.')

        self.check_integrity()
Ejemplo n.º 6
0
    def __init__(self, log_path):

        self.log_dict = ft.loadFile(log_path)

        if not self.log_dict['presentation']['is_by_index']:
            raise NotImplementedError('The visual stimuli display should be indexed.')

        self.check_integrity()
Ejemplo n.º 7
0
def start(chano,
          stc,
          name='test',
          path='../data/',
          exposures=[10, 100, 1000, 10000],
          mov={'shift': [0, 1, 2, 3, 4, 5]}):

    normalized_name = os.path.normpath(path + '/' + name)
    path, name, extension = FileTools.splitname(normalized_name)
    base_name = os.path.normpath(path + "/" + name)

    mask = 'Exposure: {:6d} Theta: {:6.2f} Shift: {:6.2f} Phi: {:6.2f}'

    time.sleep(5)
    print("\n\n")

    try:
        for motor, sweep in mov.items():
            for x in sweep:

                setattr(chano, motor, x)
                for exposure in exposures:
                    stc.exposure = exposure
                    image = stc.capture()
                    newname = FileTools.newname(base_name + '.npz')

                    np.savez(newname,
                             image=image,
                             exposure=exposure,
                             chanosat_pos=chano.pos)

                    print(
                        mask.format(exposure, chano.theta, chano.shift,
                                    chano.phi))

                    time_now = time.gmtime(time.time())
                    print("\n" + time.strftime("%X", time_now), end='')
                    print(' - Saved as: {}'.format(os.path.relpath(newname)))
                    time.sleep(1)

    except:
        print('\n\nUnexpected error.'
              ' Trying to reset chanosat to zero position\n\n')
        chano.pos = [0, 0, 0]
        time.sleep(1)
        raise
Ejemplo n.º 8
0
    def save_log(self):

        if self.display_length is None:
            self.clear()
            raise LookupError, "Please display sequence first!"

        if self.file_name is None:
            self._get_file_name()

        if self.keep_display == True:
            self.file_name += '-complete'
        elif self.keep_display == False:
            self.file_name += '-incomplete'

        #set up log object
        directory = self.log_dir + '\sequence_display_log'
        if not (os.path.isdir(directory)):
            os.makedirs(directory)

        logFile = dict(self.seq_log)
        displayLog = dict(self.__dict__)
        displayLog.pop('seq_log')
        displayLog.pop('sequence')
        logFile.update({'presentation': displayLog})

        file_name = self.file_name + ".pkl"

        #generate full log dictionary
        path = os.path.join(directory, file_name)
        ft.saveFile(path, logFile)
        print ".pkl file generated successfully."

        backupFileFolder = self._get_backup_folder()
        if backupFileFolder is not None:
            if not (os.path.isdir(backupFileFolder)):
                os.makedirs(backupFileFolder)
            backupFilePath = os.path.join(backupFileFolder, file_name)
            ft.saveFile(backupFilePath, logFile)
            print ".pkl backup file generate successfully"
        else:
            print "did not find backup path, no backup has been saved."
    'signMapFilterSigma': 9.,
    'signMapThr': 0.3,
    'eccMapFilterSigma': 15.0,
    'splitLocalMinCutStep': 10.,
    'closeIter': 3,
    'openIter': 3,
    'dilationIter': 15,
    'borderWidth': 1,
    'smallPatchThr': 100,
    'visualSpacePixelSize': 0.5,
    'visualSpaceCloseIter': 15,
    'splitOverlapThr': 1.1,
    'mergeOverlapThr': 0.1
}

currFolder = os.path.dirname(os.path.realpath(__file__))
os.chdir(currFolder)

trial = rm.loadTrial(trialName)

trial.params = params

trial.processTrial(isPlot=True)

trialDict = trial.generateTrialDict()
trial.plotTrial(isSave=isSave, saveFolder=currFolder)
plt.show()

if isSave:
    ft.saveFile(trial.getName() + '.pkl', trialDict)
Ejemplo n.º 10
0
 def load(self, fullname='temp.npy'):
     fullname = FT.file_exist(fullname, default_path=self._path_data)
     return np.load(fullname)
Ejemplo n.º 11
0
 def save(self, data, fullname='temp.npy'):
     fullname = FT.newname(fullname, default=self._path_data)
     np.save(fullname, data)
     self._temp_list.append(fullname)
     return fullname
          'splitLocalMinCutStep': 10.,
          'closeIter': 3,
          'openIter': 3,
          'dilationIter': 15,
          'borderWidth': 1,
          'smallPatchThr': 100,
          'visualSpacePixelSize': 0.5,
          'visualSpaceCloseIter': 15,
          'splitOverlapThr': 1.1,
          'mergeOverlapThr': 0.1
          }

currFolder = os.path.dirname(os.path.realpath(__file__))
os.chdir(currFolder)

trial = rm.loadTrial(trialName)

trial.params=params

trial.processTrial(isPlot=True)

trialDict = trial.generateTrialDict()
trial.plotTrial(isSave=isSave,saveFolder=currFolder)
plt.show()

if isSave:
    ft.saveFile(trial.getName()+'.pkl',trialDict)



Ejemplo n.º 13
0
import time

parser = argparse.ArgumentParser()
parser.add_argument('-name', type=str, default='dark')
parser.add_argument('-path', type=str, default='../data/')
parser.add_argument('-stc', type=str, default='/dev/video1')
parser.add_argument('-captures', type=str, default=10)

params = parser.parse_args()

stc = Device(dev_name=params.stc)

exposures = [1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000]

normalized_name = os.path.normpath(params.path + '/' + params.name)
path, name, extension = FileTools.splitname(normalized_name)
base_name = os.path.normpath(path + "/" + name)

mask = 'Exposure: {:6d}'

time.sleep(5)
print("\n\n")

for exposure in exposures:
    stc.exposure = exposure
    print(mask.format(exposure))
    for i in range(params.captures):
        image = stc.capture()
        filename = base_name + '{:02d}_exp_{:06}.npz'.format(i, exposure)
        np.savez(filename, image=image)
        time_now = time.gmtime(time.time())
Ejemplo n.º 14
0
         ['patch07', 'MMA'],
         ['patch08', 'MMP'],
         ['patch09', 'LLA'],
         # ['patch10', 'AM'],
         # ['patch11', 'LLA'],
         # ['patch12', 'MMP'],
         # ['patch13', 'MMP']
         # ['patch14', 'MMP']
         ]

currFolder = os.path.dirname(os.path.realpath(__file__))
os.chdir(currFolder)

trialPath = os.path.join(currFolder,trialName)

trialDict = ft.loadFile(trialPath)

finalPatches = dict(trialDict['finalPatches'])

for i, namePair in enumerate(names):
    currPatch = finalPatches.pop(namePair[0])
    newPatchDict = {namePair[1]:currPatch}
    finalPatches.update(newPatchDict)
    
trialDict.update({'finalPatchesMarked':finalPatches})

ft.saveFile(trialPath,trialDict)

trial, _ = rm.loadTrial(trialPath)
f = plt.figure(figsize=(10,10))
ax = f.add_subplot(111)