files.py 14 KB
Newer Older
Michael Rudolf's avatar
Michael Rudolf committed
1
2
3
4
""" Functions for file operations for rst-evaluation """

import codecs
import collections
Michael Rudolf's avatar
Michael Rudolf committed
5
import configparser
Michael Rudolf's avatar
Michael Rudolf committed
6
import csv
Michael Rudolf's avatar
Michael Rudolf committed
7
import json
Michael Rudolf's avatar
Michael Rudolf committed
8
9
import operator
import os
Michael Rudolf's avatar
Michael Rudolf committed
10
import shutil
Michael Rudolf's avatar
Michael Rudolf committed
11
12
13

import nptdms
import numpy as np
14
15
16
from tqdm import tqdm

from . import data as rstdat
Michael Rudolf's avatar
Michael Rudolf committed
17
18


Michael Rudolf's avatar
Michael Rudolf committed
19
def convert(path, file_in, config):
Michael Rudolf's avatar
Michael Rudolf committed
20
21
    """Reads data from source files and returns a dictionary with data"""

Michael Rudolf's avatar
Michael Rudolf committed
22
23
24
25
26
    if isinstance(config, configparser.ConfigParser):
        var = {
            k: json.loads(config['parameters'][k])
            for k in config['parameters']
        }
27
28
    else:
        var = config
Michael Rudolf's avatar
Michael Rudolf committed
29
30
31
32
33
34
    # possible inputs and linked helper functions
    file_convert = {'.asc': readasc,
                    '.dat': readdat,
                    '.tdms': readtdms}

    (_, ext) = os.path.splitext(os.path.join(path, file_in))
Michael Rudolf's avatar
Michael Rudolf committed
35
    data = file_convert[ext](path, file_in, config)
Michael Rudolf's avatar
Michael Rudolf committed
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

    # check if stress data was imported instead of force
    if 'normalstress' in data.keys():
        data['normalforce'] = data['normalstress'] * var['A']
        data['shearforce'] = (
            (data['shearstress'] * (var['li']*var['A'])) / var['lo']
        )
    nsamples = var['nsamples']
    if len(data['time']) > nsamples:
        freq = 1/data['time'][1]
        R = int(freq / 5)
        data['velocity'] = rstdat.downsample(data['velocity'], R)
        data['shearforce'] = rstdat.downsample(data['shearforce'], R)
        data['normalforce'] = rstdat.downsample(data['normalforce'], R)
        data['time'] = np.linspace(0, data['time'][-1], len(data['velocity']))
        print('Data to large... Downsampled to 5 Hz.')

    # Corrections
    data['time'] = data['time']-data['time'][0]
    # data['liddispl'] = -(data['liddispl']-data['liddispl'][0])
    data['velocity'][data['velocity'] < 0] = 0

    # Additional data
    data['shearstress'] = (data['shearforce']*var['lo'])/(var['li']*var['A'])
    data['normalstress'] = data['normalforce']/var['A']
    data['displacement'] = np.cumsum(data['time'][1]*data['velocity'])

    data['name'] = file_in

    print(file_in+' read')
    return data


Michael Rudolf's avatar
Michael Rudolf committed
69
def readasc(path, file_in, config):
Michael Rudolf's avatar
Michael Rudolf committed
70
71
72
73
74
75
76
77
78
79
    """ Helper function to read *.asc file """
    with codecs.open(os.path.join(path, file_in), encoding='utf-8-sig') as f:
        data_load = np.loadtxt(f)  # load file for further calculations

    # extract data and convert to SI-units
    time = data_load[:, 0]  # in s
    shearforce = data_load[:, 2] * 9.81  # kg -> N
    velocity = data_load[:, 4] / 60  # mm/min -> mm/s
    liddispl = data_load[:, 3]  # in mm
    normalforce = data_load[:, 1] * 9.81  # kg -> N
Michael Rudolf's avatar
Michael Rudolf committed
80
81
82
83
84
85
86
87
    data = {
        'time': time,
        'velocity': velocity,
        'normalforce': normalforce,
        'shearforce': shearforce,
        'liddispl': liddispl,
        'name': file_in.split('.')[0]
    }
