Nested Parallel While Loops - multithreading

I am trying to run two while loops in parallel for the purpose of data acquisition.
This program will run for "n" num_trials with specific trial duration for each trial.
During each trial, the program will collect data while keeping track of the trial duration. For example, the first trial starts collecting data at 1 seconds and stops at 10 seconds. This process will repeat for the rest number of trials
How can I run both while loops in parallel?
Basically, I just want a method that will break the second while loop once the specified trial duration is complete?
Thanks in advance.
count = 0;
num_trials = 5; % Number of Trials = 5 Trials
trial_duration = 10; % Trial Duration = 10 Seconds
global check
check = 0;
% Number of Trials
for i = 1:num_trials
fprintf('Starting Trial %i\n', i);
t_start = tic;
% Start counting and Collecting Data
while toc(t_start) < trial_duration
% Data Collection
while (check ~= 1)
count = count +1;
end
end
fprintf('Ending Trial %i\n', i);
end

Have you tried using a single loop with && ?
while (toc(t_start) < trial_duration) && (check ~= 1)
% Data Collection
count = count +1;
end

Related

How to create a watchdog on a program in python?

I want to know is it even possible to create a watchdog on a program,
I am trying to do Discrete event simulation to simulate a functioning machine,
the problem is, once I inspect my machine at let's say time = 12 (inspection duration is 2 hours lets say) if the event failure is at 13-time units) there is no way that it can be because I am "busy inspecting"
so is there a sort of "watchdog" to constantly test if the value of a variable reached a certain limit to stop doing what the program is doing,
Here is my inspection program
def machine_inspection(tt, R, Dpmi, Dinv, FA, TRF0, Tswitch, Trfn):
End = 0
TPM = 0
logging.debug(' cycle time %f' % tt)
TRF0 = TRF0 - Dinv
Tswitch = Tswitch - Dinv
Trfn = Trfn - Dinv
if R == 0:
if falsealarm == 1:
FA += 1
else:
tt = tt + Dpmi
TPM = 1
End = 1
return (tt, End, R, TPM, FA, TRF0, Trfn, Tswitch)
Thank you very much!
basically you can't be inspecting during x time if tt + x will be superior to the time to failure TRF0 or Trfn

Accurate time-keeping in node.js

I'm new to node.js, I'm trying to determine the elapsed time between an on and an off event of a switch (using BeagleBone Black), the script works, somewhat with .getTime() however from what I read it's not particularly accurate. So I did some research and attempted to use console.time, however from what I read there is no way to export the time value into a variable in this particular application.
I'm trying to write a script that times valve open and close events for an engine, so accuracy is paramount. The only input is a reed switch that is triggered by a passing magnet attached to a rotating flywheel.
More concisely, is there a way to time on/off events accurately in node.js?
var b = require('bonescript');
b.pinMode('P8_19', b.INPUT);
b.pinMode('P8_17', b.OUTPUT);
b.pinMode('USR3', b.OUTPUT);
b.attachInterrupt('P8_19', true, b.CHANGE, interruptCallback);
var cycle = 0;
//var t = 0;
var start, end;
function interruptCallback() {
if (b.digitalRead('P8_19') == 1)
{
console.log('Magnetic field present!');
cycle=cycle+1;
console.log ('cycle: ' + cycle);
}
else
{
//console.time('t');
start = (new Date()).getTime();
}
//console.timeEnd('t');
//console.log(t);
end = (new Date()).getTime();
console.log('elapsed time: ' + (end - start));
}
This is the full code that I'm currently using. Note: I've also displayed how I attempted to use console.time.
Thank you for your help!
For the most accurate time measure possible, use process.hrtime(). From the documentation:
Returns the current high-resolution real time in a [seconds,
nanoseconds] tuple Array. It is relative to an arbitrary time in the
past. It is not related to the time of day and therefore not subject
to clock drift. The primary use is for measuring performance between
intervals.
The function returns a two-element array that contains the count of seconds and count of nanoseconds. Passing one time object into another will return the difference between the two objects.
For your case:
function interruptCallback() {
if (b.digitalRead('P8_19') == 1) {
cycle = cycle + 1;
} else {
start = process.hrtime();
}
end = process.hrtime(start);
console.log('elapsed time: ' end[0] + ' seconds and ' + end[1] + 'nanoseonds.');
};

