def filter_mdf(file, signals): mdf_file = MDF(file) # Lenkradwinkel lenkradwinkel = mdf_file.get('can0_LWI_Lenkradwinkel') samples = list(lenkradwinkel.samples) vz_samples = list(mdf_file.get('can0_LWI_VZ_Lenkradwinkel').samples) for i in range(0, len(samples)): if not int(vz_samples[i]): samples[i] = samples[i] * -1 lenkradwinkel.samples = np.asarray(samples) # Lenkradwinkel geschw. lenkrad_gesch = mdf_file.get('can0_LWI_Lenkradw_Geschw') samples = list(lenkrad_gesch.samples) vz_samples = list(mdf_file.get('can0_LWI_VZ_Lenkradw_Geschw').samples) for i in range(0, len(samples)): if not int(vz_samples[i]): samples[i] = samples[i] * -1 lenkrad_gesch.samples = np.asarray(samples) # Gierrate gierrate = mdf_file.get('can0_ESP_Gierrate') samples = list(gierrate.samples) vz_samples = list(mdf_file.get('can0_ESP_VZ_Gierrate').samples) for i in range(0, len(samples)): if not int(vz_samples[i]): samples[i] = samples[i] * -1 gierrate.samples = np.asarray(samples) # filter file with VZ signals filtered_mdf = mdf_file.filter(signals) return filtered_mdf
def main(): file = sys.argv[1] mdf_file = MDF(file) mdf_file = mdf_file.filter([ 'can0_LWI_Lenkradwinkel', 'can0_LWI_Lenkradw_Geschw', 'can0_ESP_Fahrer_bremst', 'can0_ESP_Bremsdruck', 'can0_MO_Fahrpedalrohwert_01', 'can0_MO_Kuppl_schalter', 'can0_MO_Drehzahl_01', 'can0_MO_Gangposition', 'can0_ESP_v_Signal', 'can0_ESP_HL_Fahrtrichtung', 'can0_ESP_HR_Fahrtrichtung', 'can0_ESP_Laengsbeschl', 'can0_ESP_Gierrate' ]) signals = mdf_file.iter_channels(skip_master=True) sf = dict() for signal in signals: f = len( signal.timestamps) / (signal.timestamps[-1] - signal.timestamps[0]) sf[signal.name[5:]] = f values = list(map(lambda x: int(math.ceil(x) / 10) * 10, sf.values())) signal_names = list(map(lambda x: '_'.join(x.split('_')[1:]), sf.keys())) fig, ax = plt.subplots(figsize=[8, 4]) plt.bar(range(len(sf)), values, align='center') plt.yticks(np.arange(0, max(values) + 10, 10)) plt.ylabel('Frequency [Hz]') plt.xticks(range(len(sf)), signal_names, rotation='vertical') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.grid(color='gray', linestyle='-', linewidth=0.25, alpha=0.5) plt.savefig('../Thesis/images/signal_frequences.png', bbox_inches='tight')
from asammdf import MDF import sys import matplotlib.pyplot as plt mdf = MDF('Dauerzeitschrieb_20171218_053831.mf4', memory='full') sig_list = [] while 1: choice_1 = input("Do you want to add a signal?(y/n)\n") if choice_1 == "n": if len(sig_list) > 0: filter = mdf.filter(sig_list) file_name = input("Enter the file name to be saved\n") filter.convert('4.10').save(file_name + '.mf4') mdf_new = MDF((file_name + '.mf4'), memory='full') data_frame = mdf_new.export('pandas', filename=file_name) data_frame.to_csv(file_name + '.csv') print("CSV and mf4 file created.\n") choice_2 = input("Do you want to plot the signal(s)?(y/n)\n") if choice_2 == "y": for i in range(len(sig_list)): plt.figure(i) plt.xlabel('Time [s]') plt.ylabel('[{}]'.format(mdf.get(sig_list[i]).unit)) plt.plot( mdf.get(sig_list[i]).timestamps, mdf.get(sig_list[i]).samples, 'b') plt.plot( mdf.get(sig_list[i]).timestamps, mdf.get(sig_list[i]).samples, 'b.') plt.grid(True) break
def main(): my_parser = argparse.ArgumentParser( description='Transform signals with sign') my_parser.add_argument('-i', '--input', action='store', metavar='mf4_input', type=str, required=True, help='Input directory with source mf4 files') my_parser.add_argument('-o', '--output', action='store', metavar='mf4_output', type=str, required=True, help='Output directory') # Execute the parse_args() method args = my_parser.parse_args() mf4_input = args.input mf4_output = args.output if not os.path.isdir(mf4_input): print('The mf4 input path specified is not a directory') sys.exit() if not os.path.isdir(mf4_output): print('The mf4 ouput path specified is not a directory') sys.exit() for file in os.listdir(mf4_input): if not file.endswith('.mf4'): continue print('process %s' % file) mdf_file = MDF(os.path.join(mf4_input, file)) # Lenkradwinkel lenkradwinkel = mdf_file.get('can0_LWI_Lenkradwinkel') samples = list(lenkradwinkel.samples) vz_samples = list(mdf_file.get('can0_LWI_VZ_Lenkradwinkel').samples) for i in range(0, len(samples)): if not int(vz_samples[i]): samples[i] = samples[i] * -1 lenkradwinkel.samples = np.asarray(samples) # Lenkradwinkel geschw. lenkradwinkel = mdf_file.get('can0_LWI_Lenkradw_Geschw') samples = list(lenkradwinkel.samples) vz_samples = list(mdf_file.get('can0_LWI_VZ_Lenkradw_Geschw').samples) for i in range(0, len(samples)): if not int(vz_samples[i]): samples[i] = samples[i] * -1 lenkradwinkel.samples = np.asarray(samples) # Gierrate lenkradwinkel = mdf_file.get('can0_ESP_Gierrate') samples = list(lenkradwinkel.samples) vz_samples = list(mdf_file.get('can0_ESP_VZ_Gierrate').samples) for i in range(0, len(samples)): if not int(vz_samples[i]): samples[i] = samples[i] * -1 lenkradwinkel.samples = np.asarray(samples) # filter file with VZ signals filtered_mdf = mdf_file.filter(interesting_signals) filtered_mdf.save(os.path.join(mf4_output, file))
import matplotlib # import matplotlib.pyplot as plt # MDF 파일을 읽어옵니다. path = "./" data = MDF(path + "Acceleration_StandingStart.MDF") ### CAN 신호 리스트를 가져 옵니다. signal_list = list(data.channels_db) # 가져온 리스트에서 시간축은 신호가 아니므로 제외합니다. signal_list.remove('t') print(signal_list) # 로깅된 CAN 신호 전체를 볼 수 있습니다. ### 그래프 출력 #speed = data.get('VehicleSpeed') #speed.plot() ### 필요한 신호만 필터링 filtered_signal_list = ['VehicleSpeed', 'Throttle'] ### 여러 그래프 출력 for signal in data.select(filtered_signal_list): signal.plot() # 10초 ~ 12초 사이의 데이터만 필터링 filtered_data = data.filter(filtered_signal_list).cut(start=10, stop=12) ### 엑셀 파일 또는 CSV 파일로 출력 #signals_data_frame = data.to_dataframe() #signals_data_frame.to_excel(path + "signals_data_frame.xlsx") #signals_data_frame.to_csv(path + "signals_data_frame.csv")
# create empty MDf version 4.00 file mdf4 = MDF(version='4.10') # append the 3 signals to the new file signals = [s_uint8, s_int32, s_float64] mdf4.append(signals, 'Created by Python') # save new file mdf4.save('my_new_file.mf4', overwrite=True) # convert new file to mdf version 3.10 with lowest possible RAM usage mdf3 = mdf4.convert('3.10', memory='minimum') print(mdf3.version) # get the float signal sig = mdf3.get('Float64_Signal') print(sig) # cut measurement from 0.3s to end of measurement mdf4_cut = mdf4.cut(start=0.3) mdf4_cut.get('Float64_Signal').plot() # cut measurement from start of measurement to 0.4s mdf4_cut = mdf4.cut(stop=0.45) mdf4_cut.get('Float64_Signal').plot() # filter some signals from the file mdf4 = mdf4.filter(['Int32_Signal', 'Uint8_Signal']) # save using zipped transpose deflate blocks mdf4.save('out.mf4', compression=2, overwrite=True)
for files in range(len(srcFiles)): # print( f'\nRead mf4 files started. {files+1}/{len(srcFiles)} File selected {srcFiles[files].name}' ) sleep(1) try: mf4_data = MDF(srcFiles[files]) csvname = srcFiles[files].name outfilename_Comment = srcFiles[0].parent.as_posix().replace( '/', '\\') + '\\' + csvname + '_Comments.csv' outfilename_Gps = srcFiles[0].parent.as_posix().replace( '/', '\\') + '\\' + csvname + '_GPS.csv' outfilename_merged = srcFiles[0].parent.as_posix().replace( '/', '\\') + '\\' + srcFiles[0].parts[-2] + '_Merged.csv' filtered = mf4_data.filter(['Comment']) sdata = filtered.get('Comment') commentSignals.append(sdata) comment = sdata.samples.astype(str).tolist() timestamp = sdata.timestamps.tolist() fname = [srcFiles[files].name] * len(comment) gpsLatitude = mf4_data.get('GPSLatitude') gpsLongitude = mf4_data.get('GPSLongitude') gpsTs = gpsLatitude.timestamps.tolist() gpsLat = gpsLatitude.samples.tolist() gpsLon = gpsLongitude.samples.tolist() gpsLatwgs = [(Lat / 1000000) - 90 for Lat in gpsLat] gpsLonwgs = [(Lon / 1000000) - 180 for Lon in gpsLon] gpsList = {'ts': gpsTs, 'lat': gpsLatwgs, 'lon': gpsLonwgs} gpsFrame = pd.DataFrame(gpsList).to_csv(outfilename_Gps)