Michael Rudolf's avatar
Michael Rudolf committed
88
89
90
    return data


Michael Rudolf's avatar
Michael Rudolf committed
91
def readdat(path, file_in, config):
Michael Rudolf's avatar
Michael Rudolf committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
    """ Helper function to read *.dat file  """
    load_fun = [
        alternativeload, standardload, pascalload
    ]
    filetype = check_for_type(os.path.join(path, file_in))
    print('%s of type: %s' % (file_in, filetype))

    if filetype:  # if filetype is non zero:
        with codecs.open(
            os.path.join(path, file_in),
            encoding='utf-8-sig'
        ) as f:
            try:
                data = load_fun[filetype](f, file_in)
            except ValueError:
                data = alternativeload(f, file_in)
    return data


Michael Rudolf's avatar
Michael Rudolf committed
111
def readtdms(path, file_in, config):
Michael Rudolf's avatar
Michael Rudolf committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
    """ Helper function to read *.tdms file """
    if int(nptdms.__version__[0]) < 1:
        # Deprecated file interface
        DeprecationWarning(
            'Your version of NPTDMS is out of date, consider updating it.'
        )
        f = nptdms.TdmsFile(os.path.join(path, file_in))
        time = f.group_channels('Untitled')[0].time_track()  # in [s]
        df_raw = dict()
        for channel in f.group_channels('Untitled'):
            channel_name = channel.path.replace('\'', '').split('/')[-1]
            df_raw[channel_name] = channel.data
        shearforce = df_raw['Shear Force']  # in [N]
        normalforce = df_raw['Normal Force']  # in [N]
        liddispl = df_raw['Lid Displacement']  # in [mm]
        velocity = df_raw['Velocity']  # in [mm/s]
    else:
        with nptdms.TdmsFile.open(os.path.join(path, file_in)) as f:
            time = f['Untitled']['Shear Force'].time_track()  # in [s]
            shearforce = f['Untitled']['Shear Force'][:]  # in [N]
            normalforce = f['Untitled']['Normal Force'][:]  # in [N]
            liddispl = f['Untitled']['Lid Displacement'][:]  # in [mm]
            velocity = f['Untitled']['Velocity'][:]  # in [mm/s]

Michael Rudolf's avatar
Michael Rudolf committed
136
137
138
139
140
141
142
143
    data = {
        'time': time,
        'velocity': velocity,
        'normalforce': normalforce,
        'shearforce': shearforce,
        'liddispl': liddispl,
        'name': file_in.split('.')[0]
    }
Michael Rudolf's avatar
Michael Rudolf committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
    return data


def readpropfile(prop_file):
    """ Reads the properties of the experiment from the csv file """
    props = dict()
    with open(prop_file, 'r') as f:
        csv_reader = csv.reader(f)
        props['names'] = next(csv_reader)
        props['units'] = next(csv_reader)
        props['data'] = [row for row in csv_reader]
    return props


def standardload(f, file_in):
    """
    Standard loading
    """
    data_load = np.loadtxt(f, delimiter=';', skiprows=3)
    time = data_load[:, 0]  # in s
    normalforce = data_load[:, 1]  # in N
    shearforce = data_load[:, 2]  # in N
    liddispl = data_load[:, 3]  # in mm
    velocity = data_load[:, 4]  # in mm/s

    data = {
        'time': time,
        'velocity': velocity,
        'normalforce': normalforce,
        'shearforce': shearforce,
        'liddispl': liddispl,
        'name': file_in.split('.')[0]
    }
    return data


def alternativeload(f, file_in):
    """
    Loads data in a slightly different way to ensure backwards
    compatability
    """
    data_load = np.loadtxt(f, delimiter='\t', skiprows=1)
    time = data_load[:, 0]  # in s
    velocity = data_load[:, 1]  # in mm/s
    normalforce = data_load[:, 2]  # in N
    shearforce = data_load[:, 3]  # in N

    data = {
        'time': time,
        'velocity': velocity,
        'normalforce': normalforce,
        'shearforce': shearforce,
        'name': file_in.split('.')[0]
    }
    return data