Replace While() loop with Timer to prevent the GUI from freezing [Multithreading?]

How can I use the Timer class and timer events to turn this loop into one that executes chunks at a time?
My current method of just running the loop keeps freezing up the flash/air UI.
I'm trying to acheive psuedo multithreading. Yes, this is from wavwriter.as:
// Write to file in chunks of converted data.
while (dataInput.bytesAvailable > 0)
{
tempData.clear();
// Resampling logic variables
var minSamples:int = Math.min(dataInput.bytesAvailable/4, 8192);
var readSampleLength:int = minSamples;//Math.floor(minSamples/soundRate);
var resampleFrequency:int = 100; // Every X frames drop or add frames
var resampleFrequencyCheck:int = (soundRate-Math.floor(soundRate))*resampleFrequency;
var soundRateCeil:int = Math.ceil(soundRate);
var soundRateFloor:int = Math.floor(soundRate);
var jlen:int = 0;
var channelCount:int = (numOfChannels-inputNumChannels);
/*
trace("resampleFrequency: " + resampleFrequency + " resampleFrequencyCheck: " + resampleFrequencyCheck
+ " soundRateCeil: " + soundRateCeil + " soundRateFloor: " + soundRateFloor);
*/
var value:Number = 0;
// Assumes data is in samples of float value
for (var i:int = 0;i < readSampleLength;i+=4)
{
value = dataInput.readFloat();
// Check for sanity of float value
if (value > 1 || value < -1)
throw new Error("Audio samples not in float format");
// Special case with 8bit WAV files
if (sampleBitRate == 8)
value = (bitResolution * value) + bitResolution;
else
value = bitResolution * value;
// Resampling Logic for non-integer sampling rate conversions
jlen = (resampleFrequencyCheck > 0 && i % resampleFrequency < resampleFrequencyCheck) ? soundRateCeil : soundRateFloor;
for (var j:int = 0; j < jlen; j++)
{
writeCorrectBits(tempData, value, channelCount);
}
}
dataOutput.writeBytes(tempData);
}
}
I have once implemented pseudo multithreading in AS3 by splitting the task into chunks, instead of splitting the data into chunks.
My solution might not be optimal, but it worked nicely for me in the context of performing a large Depth-First Search while allowing the Flash game to flow nicely.
Use a variable ticks to count computation "ticks", similar to CPU clock cycles. Every time you perform some operation, you increment this counter by 1. Increment it even more after a heavier operation is performed.
In specific parts of your code, insert checkpoints where you check if ticks > threshold, where threshold is a parameter you want to tune after you have this pseudo multithreading working.
If ticks > threshold at the checkpoint, you save the current state of your task, set ticks to zero, then exit the function.
The method has to be retried later, so here you employ a Timer with an interval parameter that should also be tuned later.
When restarting the method, use the saved state of your paused task to detect where your task should be resumed.
For your specific situation, I would suggest splitting the tasks of the for loops, instead of thinking about the while loop. The idea is to interrupt the for loops, remember their state, then continue from there after the resting interval.
To simplify, imagine that we have only the outmost for loop. A sketch of the new method is:
WhileLoop: while (dataInput.bytesAvailable > 0 && ticks < threshold)
{
if(!didSubTaskA) {
// do subtask A...
ticks += 2;
didSubTaskA = true;
}
if(ticks > threshold) {
ticks = 0;
restTimer.reset();
restTimer.start(); // This dispatches an event that should trigger this method
break WhileLoop;
}
for (var i:int = next_unused_i;i < readSampleLength;i+=4) {
next_unused_i = i+1;
// do subtask B...
ticks += 1;
if(ticks > threshold) {
ticks = 0;
restTimer.reset();
restTimer.start();
break WhileLoop;
}
}
next_unused_i = 0;
didSubTaskA = false;
}
if(ticks > threshold) {
ticks = 0;
restTimer.reset();
restTimer.start();
}
The variables ticks, threshold, restTimer, next_unused_i, and didSubTaskA are important, and can't be local method variables. They could be static or class variables. Subtask A is that part where you "Resampling logic variables", and also the variables used there can't be local variables, so make them class variables as well, so their values can persist when you leave and come back to the method.
You can make it look nicer by creating your own Task class, then storing there the whole state of interrupted state of your "threaded"-algorithm. Also, you could maybe make the checkpoint become a local function.
I didn't test the code above so I can't guarantee it works, but the idea is basically that. I hope it helps

