How do I load variables from a file back into Scala? - scala

I have variables in scala that have their values written to an external file in this format:
1
2
0
0.5
0.62
This is my code that puts them in the file called "myVars.txt":
val pw = new java.io.PrintWriter("myVars.txt")
pw.println(beginGameCounter)
pw.println(triangleCount)
pw.println(triangleScore)
pw.println(lives)
pw.println(curPlayer.getX)
pw.println(curPlayer.getY)
pw.close
How would I load these variables back into scala and replace the old variables with these new variables (for example the old variable for beginGameCounter is 0, then when I load the file, I want it to become 1)?
Thank you.

You could try something like this:
val values = Source.fromFile(pathToFile).getLines.toList
beginGameCounter = values(0)
triangleCount = values(1)
triangleScore = values(2)
lives = values(3)
currPlayer.setX(values(4))
currPlayer.setY(values(5))
This of course assumes that the what variable is on what line is consistent.

Related

How to automatically change variable names given a new input file name

I am importing data from a .mat file and then extracting certain signals from it and I call this data, data. data is a 1x1 struct with 1 field, FT_est_X, where X is the the particular run that I collected the samples from. Here is the code snippet of how I do that.
data = load('site_data_all_2.mat');
t = data.FT_est_2.time;
% estimated data
Fx = data.FT_est_2.signals(1).values;
Fy = data.FT_est_2.signals(2).values;
Fz = data.FT_est_2.signals(3).values;
Mx = data.FT_est_2.signals(4).values;
My = data.FT_est_2.signals(5).values;
Mz = data.FT_est_2.signals(6).values;
So, you can see that this data was collected from run 2. Now, let's say I want to load in a file named site_data_all_3.mat (run 3), what happens is that all the data below %estimated data changes its name--everything stays the same, except the 2 becomes a 3 (e.g. Fx would be Fx = data.FT_est_3.signals(1).values;. Currently, I have to manually enter in the 3 for each variable; can anyone tell me how I can only change the file name and it will automatically change the variable names for me? Essentially, I just want it to be Fx = data.name_of_struct_field.signals(1).values.
Thank you!
You could construct the string some programmatic way (maybe with an iteration variable), but here's the simple answer of defining the fieldname as a string and simply using it. At the next iteration, update the fieldname variable and repeat.
fieldname = 'FT_est_2';
Fx = data.(fieldname).signals(1).values;

Matlab load mat into variable