def pascalload(f, file_in):
    """
    Loads a file with Pascal as main units
    """
    data_load = np.loadtxt(f, delimiter=';', skiprows=3)
    time = data_load[:, 0]  # in s
    normalforce = data_load[:, 1]  # in Pa
    shearforce = data_load[:, 2]  # in Pa
    liddispl = data_load[:, 3]  # in mm
    velocity = data_load[:, 4]  # in mm/s

    data = {
        'time': time,
        'velocity': velocity,
        'normalstress': normalforce,
        'shearstress': shearforce,
        'liddispl': liddispl,
        'name': file_in.split('.')[0]
    }
    return data


def check_for_type(filepath):
    """
    Checks what kind of dat file we have.

    Returns:
        0: if it is unkown
        1: if data is in Newton
        2: if data is in Pascal
    """
    with open(filepath, 'rt') as fhandle:
        for i, row in enumerate(csv.reader(fhandle)):
            if i == 2:
                row = row[0]
                if '[N]' in row:
                    return 1
                elif '[Pa]' in row:
                    return 2
                else:
                    return 0
            elif i > 2:
                break


def saveTS(path, name, exp_data, normal_stress):
    """ Saves time series in a txt file """
    # create header
    header = ['Time [s]']
    for n in normal_stress:
        header.append(n)

    # position of longest measurement
    data_lens = [len(ex['time']) for ex in exp_data]
    pos_dfmax = np.argmax(data_lens)
    max_len = np.max(data_lens)
    time_max = exp_data[pos_dfmax]['time']

    # create array to save to file
    # ts_data = np.zeros((max_len, len(exp_data)+1))
    ts_data = ['%.5f' % t for t in time_max]
    for ex in exp_data:
        pads = np.ones(max_len-len(ex['shearstress']))*np.nan
        next = np.hstack((np.around(ex['shearstress'], 2), pads))
        next_str = ['%.2f' % n for n in next]
        ts_data = np.vstack((ts_data, next_str))
    ts_data = ts_data.T

    # create file and save it
Michael Rudolf's avatar
Michael Rudolf committed
270
    with open(os.path.join(path, name+'_ts.txt'), 'w+') as f:
Michael Rudolf's avatar
Michael Rudolf committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
        csvout = csv.writer(f,
                            delimiter='\t',
                            lineterminator='\n')
        csvout.writerows([header])
        csvout.writerows(ts_data)


def saveStrength(path, name, strength):
    """ Saves the picked datapoints. """
    label = ['_peak', '_dynamic', '_reactivation']
    for i in range(0, 3):
        Stren = np.vstack((np.round(strength[0], 2),
                           np.round(strength[i+1], 2)))
        header_stress = 'Normal stress [Pa]'+'\t'+'Shear strength [Pa]'
        with open(path+name+label[i]+'.txt', "w") as f:
            f.write(header_stress+'\n')
            for row in Stren.T:
                csv.writer(f,
                           delimiter='\t',
                           lineterminator='\n').writerow(row)
        f.closed