C# Parallel processing concept

I am working on image processing with C# and implementing integral histogram. I am not getting into the details, but assume that I have MxN matrix and each cell value is the sum of itself and its left and upper neighbor, minus left upper corner neighbor. This works fast but I want to make it faster for large images or for real time image processing performance.
matrix[i,j] += matrix[i-1,j] + matrix[i,j-1] - matrix[i-1,j-1];
The actual implementation is:
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
{
int left = 0, upper = 0, u_l_corner = 0;
if (j - 1 >= 0)
{
left = matrix[i, j - 1];
}
if (i - 1 >= 0)
{
upper = matrix[i - 1, j];
}
if (j - 1 >= 0 && i - 1 >= 0)
u_l_corner = matrix[i - 1, j - 1];
matrix[i, j] += left + upper - u_l_corner;
}
So the calculation is dependent on the previous values of cells. Therefore, it does not look like it can be implemented in parallel(at least to me). But still, just want to make sure before go any further..
Can this algorithm be implemented in parallel using Parallel.For or any other method in C#? If so a simple example is highly appreciated, but if not, I better work on to find a "parallel image histogram algorithm", if any exists.
Thanks in advance.
As far as I'm concerned it is possible to make this algorithm parallel but i find no use of doing so if your matrix is relatively small ( time to process is less than few miliseconds ).
If you are very interested in making this algorithm parallel you could make this task splitted to exactly "j" tasks ( number of items in "y" axis ).
Key to doing so is starting first thread to calculate points in first row of this matrice ( [i, 0] ) then starting second thread delayed - second thread should chase first thread - must never overtake preceding thread.

Imposing parallel maximum running time for MatLab function in loops

Fresh to the Matlab, not so familiar with coding and programing in MatLab.
function fucx()
for i = 1:3
for j = 1:3
for k = 1:3
try
%MainFuc()
%TimerFuc()
time = cputime;
time = cputime-time;
a = timer;
set (a, 'executionMode', 'fixedRate')
set (a,'timerfcn','disp(time)')
start(a)
timeStop = time;
if (timeStop>60) % in seconds
disp('RunOutOfTime: Program terminated');
stop(a)
break;
end;
catch
%%Err()
end
end
end
end
end
Thanks a lot for any help.
%%Update%%
I see the recommended answer as below. I've tried this one.
start = tic;
for i=1:1000000
if (mod(i,1000)==0)
if (toc(start) > 2) % here, 2 seconds
error('Took toooo loooong');
end
end
end
The thing I want to assure is that the timer or tic function running in parallel to the MainFuc() and know when to stop the loop.
You should use the "tic" and "toc" functions from matlab, see the documentation here Matlab tic function.
When you call "tic", the timer restarts, and every time you call "toc" it gives you the time in seconds since the last "tic". Then if you call "tic" another time, the timer will restart.
Here is the code you need.
a = 0;
for i = 1:3
for j = 1:3
tic;
for k = 1:10^7
try
%MainFuc()
a = a + 1;
catch
%%Err()
end
%TimerFuc()
time = toc;
if (time>2) % in seconds
disp('RunOutOfTime: Program terminated');
break;
end;
end
end
end

Resources