-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomNoise.py
executable file
·283 lines (236 loc) · 10.6 KB
/
randomNoise.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/usr/bin/python3
import argparse
from os import remove
from pathlib import Path
import time
import numpy as np
from epics import caput, caget
import subprocess
ver = "1.4.0"
author = "Valentin Reichenbach"
description = """
This program is used to generate noise for a PV in an epics system.
In normal mode it will apply the noise to a given PV.
In debug mode it will continuously write to a given text file to simulate a debug enviroment.
"""
epilog = """
Author: Valentin Reichenbach
Version: 1.4.0
License: GPLv3+
"""
def writeToDebugFile(debugFile: str, content, args):
content = str(content)
f = open(debugFile, 'w')
f.write(content)
if args.verbose >= 1:
print('Written '+ content + ' to ' + str(debugFile) + '')
f.close()
def getFromDebugFile(debugFile: str, lastVal: float, args) -> float:
f = open(debugFile, 'r')
content = f.read()
f.close()
try:
float(content)
except Exception as e:
if args.verbose >= 1:
print('Error while reading ' + str(debugFile) + '!')
print('Exception: ', e)
content = lastVal
return content
def readSinFile(verbose: int):
f = open('sin.txt', 'r')
content = f.read()
f.close()
if verbose >= 3:
print('sin.txt: ' + str(content))
return content
def generateNoise(i, y, count, no_delete: bool, file: str, noise_type: str, noise_strength: float, drift: float, period: float, fileVal: float, verbose: int) -> float:
time_start = time.time()
if noise_type == 'normal':
# draws a random value from normal (Gaussian) distribution bewteen -1 and 1
noise = noise_strength * np.random.normal(0,1,1)[0] + drift
noise = float(noise) + float(fileVal)
elif noise_type == 'sin':
if i == len(y) - 1:
other_sin = y[0]
else:
other_sin = y[i + 1]
diff = other_sin - y[i]
i = i + 1
if i >= count:
i = 0
# sleep
while time.time() - time_start < period/count:
pass
noise = diff + fileVal
elif noise_type == 'mix':
# draws a random value from a mixture of a normal distribution and a sine wave bewteen -1 and 1
# by calling the normal and sin functions
normal_noise , _ = generateNoise(i, y, count, no_delete=no_delete, file=file, noise_type='normal', noise_strength=noise_strength, drift=drift, period=period, fileVal=0, verbose=verbose)
sin_noise , i = generateNoise(i, y, count, no_delete=no_delete, file=file, noise_type='sin', noise_strength=noise_strength, drift=drift, period=period, fileVal=0, verbose=verbose)
noise = normal_noise + sin_noise
else:
print('Error: noise type ' + noise_type + ' not recognized')
return 0
return noise , i
def debugMode(args):
# check if debug file already exists
try:
remove("debugEnv.txt")
except:
pass
print('Starting...')
# create the debug file
debugFile = Path(args.file)
# convert to str for python 3.5
debugFile = str(debugFile)
writeToDebugFile(debugFile=debugFile, content=1, args=args)
# set the last value to the niveau
lastVal= 1.0
i = 0
count = 100
x = 2 * np.pi * np.arange(count) / count
y = args.amplitude * np.sin(x) + args.shift
try:
while True:
# Writes a random value to the debugfile
fileVal = getFromDebugFile(debugFile=debugFile, lastVal=lastVal, args=args)
fileVal = float(fileVal)
noise , i = generateNoise(i, y, count, no_delete=args.no_delete, file=args.file, noise_type=args.noise_type, noise_strength=args.noise_strength, drift=args.drift, period=args.period, fileVal=fileVal, verbose=args.verbose)
# if the noise gets read incorrectly, use the last value
if noise == '':
if args.verbose >= 2:
print('Error while reading noise. Using 0')
noise = 0
# conversion to float because python threw an error otherwise
if args.verbose >= 3:
print('fileVal: ' + str(fileVal))
print('noise: ' + str(noise))
print('lastVal: ' + str(lastVal))
# write the new value to the debug file
writeToDebugFile(debugFile=debugFile, content=noise, args=args)
if args.verbose >= 3:
print('')
# update the last value
lastVal = noise
# wait for the next iteration
time.sleep(args.delay)
except KeyboardInterrupt:
print('\nKeyboard interrupt detected\nExiting...')
return
def normalMode(args):
print('Starting in Normal Mode...')
# get first value
lastVal= caget(args.pv + ":outCur")
i = 0
count = 100
x = 2 * np.pi * np.arange(count) / count
y = args.amplitude * np.sin(x) + args.shift
try:
while True:
# get value from other script
currentVal = caget(args.pv + ":outCur")
noise , i = generateNoise(i, y, count, False, "debugEnv.txt", noise_type=args.noise_type, noise_strength=args.noise_strength, drift=args.drift, period=args.period, fileVal=lastVal, verbose=args.verbose)
# if the noise gets read incorrectly, use the last value
if noise == '':
if args.verbose >= 2:
print('Error while reading noise. Using 0')
noise = 0
# write new value to pv
newVal = noise
caput(args.pv + ":outCur", newVal)
# update the last value
lastVal = noise
if args.verbose >= 1:
print('Old value: ' + str(currentVal))
print('Noise: ' + str(noise))
print('New value: ' + str(newVal))
print('')
# wait for the next iteration
time.sleep(args.delay)
except KeyboardInterrupt:
print('\nKeyboard interrupt detected\nExiting...')
return
def cleanup(no_delete: bool, file: str, noise_type: str, mode: str):
if no_delete == False and mode == 'debug':
try:
remove(file)
except Exception as e:
print('Something went wrong while deleting ' + str(file) + '!')
print(e)
if noise_type == 'sin':
try:
# kill subprocess
subprocess.run(['pkill', '-f', 'sinenoise.py'])
except Exception as e:
print('Something went wrong while killing the sinenoise subprocess!')
print(e)
try:
# delete sin.txt
remove('sin.txt')
except Exception as e:
print('Something went wrong while deleting sin.txt!')
print(e)
def main():
parser = argparse.ArgumentParser(
description=description, epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter)
parentParser = argparse.ArgumentParser('The parent parser', add_help=False)
# general options
parentParser.add_argument('-d','--delay', type=float, default=0.05, help='delay between each write in miliseconds. The default value is 0.05')
parentParser.add_argument('-v', '--verbose', action='count', default=0, help='verbose output')
parentParser.add_argument('--version', action='version', version=ver)
parentParser.add_argument('--noise-strength', type=float, default=0.5, help='the strength of the noise. The default value is 0.5')
parentParser.add_argument('--drift', type=float, default=0.0, help='the drift of the noise. The default value is 0.0')
parentParser.add_argument('--noise-type', type=str, default='normal', help='the type of noise that should be generated. The default value is "normal" (a normal distribution). Alternativly, you can use "sin" for noise a sine wave like noise, or "mix for a bixture of both"')
parentParser.add_argument("--period", type=float, default=10, help="the period of the sine wave in seconds. The default value is 10")
parentParser.add_argument('--shift', type=float, default=0.0, help='the shift of the sine wave. The default value is 0.0')
parentParser.add_argument('--amplitude', type=float, default=1.0, help='the amplitude of the sine wave. The default value is 1.0')
# subcommands
subparsers = parser.add_subparsers(dest='mode', help='the program can use an epics interface or create a debug enviroment for another script')
subparsers.required = True
# normal mode
pvParser = subparsers.add_parser('normal', help='uses the epics interface', parents=[parentParser])
pvParser.add_argument('--pv', type=str, default='I1SV02' ,help='the process variable that should be controlled. The default is I1SV02')
pvParser.add_argument('--force', action='store_true', default=False,
help='forces the pv connect check to pass. This is should only be used for development and testing purposes')
# debug mode
debugParser = subparsers.add_parser('debug', help='controls a test enviroment instead of the epics interface', parents=[parentParser])
debugParser.add_argument('-f', '--file', type=str, default='debugEnv.txt', help='simulates a debug enviroment for a controller script using a file called "debugEnv.txt"')
debugParser.add_argument('--no-delete', action='store_true', default=False, help='doesn\'t delete the debug env file after running the program')
args = parser.parse_args()
try:
args.file = str(args.file)
except:
pass
# # start sine noise script with the given arguments if asked for
# if args.noise_type == 'sin' or args.noise_type == 'mix':
# cmd = ['python3', 'sinenoise.py', "--force"]
# sleep(1)
# if args.frequency:
# cmd.append('--frequency')
# cmd.append(str(args.frequency))
# if args.verbose > 0:
# print('Starting sine noise script with cmd:')
# cmd_str = ''
# for i in cmd:
# cmd_str += i + ' '
# print(cmd_str)
# # start the sine noise script as a subprocess
# subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# sleep shortly to let subprocess start
# sleep(1)
# start the given mode
if args.mode == 'debug':
debugMode(args)
elif args.mode == 'normal':
normalMode(args)
# set debug mode rélated variables to default values
# script crashes otherwise
args.no_delete = False
args.file = 'debugEnv.txt'
else:
print('Something went wrong while parsing the arguments\nExiting...')
# cleanup
cleanup(no_delete=args.no_delete, file=args.file, noise_type=args.noise_type, mode=args.mode)
if __name__ == '__main__':
main()