Writing to Excel sheet based on image difference using matlab - excel

I have some folders named test* from test 1 to test 100 for example, I need to print names of folders as header in first row.
Then I need to check my test image image2 with each image inside these folders if the diff bigger than 0.05 between my test image2 and every images from each folder test* will write 1 otherwise write 0. till to testn.
My code is as follow :
srcFolders = dir('D:\test*');
for folder = 1:length(srcFolders)
path = strcat('D:\',srcFolders(folder).name);
sear = strcat(path, '\*.bmp');
srcFiles = dir(sear);
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
Image1= imread(filename);
Image2 = imread('D:\2','jpeg'); % Image 2
x = diff( Image2 , Image1)
% any suggestion here to get my output for printing in excel
if (x >= 0.05)
xlswrite(xlsfile, srcFiles(i), ‘0’, ‘A1’);
else
xlswrite(xlsfile, srcFiles(i), ‘1’, ‘A1’);
end
end
end
thanks

%On every 'folder loop', increment the column range so you have 1 column by folder
%On every 'file loop', increment the row range so you have 1 row by file
xls_filename = 'foo.xls'; %The name of your xls file
xls_sheet = 'sheet_name'; % Put here the name of the sheet you want to write in
column_range = 'A' % Initialisation of the column range
srcFolders = dir('D:\test*');
for folder = 1:length(srcFolders)
path = strcat('D:\',srcFolders(folder).name);
folder_range = strcat(column_range, '1');
xlswrite(xls_filename, {srcFolders(folder).name}, xls_sheet, folder_range); %Writing the name of the folder in the first row
sear = strcat(path, '\*.bmp');
srcFiles = dir(sear);
row_range = '2';
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
Image1= imread(filename);
Image2 = imread('D:\2','jpeg');
x = diff( Image2 , Image1);
file_range = strcat(column_range, row_range);
if (x >= 0.05)
xlswrite(xls_filename, {'0'}, xls_sheet, file_range ); %Writing '0' in the second row
else
xlswrite(xls_filename, {'1'}, xls_sheet, file_range ); %Writing '1' in the second row
end
row_range = char(row_range + 1); %Moving to the next row
end
column_range = char(column_range + 1); %Moving to the next column
end

Related

How to merge cells without losting data in libreoffice-calc?

Launch libreoffice-calc:
soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"
Launch python shell to write data into the calc:
import uno
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
svcmgr = context.ServiceManager
desktop = svcmgr.createInstanceWithContext("com.sun.star.frame.Desktop", context)
oDoc = desktop.loadComponentFromURL( "private:factory/scalc","_blank", 0, () )
oSheet = oDoc.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("A1:C3")
Write data into oRange.
oRange.setDataArray((('a1','a2','a3'),('b1','b2','b3'),('c1','c2','c3'),))
The calc's appearance now:
I want to merge all data in oRange and format it with vertical and horizontal alignment.
My desired effect in the editing calc.
oRange.merge()
oCell = oSheet.getCellByPosition(0, 0)
oCell.HoriJustify = 2
oCell.VertJustify = 2
Merged data with vertical and horizontal alignment ,previous data in many cells b1-c1 and a2-c2 and a3-c3 lost.
The real effect.
How to fix my code to get the desired effect?
import uno
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
svcmgr = context.ServiceManager
desktop = svcmgr.createInstanceWithContext("com.sun.star.frame.Desktop", context)
oDoc = desktop.loadComponentFromURL( "private:factory/scalc","_blank", 0, () )
oSheet = oDoc.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("A1:C3")
tup = (('a1','a2','a3'),('b1','b2','b3'),('c1','c2','c3'),)
oRange.setDataArray(tup)
target =''
for item in tup:
tmp = ' '.join(item)
target = target + tmp + ' '
target = target.strip()
oRange.merge(True)
oCell = oSheet.getCellByPosition(0, 0)
oCell.String = target
oCell.HoriJustify = 2
oCell.VertJustify = 2
I'm not sure, but I think UNO has no way of knowing that you want to rearrange the data into the merged cell that way. What UNO does is "copy" the data from the "main" cell (the top left one) and "paste" its data into the merged cell. Therefore, what you could do is change the data of the main cell before merging. Check the example below.
# get range
oRange = oSheet.getCellRangeByName("A1:C3")
# build string
flat_list = [str(item) for sublist in oRange.getDataArray() for item in sublist]
string = ' '.join(flat_list)
# put string into main cell
main_cell = oRange.getCellByPosition(0, 0)
main_cell.setString(string)
# merge
oRange.merge()

Calculate percentage change in pandas with rows that contain the same values

I am using Pandas to calculate percentage change(s) between values that occur more than once in the column of interest.
I want to compare the values of last weeks workout provided they're the same exercise type to get the percentage change of (weight used, reps accomplished )
I am able to get the percentages of all the rows which is halfway what I want but the conditional part is missing - so only get the percentages if the exercise_name is of the same value as we want to compare how we improve on a weekly, bi-weekly basis.
ids = self.user_data["exercise"].fillna(0)
dups = self.user_data[ids.isin(ids[ids.duplicated()])].sort_values("exercise")
dups['exercise'] = dups['exercise'].astype(str)
dups['set_one_weight'] = pd.to_numeric(dups['set_one_weight'])
dups['set_two_weight'] = pd.to_numeric(dups['set_two_weight'])
dups['set_three_weight'] = pd.to_numeric(dups['set_three_weight'])
dups['set_four_weight'] = pd.to_numeric(dups['set_four_weight'])
dups['set_one'] = pd.to_numeric(dups['set_one'])
dups['set_two'] = pd.to_numeric(dups['set_two'])
dups['set_three'] = pd.to_numeric(dups['set_three'])
dups['set_four'] = pd.to_numeric(dups['set_four'])
**percent_change = dups[['set_three_weight']].pct_change()**
the last line gets the percentage change for all the rows for column set_three_weight but is unable to do what I want above which is find rows with same name and obtain the percentage change.
UPDATE
Using Group By Solution
ids = self.user_data["exercise"].fillna(0)
dups = self.user_data[ids.isin(ids[ids.duplicated()])].sort_values("exercise")
dups['exercise'] = dups['exercise'].astype(str)
dups['set_one_weight'] = pd.to_numeric(dups['set_one_weight'])
dups['set_two_weight'] = pd.to_numeric(dups['set_two_weight'])
dups['set_three_weight'] = pd.to_numeric(dups['set_three_weight'])
dups['set_four_weight'] = pd.to_numeric(dups['set_four_weight'])
dups['set_one'] = pd.to_numeric(dups['set_one'])
dups['set_two'] = pd.to_numeric(dups['set_two'])
dups['set_three'] = pd.to_numeric(dups['set_three'])
dups['set_four'] = pd.to_numeric(dups['set_four'])
dups['routine_upload_date'] = pd.to_datetime(dups['routine_upload_date'])
# percent_change = dups[['set_three_weight']].pct_change()
# Group the exercises together and create a new cols that represent the percentage delta variation in percentages
dups.sort_values(['exercise', 'routine_upload_date'], inplace=True, ascending=[True, False])
dups['set_one_weight_delta'] = (dups.groupby('exercise')['set_one_weight'].apply(pd.Series.pct_change) + 1)
dups['set_two_weight_delta'] = (dups.groupby('exercise')['set_two_weight'].apply(pd.Series.pct_change) + 1)
dups['set_three_weight_delta'] = (dups.groupby('exercise')['set_three_weight'].apply(pd.Series.pct_change) + 1)
dups['set_four_weight_delta'] = (dups.groupby('exercise')['set_four_weight'].apply(pd.Series.pct_change) + 1)
dups['set_one_reps_delta'] = (dups.groupby('exercise')['set_one'].apply(pd.Series.pct_change) + 1)
dups['set_two_reps_delta'] = (dups.groupby('exercise')['set_two'].apply(pd.Series.pct_change) + 1)
dups['set_three_reps_delta'] = (dups.groupby('exercise')['set_three'].apply(pd.Series.pct_change) + 1)
dups['set_four_reps_delta'] = (dups.groupby('exercise')['set_four'].apply(pd.Series.pct_change) + 1)
print(dups.head())
I think this gets me the result(s) I want, would like someone to confirm

compare multi images with all images in referenced folders using matlab

I have some reference image (I'll call this images as Ref\animal.jpg', 'Ref\food.jpg', 'Ref\gon.jpg ... etc ). Then in each folder i want to compare Image1, Image2, ..., ImageN to each referenced image . I want to summarize the results of the comparison by writing to an Excel file (which has the same name as the folder) (in A1) 'Image 1 = ok', (in B1) 'Image 2 = no', ..., (in the Nth row, 1st column) 'Image N = ok'.
i got the following error , when i use single image its working well but multi images in reference images ( second line ) i got cellfun error .
Error using cellfun
Input #2 expected to be a cell array, was double instead.
any one please can correct the following code ??
%The base file path
path = 'D:';
% Relative reference to reference images
ImageRefLocations = {'Ref\RefI1.jpg', 'Ref\RefI2.png', 'Ref\RefI3.jpg'};
%Base Image location
baseImage = fullfile(path, ImageRefLocations(:));
%The pattern used to choose the folders
folderPattern = 'folder*';
%The image extension
[~, ~, ext] = unique(cellfun(#(f) fileparts(f), baseImage, 'uni', 0));
%The excel extension
ExcelExt = '.xlsx';
msg = {' = no'; ' = ok'};
i0 = cellfun(#(f) imread(f), baseImage, 'uni', 0);
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
isDir = [srcFolders.isdir];
srcFolders = {srcFolders(isDir).name}';
PathedFolders = fullfile(path, srcFolders);
excelFiles = fullfile(path, strcat(srcFolders, ExcelExt));
for i = 1:length(PathedFolders)
f = PathedFolders{i};
after this line i got error ...
Error using cellfun
Input #2 expected to be a cell array, was double instead.
Images = cellfun(#(x) dir(fullfile(f, ['*', x])), ext, 'uni', 0);
Images = vertcat(Images{:});
if isempty(Images)
continue
end
Images = {Images.name}';
[~, ImageNames, ~] = cellfun(#(x) fileparts(x), Images, 'uni', 0);
ImageList = fullfile(f, Images);
match = zeros(size(ImageList));
for j = 1:length(ImageList)
image = imread(ImageList{j});
for k = 1:length(i0)
if ~all(size(image) == size(i0{k}))
continue
end
match(j) = all(image(:) == i0{k}(:));
if match(j)
continue
end
end
end
matchMessage = strcat(Images, msg(match + 1));
xlswrite(excelFiles{i}, matchMessage)
end

write excel file to many folders in directory using matlab

I need to write an excel file to many folders ( folder* ) under D:\ and loop over them to further process individually.
i tried the following code for long time ..
srcFolders = dir('D:\folder*');
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
xlswrite('srcFolders\filename.xls', srcFolders(folder).name,'Sheet1', folder_range);
end
I'm assuming that you want to write different sets of data to a Excel file and were just having some trouble. If that's not accurate comment and let me know.
%Just generating some arbitrary data
data = arrayfun(#(m,n) rand(m,n), randi(50, 9, 1), randi(50, 9, 1), 'uni', 0);
%The base file path
path = 'D:';
%The pattern used to choose the folders
folderPattern = 'folder*';
%The files you want to write to
srcFiles = {'A', 'B', 'D'};
%And the extension
ext = '.xlsx';
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
srcFolders = fullfile(path, {srcFolders.name});
%Construct the full file path
fullPath = cellfun(#(f) fullfile(f, strcat(srcFiles(:), ext)), srcFolders, 'uni', 0);
fullPath = vertcat(fullPath{:});
%Write the data to the files
for i = 1:length(fullPath)
xlswrite(fullPath{i}, data{i})
end
Edit:
Based on OP's feed.
Note for the second overhaul. I didn't test this and I'm done. This was way to much for a single question and you are abusing the way this website is supposed to work.
%The base file path
path = 'D:';
%Relative reference to reference images
ImageRefLocations = {'Ref\RefI1.jpg', 'Ref\RefI2.png', 'Ref\RefI3.jpg'};
%Base Image location
baseImage = fullfile(path, ImageRefLocations(:));
%The pattern used to choose the folders
folderPattern = 'folder*';
%The image extension
[~, ~, ext] = unique(cellfun(#(f) fileparts(f), baseImage, 'uni', 0));
%The excel extension
ExcelExt = '.xlsx';
msg = {' = no'; ' = ok'};
i0 = cellfun(#(f) imread(f), baseImage, 'uni', 0);
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
isDir = [srcFolders.isdir];
srcFolders = {srcFolders(isDir).name}';
PathedFolders = fullfile(path, srcFolders);
excelFiles = fullfile(path, strcat(srcFolders, ExcelExt));
for i = 1:length(PathedFolders)
f = PathedFolders{i};
Images = cellfun(#(x) dir(fullfile(f, ['*', x])), ext, 'uni', 0);
Images = vertcat(Images{:});
if isempty(Images)
continue
end
Images = {Images.name}';
[~, ImageNames, ~] = cellfun(#(x) fileparts(x), Images, 'uni', 0);
ImageList = fullfile(f, Images);
match = zeros(size(ImageList));
for j = 1:length(ImageList)
image = imread(ImageList{j});
for k = 1:length(i0)
if ~all(size(image) == size(i0{k}))
continue
end
match(j) = all(image(:) == i0{k}(:));
if match(j)
continue
end
end
end
matchMessage = strcat(Images, msg(match + 1));
xlswrite(excelFiles{i}, matchMessage)
end

Windows native script to change text file based on line and column number

A simulation program I'm using requires a text based input file. I need to run the simulation in different configurations by changing the values in the text file. I am looking for a way to do this automatically with any script that does not require third party compilers. It has to run natively on a Windows XP machine. I only have a little bit of coding experience in MATLAB and FORTRAN.
I will describe my idea of what the script should do in some pseudo-code:
% speed.txt - a txt file with 10 different speed values
% coeff.txt - a txt file with 10 different coefficients
% dist.txt - a txt file with 5 different distance values
% input.txt - the txt file containing the input parameters. This file has to be changed.
% output.txt- the output of the simulation
% sp - the i-th speed value
% co - the i-th coeff value
% di - the j-th distance value
% D:\FO - Final Output folder
Read input.txt
for i = 1:10
Display i on screen % so I know how much of the batch is done
Go to line 37, overwrite 1st four characters with i-th value from speed.txt
Go to line 68, overwrite 1st eight characters with i-th value from coeff.txt
for j = 1:5
Display j on screen % so I know how much of the batch is done
Go to line 67, overwrite 1st five characters with j-th value from dist.txt
Run simulation.exe
When simulation is done, get output.txt, rename it to "output_sp_co_di.txt"
and move the file to D:\FO
end
end
I hope that this is possible with a .bat or .vbs script (or anything else that will run natively). All help is greatly appreciated.
EDIT: after some advice I started a vbs script. I have never used that language before but pulled the thing here under together from scraps on the internet:
Option Explicit
Dim objFSO, strTextFile, strData, strLine, arrLines
Dim filesys, filetxt, path
Dim speed(10), ct(10), dist(4), text(73), d(4)
Dim i, j, k
i = 0
j = 0
k = 0
speed(0) = 3.0
speed(1) = 5.0
speed(2) = 7.0
speed(3) = 9.0
speed(4) = 11.0
speed(5) = 13.0
speed(6) = 15.0
speed(7) = 17.0
speed(8) = 19.0
speed(9)= 21.0
speed(10)= 22.0
ct(0) = 0.987433
ct(1) = 0.816257
ct(2) = 0.816361
ct(3) = 0.720357
ct(4) = 0.418192
ct(5) = 0.239146
ct(6) = 0.154534
ct(7) = 0.107608
ct(8) = 0.079057
ct(9)= 0.060437
ct(10)= 0.053465
dist(0) = 173.48
dist(1) = 260.22
dist(2) = 346.96
dist(3) = 433.7
dist(4) = 520.44
d(0) = 2
d(1) = 3
d(2) = 4
d(3) = 5
d(4) = 6
CONST ForReading = 1
'name of the text file
strTextFile = "TurbSim.inp"
'Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Open the text file - strData now contains the whole file
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll
'Split the text file into lines
arrLines = Split(strData,vbCrLf)
'Step through the lines
For Each strLine in arrLines
text(i) = strLine
i = i + 1
Next
'Open text file to write to
path = objFSO.GetAbsolutePathName("D:\Sandbox\TurbSim.inp")
For i = 0 To 10
If i = 0 Then
text(37) = Replace(text(37),"UUUU",speed(i))
text(68) = Replace(text(68),"CCCCCCCC",ct(i))
Else
text(37) = Replace(text(37),speed(i-1),speed(i))
text(68) = Replace(text(68),ct(i-1),ct(i))
End If
For j = 0 To 4
If j = 0 Then
text(67) = Replace(text(67),"DDDDD",dist(j))
Else
text(67) = Replace(text(67),dist(j-1),dist(j))
End If
Set filetxt = objFSO.opentextfile("D:\Sandbox\TurbSim.inp", 2, True)
For k = 0 To 73
if k = 73 Then
filetxt.write text(k)
Else
filetxt.write text(k) & vbCr & vbLf
End If
objFSO.CopyFile "D:\Sandbox\TurbSim.inp", _
"D:\Sandbox\input\TurbSim_" & speed(i) & "_" & d(j) &"D.inp"
Next
filetxt.close
Next
Next
' wscript.echo text(37)
' wscript.echo text(68)
' wscript.echo text(67)
filetxt.Close
'Cleanup
' Set filesys = Nothing
Set objFSO = Nothing
Problem is now that the distance part (the j-loop) is not working properly. From the output generated (TurbSim_speed_dD.inp) I see that only the last distance (520.44) is used. I don't really understand why, I'll look into that later. If anyone has a suggestion for improvement, then you're ideas are always welcome.
The Batch file below is a .bat version of your vbs script:
#echo off
SetLocal EnableDelayedExpansion
REM Auxiliary macro for easier replacements
set Replace=for /F "tokens=1,2 delims==" %%x in
:: speed - vector with 11 different speed values
Set i=0
For %%s in (3.0 5.0 7.0 9.0 11.0 13.0 15.0 17.0 19.0 21.0 22.0) do (
Set speed[!i!]=%%s
Set /A i+=1
)
:: ct - vector with 11 different coefficients
Set i=0
For %%c in (0.987433 0.816257 0.816361 0.720357 0.418192 0.239146 0.154534 0.107608 0.079057 0.060437 0.053465) do (
Set ct[!i!]=%%c
Set /A i+=1
)
:: dist - vector with 5 different distance values
Set i=0
For %%d in (173.48 260.22 346.96 433.7 520.44) do (
Set dist[!i!]=%%d
Set /A i+=1
)
REM d does not need to be a vector because d(i) = i+2
:: Split the text file into lines, and Step through the lines
Set i=0
For /F "delims=" %%l in (TurbSim.inp) do (
Set "text[!i!]=%%l"
Set /A i=i+1
)
For /L %%i in (0,1,10) do (
If %%i == 0 (
%Replace% ("UUUU=!speed[%%i]!") do set "text[37]=!text[37]:%%x=%%y!"
%Replace% ("CCCCCCCC=!ct[%%i]!") do set "text[68]=!text[68]:%%x=%%y!"
) Else (
set /A iM1=i-1
%Replace% ("!iM1!") do set speed_iM1=!speed[%%x]!& set ct_iM1=!ct[%%x]!
%Replace% ("!speed_iM1!=!speed[%%i]!") do set "text[37]=!text[37]:%%x=%%y!"
%Replace% ("!ct_iM1!=!ct[%%i]!") do set "text[68]=!text[68]:%%x=%%y!"
)
For /L %%j in (0,1,4) do (
If %%j == 0 (
%Replace% ("DDDDD=!dist[%%j]!") do set "text[67]=!text[67]:%%x=%%y!"
) Else (
set /A jM1=j-1
%Replace% ("!jM1!") do set dist_jM1=!dist[%%x]!
%Replace% ("!dist_jM1!=!dist[%%j]!") do set "text[67]=!text[67]:%%x=%%y!"
)
set /A d=j+2
(For /L %%k in (0,1,73) do (
if %%k == 73 (
set /P =!text[%%k]!< NUL
) Else (
echo !text[%%k]!
)
)) > "D:\Sandbox\input\TurbSim_!speed[%%i]!_!d!D.inp"
)
)
echo %text[37]%
echo %text[68]%
echo %text[67]%
Notes:
1- This is a first attempt Batch file based on your vbs script; I really don't understand what you tried to do and just did a direct translation. It seems that the requirements you state in the question are not the same of the vbs script. Any problem may be solved if you give me specific details.
2- Previous Batch file remove any empty line from the input file. This may be solved if needed.
3- The text replacement in Batch is textual, NOT by numeric value. Any number must be written exactly the same as the array values in order to be replaced. I think the same behaviour apply to vbs.
4- Input file must not contain certain special Batch characters, like ! ^ and others. This may be fixed in certain cases only.
I have managed to pull together a .vbs script from various internet references that does what I want. The script does the following:
Reads in original input file
Stores the data line by line in the text array
Reads in speed, coefficient and distance data from text file
Stores this data in separate speed, coefficient and distance arrays line by line.
Takes first entry of speed and coeff. array and writes it at appropriate places in the
text array
Loops through distance array and writes the text array line by line back to an .inp file
Runs the simulation with the edited input file
Waits until simulation is terminated.
Copy output files from current directory to output folder, renaming them in the process.
Wait 10 seconds to make sure copying is finished
10.Repeat steps 6-10 with all other entries of speed and coeff. array
Requirements for this script to work:
A. An input folder with an .inp file that has "UUUU", "DDDDD", "CCCCCCCC" written at places where respectively the velocity, distance and coefficient should be written.
B. An output folder
C. The files speed.txt, ct.txt and distance.txt containing the speed, coefficient and distance values to be used.
D. You should run this script from an admin account. Otherwise you don't have the permission to check if the simulation is still running with the "Win32_process".
Option Explicit
Dim objFSO, strTextFile, strTData, strLine, arrTLines
Dim strVelFile, strCtFile, strDistFile
Dim strVData, strCData, strDData
Dim arrVLines, arrCLines, arrDLines
Dim strLineV, strLineC, strLineD
Dim strComputer, oWMI, colEvents, oEvent
Dim filesys, filetxt, path, curPath
Dim speed(), ct(), dist(), text(73)
Dim oShell
Dim i, j, k
i = 0
j = 0
k = 0
' Subroutine to start an executable
Sub Run(ByVal sFile)
Dim shell
Set shell = CreateObject("WScript.Shell")
shell.Run Chr(34) & sFile & Chr(34), 1, false
Set shell = Nothing
End Sub
CONST ForReading = 1
' Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Create Shell object. Needed to change directories
Set oShell = CreateObject("WScript.Shell")
'Change current directory to \input folder
oShell.CurrentDirectory = ".\input"
' The name of the original input file
' with the UUUU, DDDDD, CCCCCCC in the correct places
strTextFile = "TurbSim.inp"
' Open the text file and read it all into strTData
strTData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll
' Go back to parent folder as there all the other .txt files reside
Set oShell = CreateObject("WScript.Shell")
oShell.CurrentDirectory = ".\.."
' name of other input text files
strVelFile = "speed.txt"
strCtFile = "ct.txt"
strDistFile = "dist.txt"
' Open the text file - str*Data now contains the whole file
strVData = objFSO.OpenTextFile(strVelFile,ForReading).ReadAll
strCData = objFSO.OpenTextFile(strCtFile,ForReading).ReadAll
strDData = objFSO.OpenTextFile(strDistFile,ForReading).ReadAll
' Split the text files into lines
arrTLines = Split(strTData,vbCrLf)
arrVLines = Split(strVData,vbCrLf)
arrCLines = Split(strCData,vbCrLf)
arrDLines = Split(strDData,vbCrLf)
' Give the speed, ct and dist arrays their dimension
ReDim speed(UBound(arrVLines))
ReDim ct(UBound(arrCLines))
ReDim dist(UBound(arrDLines))
' Add data to arrays text, speed, ct and dist line by line
For Each strLine in arrTLines
text(i) = strLine
i = i + 1
Next
'Reset counter
i = 0
' Step through the lines speed
For Each strLineV in arrVLines
speed(i) = strLineV
i = i + 1
Next
i = 0
' Step through the lines ct
For Each strLineC in arrCLines
ct(i) = strLineC
i = i + 1
Next
i = 0
' Step through the lines dist
For Each strLineD in arrDLines
dist(i) = strLineD
i = i + 1
Next
i = 0
' Get the current path. Needed to point to the executable.
curPath = objFSO.GetAbsolutePathName(".")
For i = 0 To UBound(speed)
If i = 0 Then
' Replace the UUUU and CCCCCCCC values
' Only the first run.
text(37) = Replace(text(37),"UUUU",speed(i))
text(68) = Replace(text(68),"CCCCCCCC",ct(i))
Else ' Replace the previous speed and coeff. values with the current one
text(37) = Replace(text(37),speed(i-1),speed(i))
text(68) = Replace(text(68),ct(i-1),ct(i))
End If
For j = 0 To UBound(dist)
If j = 0 And i = 0 Then
' Replace the DDDDD value (only at first run)
text(67) = Replace(text(67),"DDDDD",dist(j))
ElseIf j = 0 And i > 0 Then
' Replace the distance value of the previous speed/coeff. case
' with the current one
text(67) = Replace(text(67), dist(UBound(dist)), dist(j))
Else ' Replace the previous distance value with the current one
text(67) = Replace(text(67),dist(j-1),dist(j))
End If
Set filetxt = objFSO.opentextfile(curPath & "\TurbSim.inp", 2, True)
For k = 0 To 73 ' Write to an .inp file line by line
if k = 73 Then ' Prevent adding a new line at the end
filetxt.write text(k)
Else
filetxt.write text(k) & vbCr & vbLf
End If
Next
filetxt.close
' Execute the simulation
Run curPath &"\TurbSimGW.exe"
strComputer = "."
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
'# Create an event query to be notified within 3 seconds when TurbSimGW is closed
Set colEvents = oWMI.ExecNotificationQuery _
("SELECT * FROM __InstanceDeletionEvent WITHIN 3 " _
& "WHERE TargetInstance ISA 'Win32_Process' " _
& "AND TargetInstance.Name = 'TurbSimGW.exe'")
'# Wait until TurbSimGW is closed
Set oEvent = colEvents.NextEvent
' Copy and rename output files
objFSO.CopyFile curPath & "\TurbSim.wnd", _
curPath & "\output\TurbSim_" & speed(i) & "_" & j+2 &"D.wnd"
wscript.sleep 10000 ' time to allow copying the files
Next
Next
'' ' wscript.echo text(37)
'' ' wscript.echo text(68)
'' ' wscript.echo text(67)
filetxt.Close
' Cleanup
' Set filesys = Nothing
Set objFSO = Nothing
Now it works flawlessly. However A solution to requirement D would be nice. My work-around is instead of checking if the program is terminated I just set a sleep value. For this value of sleep I know for sure the simulation is done and the output files are ready to copy.

Resources