When loading data from a .Mat file directly into a variable, it stores an struct instead of the variable itself.
Example:
myData.mat contains var1, var2, var3
if I do:
load myData.mat
it will create the variables var1, var2 and var3 in my workspace. OK.
If I assign what load returns to a variable, it stores an struct. This is normal since I'm loading several variables.
foo = load('myData.mat')
foo =
struct with fields:
var1
var2
var3
However suppose that I'm only interested in var1 and I want to directly store into a variable foo.
Load has an option of loading only specific variables from a .mat file, however it still stores an struct
foo = load('myData.mat', 'var1')
foo =
struct with fields:
var1
I want var1 to be directly assigned to foo.
Of course I can do:
foo = load('myData.mat', 'var1')
foo = foo.var1;
But it should be a way of doing this automatically in one line right?
If the MAT-file contains one variable, use
x = importdata(mat_file_name)
load does not behave this way otherwise load would behave inconsistently depending upon the number of variables that you have requested which would lead to an extremely confusing behavior.
To illustrate this, imagine that you wrote a general program that wanted to load all variables from a .mat file, make some modification to them, and then save them again. You want this program to work with any file so some files may have one variable and some may have multiple variables stored in them.
If load used the behavior you've specified, then you'd have to add in all sorts of logic to check how many variables were stored in a file before loading and modifying it.
Here is what this program would look like with the current behavior of load
function modifymyfile(filename)
data = load(filename);
fields = fieldnames(data);
for k = 1:numel(fields)
data.(fields{k}) = modify(data.(fields{k}));
end
save(filename, '-struct', 'data')
end
If the behavior was the way that you think you want
function modifymyfile(filename)
% Use a matfile to determine the number of variables
vars = whos(matfile(filename));
% If there is only one variable
if numel(vars) == 1
% Assign that variable (have to use eval)
tmp = load(filename, vars(1).name);
tmp = modify(tmp);
% Now to save it again, you have to use eval to reassign
eval([vars(1).name, '= tmp;']);
% Now resave
save(filename, vars(1).name);
else
data = load(filename);
fields = fieldnames(data);
for k = 1:numel(fields)
data.(fields{k}) = modify(data.(fields{k}));
end
save(filename, '-struct', 'data');
end
end
I'll leave it to the reader to decide which of these is more legible and robust.
The best way to do what you're trying to do is exactly what you've shown in your question. Simply reassign the value after loading
data = load('myfile.mat', 'var1');
data = data.var1;
Update
Even if you only wanted the variable to not be assigned to a struct when a variable was explicitly specified, you'd still end up with inconsistent behavior which would make it difficult if my program accepted a list of variables to change as a cell array
variables = {'var1', 'var2'}
data = load(filename, variables{:}); % Would yield a struct
variables = {'var1'};
data = load(filename, variables{:}); % Would not yield a struct
#Suever is right, but in case you wish for a one-line workaround this will do it:
foo = getfield(load('myData.mat'), 'var1');
It looks ugly but does what you want:
foo = subsref(matfile('myData.mat'),struct('type','.','subs','var1'))
Use matfile allows partial loading of variables into memory i.e. it only loads what is necessary. The function subsref does the job of the indexing operator "." in this case.

Read many Matlab files, change them and create many new Matlab files in Python