def saveFric(path, name, fricmut, fricstd):
    """ Saves the fit data. """
    header = '# Parameter' + \
             '\t' + \
             'Coeff. of internal friction' + \
             '\t' + \
             'Std. deviation (Coeff.)' + \
             '\t' + \
             'Cohesion [Pa]' + \
             '\t' + \
             'Std deviation (Coh.) [Pa]'
    with open(path+name+'_fricstd.txt', 'w') as f:
        f.write(header+'\n')
        f_string = ''
        f_string += 'Peak friction:' + \
                    '\t' + \
                    str(np.around(fricstd[0][0], 4)) + \
                    '\t'+str(np.around(fricstd[0][1], 4)) + \
                    '\t'+str(np.around(fricstd[0][2], 4)) + \
                    '\t'+str(np.around(fricstd[0][3], 4)) + \
                    '\n'
        f_string += 'Dynamic friction:' + \
                    '\t' + \
                    str(np.around(fricstd[1][0], 4)) + \
                    '\t' + \
                    str(np.around(fricstd[1][1], 4)) + \
                    '\t' + \
                    str(np.around(fricstd[1][2], 4)) + \
                    '\t' + \
                    str(np.around(fricstd[1][3], 4)) + \
                    '\n'
        f_string += 'Reactivation friction:' + \
                    '\t' + \
                    str(np.around(fricstd[2][0], 4)) + \
                    '\t' + \
                    str(np.around(fricstd[2][1], 4)) + \
                    '\t' + \
                    str(np.around(fricstd[2][2], 4)) + \
                    '\t' + \
                    str(np.around(fricstd[2][3], 4)) + \
                    '\n'
        f.write(f_string)
    f.closed
    with open(path+name+'_fricmut.txt', 'w') as f:
        f.write(header+'\n')
        f_string = ''
        f_string += 'Peak friction:' + \
                    '\t' + \
                    str(np.around(fricmut[0][0], 4)) + \
                    '\t' + \
                    str(np.around(fricmut[0][1], 4)) + \
                    '\t' + \
                    str(np.around(fricmut[0][2], 4)) + \
                    '\t' + \
                    str(np.around(fricmut[0][3], 4)) + \
                    '\n'
        f_string += 'Dynamic friction:' + \
                    '\t' + \
                    str(np.around(fricmut[1][0], 4)) + \
                    '\t' + \
                    str(np.around(fricmut[1][1], 4)) + \
                    '\t' + \
                    str(np.around(fricmut[1][2], 4)) + \
                    '\t' + \
                    str(np.around(fricmut[1][3], 4)) + \
                    '\n'
        f_string += 'Reactivation friction:' + \
                    '\t' + \
                    str(np.around(fricmut[2][0], 4)) + \
                    '\t' + \
                    str(np.around(fricmut[2][1], 4)) + \
                    '\t' + \
                    str(np.around(fricmut[2][2], 4)) + \
                    '\t' + \
                    str(np.around(fricmut[2][3], 4))+'\n'
        f.write(f_string)
    f.closed


def savelidpos(path, name, p_ind, exp_data):
    """ Saves lid position at peak location to estimate densities """
    lid_pos = collections.defaultdict(list)
    for p, ex in zip(p_ind, exp_data):
        for k in p.keys():
            lid_pos[k].append(ex['liddispl'][p[k]])

    names = [ex['name'] for ex in exp_data]
    header = [k for k in lid_pos.keys()]
    header.insert(0, 'experiment')
    data = [lid_pos[k] for k in lid_pos.keys()]
    rows = [
        [names[i], data[0][i], data[1][i], data[2][i]]
        for (i, _) in enumerate(data[0])
    ]

    rows.sort(key=operator.itemgetter(0))

    with open(path+name+'_lidpos.txt', 'w+') as f:
        w = csv.writer(
            f,
            delimiter=',')
        w.writerow(header)
        w.writerows(rows)
    return rows
Michael Rudolf's avatar
Michael Rudolf committed
398
399
400
401
402
403
404


def get_length(file_path):
    """ Gives back sample length of tdms data """
    with nptdms.TdmsFile.open(file_path) as tdms_file:
        length = len(tdms_file['Untitled']['Shear Force'].time_track())
    return length
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432


def check_tdms(file_list, config):
    """
    Checks if a tdms file on the list is longer than allowed. If yes then the
    data is automatically downsampled.
    """
    max_len = 0
    for file_name in tqdm(file_list, desc='Checking TDMS file length'):
        cur_len = get_length(
            os.path.join(config['paths']['path_in'], file_name)
        )
        if cur_len > max_len:
            max_len = cur_len

    if max_len > config.getint('parameters', 'nsamples'):
        print(
            'Converting folder. Raw data files will be moved to raw_data.'
        )
        raw_folder = os.path.join(config['paths']['path_in'], 'raw_data')
        os.makedirs(
            raw_folder,
            exist_ok=True
        )
        for file_name in tqdm(file_list, desc='Downsampling Files'):
            file_path = os.path.join(config['paths']['path_in'], file_name)
            new_path = os.path.join(raw_folder, file_name)
            shutil.move(file_path, new_path)
Michael Rudolf's avatar
Michael Rudolf committed
433
            new_file_path = rstdat.downsample_file(new_path)
434
            shutil.move(new_file_path, file_path)