shuffling the string code in any language - matlab

I am trying to code a program to shuffle the dna sequence as much as
possible to destroy the order in the sequence. i have written matlab
code but its too slow. Also i was looking into hamming distance
measure or levenstein measure, also how can i incorporate those measure to
ensure proper shuffling. the rules I followed in shuffling
rule 1: the ith residue should not be near i-1,i-2,i-3,i+1,i+2,i+3
rule 2: in next arrangement i's new position and old position must be at 20 place difference. i.e. if A had 1st position in the string in
shuffled string it must be more than equal to 21st position.
function seq=shuffling(str)
len=length(str);
t1=0.4;
seqlen=1:len;
if(len>150)
t1=0.90;
elseif(len>=100)
t1=0.7;
end
while 1
shufseq=randperm(len);
temp1=diff([seqlen;shufseq]);%differences between order indices of original and shuffled arrangement
if(isempty(find(temp1==0)) && isempty(find(diff(shufseq)==1|diff(shufseq)==2 |diff(shufseq)==3 |diff(shufseq)==4 |diff(shufseq)==-1|diff(shufseq)==-2 |diff(shufseq)==-3 |diff(shufseq)==-4)))% rule 1
if((length(find(temp1>20|temp1<-20))/len)>t1)%rule 2 if ratio of (counts of arrangements/length of the string) should be more than one after certain length threshhold(=t1)
break
else
continue
end
else
continue
end
end
seq=str(shufseq);

i came up with one alternative. i.e. knowing the composition or counts of unique alphabets in the string. then choosing randomly among these alphabets and reducing their count by 1 in each iteration. this iteration is over the length of the sequence.
function seq=newshuffle(str)
%#codegen
len=length(str);
seq=[];
ndict= ['A';'C';'G';'T'];
ncomp=struct2array(count(str))';
for l=1:len
while 1
x=randi(4,1,1);
if ncomp(x)~=0
break;
end
end
seq=[seq,ndict(x)];
ncomp(x)=ncomp(x)-1;
end
end

Related

Longest increasing subsequence with K exceptions allowed

Hello I am stuck with my homework which is: given sequence of integers, find the longest subsequence whose elements are ordered in an increasing order. Up to k exceptions that means at most k times, the next number in the sequence is smaller than previous one. Output should be the length of the longest such subsequence.
I found many examples of finding LIS, even one with one change allowed, but I don't know how to check with k changes. Here is the link to post with one change: https://www.geeksforgeeks.org/longest-increasing-subarray-with-one-change-allowed/amp/
You can set up k counters and traverse the sequence. Once you reach an exception you go to the next counter. If you reached the k+1-th counter you drop the first one and shift all your counters by one so that the n+1th counter becomes the nth. With each step you store the current index together with the sum of your k counters as the total sequence length. Take the maximum of that in the end
Explanation:
The question is only where the longest subsequence begins. If you know that you know how long it is (until the k+1) exception or the end of the sequence). Let this point be s.
The longest subsequence can only begin at an exception or at the start of the sequence. If not you could add the s-1 item to the sequence without adding an exception and form a longer subsequence.
The method above computes all possible longest subsequences and chooses the longest candidate in the end.

Efficient Enumeration of subsets of variable size

There are 2 variables: i and j.
i runs from 1 to fixed constant N. j runs from 1 to M(i), meaning we have an array
M=zeros(N,1);
M=[3,2,5,4];
Also S is a set of say 10 integers. Corresponding to every i, I have to find all possible ways of choosing numbers from S up to a given max limit M(i).
My code:
desired_enumerations={};
for i=1:N
for j=1:M(i)
a = combnk(S,j);
for k=1:size(a,1)
desired_enumerations{end+1,1}=a(k,:);
end
end
end
My question:
I want to pre-compute all possible subsets of S up to max(M) elements outside the double for loop and then use that data inside the for loops so i don't have to enumerate the subsets inside double for loop and avoid repeated calculations.
What is an efficient way to do this?
EDIT:
Just as a bonus if someone could also give the time-complexity of the code in big-O notation. Or i can open a new question.

'Find' function working incorrectly, have tried floating point accuracy resolution

