projects.py 2.18 KB
Newer Older
Michael Rudolf's avatar
Michael Rudolf committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
#!/usr/bin/env python3

'''
projects.py

Project management by assigning an individual config to each project.


__AUTHOR__: Michael Rudolf
__DATE__: 25-Mar-2019

'''

import configparser


def project(**kwargs):
    '''
    Tries to read a project from the given file path. If called without any
    arguments a new project is created in the current path using standard
    entries. You can change default values and add new values to the project by
    passing keyword arguments.

    Examples:
    project()
        - Creates a default project with the name 'default_parameters.ini'
    project(file_path='foo.ini')
        - Tries to open the project 'foo.ini' if it does not exist, it is
          created.
    project(window=45)
        - Creates a default project with the entry 'window' set to 45.

    '''
    prj = configparser.ConfigParser()
    if 'file_path' in kwargs:
        prj_path = kwargs['file_path']
        try:
            with open(prj_path) as f:
                prj.read_file(f)
        except Exception as e:
            prj = create_default_project(file_path=prj_path)
    else:
        prj = create_default_project()
    return update_project(prj, **kwargs)


def create_default_project(file_path='default_parameters.prj'):
    ''' Contains the default entries for the project '''
    prj = configparser.ConfigParser()

    prj['params'] = {
        'directory': '',
        'file_path': file_path,
        'lowpass_cutoff': 150,
        'lowpass_order': 5,
        'min_cycles': 5,
        'min_win': 10,
        'step_frac': 1,
        'window': 30,
    }

    prj['state'] = {
        'feature_file': '',
        'features_created': False,
        'set_folder': '',
        'sets_created': False,
        'subset_folder': '',
        'subsets_created': False,
    }

    return save_project(prj)


def update_project(prj, **kwargs):
    for k in kwargs.keys():
        prj['params'][k] = kwargs[k]
    return save_project(prj)


def save_project(prj):
    with open(prj['params']['file_path'], 'w') as prj_file:
        prj.write(prj_file)
    return read_project(prj)


def read_project(prj):
    with open(prj['params']['file_path'], 'rt') as prj_file:
        prj.read_file(prj_file)
    return prj