Now the problem is how to put all the "new" matlab files in a Folder. Otherwise I am mixing the unswapped with the swapped ones. And my files are huge!
I wrote code, but even though I specify where to put the files, it does not work!
read_files = glob.glob('/home/FeaturesF3/*.mat')
write_files = glob.glob('/home/Swapped/'
x2D = np.array([])
for f in read_files:
x3D = sio.loadmat(f)['features']
x2D = x3D.swapaxes(0,1)
outputFileName = join (write_files, f + '_swapped.mat')
sio.savemat(outputFileName, {"x2D":x2D})
I want to read many Matlab files (20) which are inside the folder "FeaturesF3", swap the indexes and then create other 20 new Matlab files.
With my code, I only get 1 "*.mat" file.
Where and how do I have to specify the name of the "new" Matlab files, and that there must be 20 and not just 1?
This is my code:
read_files = glob.glob('/home/FeaturesF3/*.mat')
x2D = np.array([])
for f in read_files:
x3D = sio.loadmat(f)['features']
x2D = x3D.swapaxes(0,1)
sio.savemat('/home/FeaturesF3/*.mat', {"x2D":x2D})
sio.savemat('/home/FeaturesF3/*.mat', {"x2D":x2D})
is your problem: you're always using the same file name (which, by the way, looks invalid).
What about simply appending to the input file name?
for f in read_files:
…
sio.savemat(f + "_swapped.mat", {"x2D":x2D})

matlab How to use a textstring as input parameter in functions

I would like to use a dataset filename "AUDUSD" in several functions. It would be easier for me, just to change the filename "AUDUSD" to a more general name like "FX" and then using the abbreviation "FX" in other_matlab functions, e.g. double(). But matlab does not know the name "FX" (that should be assigned to the dataset "AUDUSD") in the code below... Any suggestions?
CODE:
FX = 'AUDUSD';
load(FX); %OKAY !!! FX works as input to open file AUDUSD!
Svars = {'S_bid','S_offer'};
Fvars = {'F_bid','F_offer'};
vS = double(FX,Svars); % FX does NOT work as input for the file AUDUSD
There is no double() function that accepts multiple cell arrays as arguments (this is what happens when you call double(FX,Svars)).
If you call double(FX), then each character in FX is interpreted for its ASCII value and then cast to double. So you get [ 65.0 85.0 68.0 85.0 83.0 68.0 ]. This is the behavior for the double() function if you provide a vector: each individual value in the vector is cast to double.
You'd have to provide more details on what you're trying to accomplish to give any more suggestions.
I have a different example, maybe you will better understand my point. The key work I would like to process is as follows:
I have got a folder with "dataset" files. I would like to loop through this folder, entering in any datasetfile, extracting the 2nd and 3rd column of each dataset file, and constructing only ONE new datasetfile with all 2nd and 3rd columns of the datasetfiles.
One problem is that the size of the datasetfiles are not the same, so I tried to translate a datasetfile into a double-matrix and then consolidate all double matrices into ONE double matrx.
Here my code:
folder_string = 'Diss_Data/Raw';
FolderContent = dir(folder_string);
No_ds = numel(FolderContent);
for i = 1:No_ds
if isdir(FolderContent(i).name)==0
file_string = FolderContent(i).name;
file_path = strcat(folder_string,'/',file_string)
dataset_filename = file_string(1:6);
load(file_path); %loads the suggested datasetfile; OKAY
M = double(dataset_filename);% returns an ASCII code number; WRONG; should transfer the datasetfile into a matrix M
vS = M(:,2:3);
%... to be continued
end
end

Import variables from file

Hi so I have a file called config.m that contains a list of variables along with some comments. I wanted to basically load that script up through another matlab script so that the variables would be recognized and used and could also be changed easily. Here is what my file with the variables looks like.
%~~~~~~~~~~~~~~~~~
%~~~[General]~~~~~
%~~~~~~~~~~~~~~~~~
%path to samtools executable
samtools_path = '/home/pubseq/BioSw/samtools/0.1.8/samtools';
%output_path should be to existing directory, script will then create tumour
%and normal folders and link the bam files inside respectively
output_path = '/projects/dmacmillanprj/testbams';
prefix = %prefix for output files
source_file = % from get_random_lines.pl, what is this?
% The window size
winSize = '200';
% Between 0 and 1, i.e. 0.7 for 70% tumour content
tumour_content = '1';
% Should be between 0 and 0.0001
gc_window = 0.005;
% Path to tumour bam file
sample_bam = '/projects/analysis/analysis5/HS2310/620GBAAXX_4/bwa/620GBAAXX_4_dupsFlagged.bam';
% Path to normal bam file
control_bam = '/projects/analysis/analysis5/HS2381/620GBAAXX_6/bwa/620GBAAXX_6_dupsFlagged.bam';
I have tried this:
load('configfile.m')
??? Error using ==> load
Number of columns on line 2 of ASCII file /home/you/CNV/branches/config_file/CopyNumber/configfile.m
must be the same as previous lines.
Just run the script config.m inside another script as
config
Remember config.m file should be in the working directory or in MATLAB path.
However I would recommend you to create a function from this script and return a structure with all the parameters as fields. Then you will be more flexible in your main script since you can assign any name to this structure.
function param = config()
param.samtools_path = '/home/pubseq/BioSw/samtools/0.1.8/samtools';
param.output_path = '/projects/dmacmillanprj/testbams';
% ... define other parameteres
In the main script:
P = config;
st_dir = P.samtools_path;
% ...etc...
Alternatively, you could define a class with constant properties in your config.m file:
classdef config
properties (Constant)
samtools_path = '/home/pubseq/BioSw/samtools/0.1.8/samtools';
output_path = '/projects/dmacmillanprj/testbams';
end
end
Thereby, you can access the class properties in another script:
config.samtools_path
config.output_path
To round it up, you could place your config.m file into a package (+ folder) and import it explicitly in your script. Assuming your package would be called "foo" and the "+foo" folder on your Matlab path, your script would look as follows:
import foo.config
foo.config.samtools_path
foo.config.output_path
load() is not suitable for files that contain text (even in the form of matlab comments.)
You should use textscan() or dlmread(), specifying to them that you want to skip two header lines or that you want to treat '%' as indicating a comment.