I have vertically concatenated files from my directory into a matrix that is about 60000 x 15 in size (verified).
d=dir('*.log');
n=length(d);
data=[];
for k=1:n
data{k}=importdata(d(k).name);
end
total=[];
for k=1:n
total=[total;data{n}];
end
I am using a the following 32-iteration loop and the 'Find" function to locate row numbers where the final column is an integer corresponding to the integer iteration of the loop:
for i=1:32
v=[];
vn=[];
[v,vn]=find(abs(fix(i)-fix(total))<eps);
g=length(v)
end
I have tried to account for the floating point accuracy by using 'fix' on values of 'i' and values from matrix 'total', in addition to taking their absolute difference and checking it to be less than a tolerance of 'eps' (floating-point relative accuracy function), up to a tolerance of .99.
The 'Find' function is not working correctly. It is only working for certain integers (although it should be locating all of them (1-32)), and for the integers it does find the values are incomplete.
What is the problem here? If 'Find' is inadequate for this purpose, what is a suitable alternative?
You are getting a lot of zeros because you are looking not just at the 15th column of data but the entire data matrix so you are going to have a lot of non-integers.
Also, you're using fix on both numbers and since floating point errors can cause the number to be slightly above and below the desired integer, this will cause the ones that are below to round down an integer lower than what you'd expect. You should use round to round to the nearest integer instead.
Rather than using find to do this, I would use simple boolean logic to determine the value of the last column
for k = 1:32
% Compare column 15 to the current index
matches = abs(total(:,end) - k) < eps;
% Do stuff with these matches
g = sum(matches); % Count the matches
end
Depending on what you want to actually do with the data, you may be able to use the last column as an input to accumarray to perform an operation on each group.
As a side note, you can replace the first chunk of code with
d = dir('*.log');
data = cellfun(#importdata, {d.name}, 'UniformOutput', false);
total = cat(1, data{:});

recording 'bursts' of samples at 300 samples per sec

I am recording voltage changes over a small circuit- this records mouse feeding. When the mouse is eating, the circuit voltage changes, I convert that into ones and zeroes, all is well.
BUT- I want to calculate the number and duration of 'bursts' of feeding- that is, instances of circuit closing that occur within 250 ms (75 samples) of one another. If the gap between closings is larger than 250ms I want to count it as a new 'burst'
I guess I am looking for help in asking matlab to compare the sample number of each 1 in the digital file with the sample number of the next 1 down- if the difference is more than 75, call the first 1 the end of one bout and the second one the start of another bout, classifying the difference as a gap, but if it is NOT, keep the sample number of the first 1 and compare it against the next and next and next until there is a 75-sample difference
I can compare each 1 to the next 1 down:
n=1; m=2;
for i = 1:length(bouts4)-1
if bouts4(i+1) - bouts4(i) >= 75 %250 msec gap at a sample rate of 300
boutend4(n) = bouts4(i);
boutstart4(m)= bouts4(i+1);
m = m+1;
n = n+1;
end
I don't really want to iterate through i for both variables though...
any ideas??
-DB
You can try the following code
time_diff = diff(bouts4);
new_feeding = time_diff > 75;
boutend4 = bouts4(new_feeding);
boutstart4 = [0; bouts4(find(new_feeding) + 1)];
That's actually not too bad. We can actually make this completely vectorized. First, let's start with two signals:
A version of your voltages untouched
A version of your voltages that is shifted in time by 1 step (i.e. it starts at time index = 2).
Now the basic algorithm is really:
Go through each element and see if the difference is above a threshold (in your case 75).
Enumerate the locations of each one in separate arrays
Now onto the code!
%// Make those signals
bout4a = bouts4(1:end-1);
bout4b = bouts4(2:end);
%// Ensure column vectors - you'll see why soon
bout4a = bout4a(:);
bout4b = bout4b(:);
% // Step #1
loc = find(bouts4b - bouts4a >= 75);
% // Step #2
boutend4 = [bouts4(loc); 0];
boutstart4 = [0; bouts4(loc + 1)];
Aside:
Thanks to tail.b.lo, you can also use diff. It basically performs that difference operation with the copying of those vectors like I did before. diff basically works the same way. However, I decided not to use it so you can see how exactly your code that you wrote translates over in a vectorized way. Only way to learn, right?
Back to it!
Let's step through this slowly. The first two lines of code make those signals I was talking about. An original one (up to length(bouts) - 1) and another one that is the same length but shifted over by one time index. Next, we use find to find those time slots where the time index was >= 75. After, we use these locations to access the bouts array. The ending array accesses the original array while the starting array accesses the same locations but moved over by one time index.
The reason why we need to make these two signals column vector is the way I am appending information to the starting vector. I am not sure whether your data comes in rows or columns, so to make this completely independent of orientation, I'm going to make sure that your data is in columns. This is because if I try to append a 0, if I do it to a row vector I have to use a space to denote that I'm going to the next column. If I do it for a column vector, I have to use a semi-colon to go to the next row. To completely avoid checking to see whether it's a row or column vector, I'm going to make sure that it's a column vector no matter what.
By looking at your code m=2. This means that when you start writing into this array, the first location is 0. As such, I've artificially placed a 0 at the beginning of this array and followed that up with the rest of the values.
Hope this helps!

find discretization steps

I have data files F_j, each containing a list of numbers with an unknown number of decimal places. Each file contains discretized measurements of some continuous variable and
I want to find the discretization step d_j for file F_j
A solution I could come up with: for each F_j,
find the number (n_j) of decimal places;
multiply each number in F_j with 10^{n_j} to obtain integers;
find the greatest common divisor of the entire list.
I'm looking for an elegant way to find n_j with Matlab.
Also, finding the gcd of a long list of integers seems hard — do you have any better idea?
Finding the gcd of a long list of numbers isn't too hard. You can do it in time linear in the size of the list. If you get lucky, you can do it in time a lot less than linear. Essentially this is because:
gcd(a,b,c) = gcd(gcd(a,b),c)
and if either a=1 or b=1 then gcd(a,b)=1 regardless of the size of the other number.
So if you have a list of numbers xs you can do
g = xs(1);
for i = 2:length(xs)
g = gcd(x(i),g);
if g == 1
break
end
end
The variable g will now store the gcd of the list.
Here is some sample code that I believe will help you get the GCD once you have the numbers you want to look at.
A = [15 30 20];
A_min = min(A);
GCD = 1;
for n = A_min:-1:1
temp = A / n;
if (max(mod(temp,1))==0)
% yay GCD found
GCD = n;
break;
end
end
The basic concept here is that the default GCD will always be 1 since every number is divisible by itself and 1 of course =). The GCD also can't be greater than the smallest number in the list, thus I start with the smallest number and then decriment by 1. This is assuming that you have already converted the numbers to a whole number form at this point. Decimals will throw this off!
By using the modulus of 1 you are testing to see if the number is a whole number, if it isn't you will have a decmial remainder left which is greater than 0. If you anticipate having to deal with negative you will have to tweak this test!
Other than that, the first time you find a number where the modulus of the list (mod 1) is all zeros you've found the GCD.
Enjoy!