Please Consider :
Subsets[Flatten[ParallelTable[{i, j}, {i, 1, 96}, {j, 1, 4}], 1], {4}]
I need to select all the Sublist such that the the i value is never the same within each sublist of 4
{{3,1},{4,1},{5,1},{6,1}} should be accepted while {{1,1},{1,2},{2,3},{6,1}} should be rejected. The Value 1 for i being repeated 2 times.
I know I could do this with Cases, but don`t understand the Syntax of it, and find the help on Cases rather empty compared to its potential applications.
Assuming your data is in the variable data, the following should do it:
Select[data, Length#Union[#[[All, 1]]] === 4 &]
This takes the "i"-value (i.e. first element), and checks that the 4 values are all different (i.e. if we remove the duplicates we still have 4 of them)
This response assumes that the input data is a list of tuples of four pairs each, e.g.:
$data = {{{3, 1}, {4, 1}, {5, 1}, {6, 1}} , {{1, 1}, {1, 2}, {2, 3}, {6, 1}}};
Using Cases, one could name and compare the first elements of each pair to ensure that they are unequal:
Cases[
$data
, {{a_, _}, {b_, _}, {c_, _}, {d_, _}} /; Unequal[a, b, c, d]
]
Another use of Cases compares the first elements of each pair without naming them:
Cases[
$data
, tuple_ /; Unequal ## tuple[[All, 1]]
]
Alternatively, one could use DeleteCases and exclude tuples with at least two pairs with the same initial value:
DeleteCases[
$data
, {___, {a_, _}, ___, {a_, _}, ___}
]
One might think that this last expression could be:
(* warning: does not work *)
Cases[$data, Except[{___, {a_, _}, ___, {a_, _}, ___}]]
... but Except does not permit named patterns in the first argument.
WReach already covered Cases well, so here is another approach.
Pick[data, Signature /# data[[All, All, 1]], 1 | -1]
It is faster than most of the other methods, but still not as fast as the fixed-length Cases method.
Related
I want to do multiple where query without effect data. I want to get data that include at least 1 data per array. Pseudo code
data =[1,3]
array1 = [1,2]
array2 = [3,4]
if(data.IsIntersect(array1) and data.IsIntersect(array2))
IsIntersect checks are there a intersection beetween arrays
I did so far
queryBuilder.andWhere(
'properties.id IN (:...sizeIds) AND properties.id IN (:...colorIds)',
{ sizeIds: [1, 2], colorIds: [3, 4] },
);
It returns empty because firstly checks properties for 'sizeIds' then it checks for 'colorIds'. For example
properties includes 1,3
check for sizeIds, returns 1
check for colorIds, return empty
How can I do that with typeORM?
How can properties.id be 1 and 3? And if it is, how could 1 or 3 be in both? You're asking for the impossible.
I assume you mean to ask for when properties.id is 1 or 3, because if it is [1,3] then you should use the postgres array syntax {1,3} & the ANY keyword (some variation on this: Check if value exists in Postgres array).
tldr, I think all you need is brackets and OR instead of AND:
queryBuilder.andWhere(
'(properties.id IN (:...sizeIds) OR properties.id IN (:...colorIds))',
{ sizeIds: [1, 2], colorIds: [3, 4] },
);
If properties.id is in fact an array, then please add the entity definition to your question. If you want to merge the rows where properties.id is in the list you will need a GROUP BY (https://orkhan.gitbook.io/typeorm/docs/select-query-builder).
My question is probably really easy, but I am a mathematica beginner.
I have a dataset, lets say:
Column: Numbers from 1 to 10
Column Signs
Column Other signs.
{{1,2,3,4,5,6,7,8,9,10},{d,t,4,/,g,t,w,o,p,m},{g,h,j,k,l,s,d,e,w,q}}
Now I want to extract all rows for which column 1 provides an odd number. In other words I want to create a new dataset.
I tried to work with Select and OddQ as well as with the IF function, but I have absolutely no clue how to put this orders in the right way!
Taking a stab at what you might be asking..
(table = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} ,
Characters["abcdefghij"],
Characters["ABCDEFGHIJ"]}) // MatrixForm
table[[All, 1 ;; -1 ;; 2]] // MatrixForm
or perhaps this:
Select[table, OddQ[#[[1]]] &]
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}
The convention in Mathematica is the reverse of what you use in your description.
Rows are first level sublists.
Let's take your original data
mytable = {{1,2,3,4,5,6,7,8,9,10},{d,t,4,"/",g,t,w,o,p,m},{g,h,j,k,l,s,d,e,w,q}}
Just as you suggested, Select and OddQ can do what you want, but on your table, transposed. So we transpose first and back:
Transpose[Select[Transpose[mytable], OddQ[First[#]]& ]]
Another way:
Mathematica functional command MapThread can work on synchronous lists.
DeleteCases[MapThread[If[OddQ[#1], {##}] &, mytable], Null]
The inner function of MapThread gets all elements of what you call a 'row' as variables (#1, #2, etc.). So it test the first column and outputs all columns or a Null if the test fails. The enclosing DeleteCases suppresses the unmatching "rows".
This question already has answers here:
NumPy selecting specific column index per row by using a list of indexes
(7 answers)
Closed 2 years ago.
Is there a better way to get the "output_array" from the "input_array" and "select_id" ?
Can we get rid of range( input_array.shape[0] ) ?
>>> input_array = numpy.array( [ [3,14], [12, 5], [75, 50] ] )
>>> select_id = [0, 1, 1]
>>> print input_array
[[ 3 14]
[12 5]
[75 50]]
>>> output_array = input_array[ range( input_array.shape[0] ), select_id ]
>>> print output_array
[ 3 5 50]
You can choose from given array using numpy.choose which constructs an array from an index array (in your case select_id) and a set of arrays (in your case input_array) to choose from. However you may first need to transpose input_array to match dimensions. The following shows a small example:
In [101]: input_array
Out[101]:
array([[ 3, 14],
[12, 5],
[75, 50]])
In [102]: input_array.shape
Out[102]: (3, 2)
In [103]: select_id
Out[103]: [0, 1, 1]
In [104]: output_array = np.choose(select_id, input_array.T)
In [105]: output_array
Out[105]: array([ 3, 5, 50])
(because I can't post this as a comment on the accepted answer)
Note that numpy.choose only works if you have 32 or fewer choices (in this case, the dimension of your array along which you're indexing must be of size 32 or smaller). Additionally, the documentation for numpy.choose says
To reduce the chance of misinterpretation, even though the following "abuse" is nominally supported, choices should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple.
The OP asks:
Is there a better way to get the output_array from the input_array and select_id?
I would say, the way you originally suggested seems the best out of those presented here. It is easy to understand, scales to large arrays, and is efficient.
Can we get rid of range(input_array.shape[0])?
Yes, as shown by other answers, but the accepted one doesn't work in general so well as what the OP already suggests doing.
I think enumerate is handy.
[input_array[enum, item] for enum, item in enumerate(select_id)]
How about:
[input_array[x,y] for x,y in zip(range(len(input_array[:,0])),select_id)]
This question is related to the context described in Seeking a solution or a heursitic approxmation for the 3-partition combinatorial situation. The task is distribute approximately 48 pieces of inherited jewelry, each with its appraised value, to 3 inheritors so as to give each inheritor equal or nearly equal value. That question has been sufficiently answered for my legalistic purposes.
This new question arises out of my pursuit of solving this by enumeration. Totally unnecessary legally. Just an intellectual challenge now.
The problem now:
Assign to each item a unique index: probably just the integers 1 through 48. Now allocate these 48 to each of the 3 inheritors and eliminate the duplicates.
To make this example case simpler, assert that there are only 9 items and each inheritor is to receive exactly 3 items. (Note that this diverges from the previous goal of making the 3 bins of nearly equal value.)
How to eliminate the duplications in the sequence of items-to-bins?
Example:
Let bin 1 contain items {1,2,3}
Let bin 2 contain items {4,5,6}
Let bin 3 contain items {7,8,9}
There will be 6 duplications of the final values of this triplet-of-triplets:
{1,2,3}{4,5,6}{7,8,9}
{4,5,6}{1,2,3}{7,8,9}
{4,5,6}{7,8,9}{1,2,3}
{7,8,9}{1,2,3}{4,5,6}
{7,8,9}{4,5,6}{1,2,3}
etc.
Again, how to eliminate the duplications in the sequence of items-to-bins? Without enumerating the entire set of permutations-of-triplets. No, that's not quite right. I might have to temporarily grind out all the permutations-of-triplets. How to quickly eliminate the duplicated combinations-of-triplets based on what has been done a priori?
I can imagine something like inventing a function which, given any combination of 3 items, returns a unique value. Something using prime numbers? Except that many pairs of prime numbers sum to another prime number.
I crossposted the original question on mathoverflow. I apologize for not understanding the relationship between stackoverflow and mathoverflow.
One can show that the total number of restricted partitions is
, which equals 280.
This can be reordered as:
You can get this by taking the first third of the (ordered) combinations you obtain by taking three out of nine list members and the first half of the combinations you get when you take three out of the remaining six for each choice of the first three. There's no free choice for the last three of course.
With Mathematica you might generate this as:
list = Range[9];
l1 = Subsets[list, {3}, Binomial[9, 3]/3];
l2 = Subsets[Complement[list, #], {3}, Binomial[6, 3]/2] & /# l1;
Flatten[
Outer[
Function[{ll1, ll2}, {ll1, ll2, Complement[list, ll1, ll2]}],
{#1}, #2, 1, 1
] & ### ({l1, l2}\[Transpose]),
2]
This is a good question. It is essentially a restricted set partition problem.
Here is one way in which you may approach this. I am not certain that it is optimal, but it is many magnitudes more efficient than brute force (generating all permutations and then removing duplicates).
I will be using curly brackets to represent lists, as this is familiar to me.
Start with this template, which represents zero items in three bins:
{ {{}, {}, {}} }
For each list within the outermost (i.e. just {{}, {}, {}} here):
Append 1 to each sub-list, skipping any lists that are full (contain three elements), and append only to the first empty {} list if there is more than one.
Keep a copy of the entire list for each replacement that is made, and join these together at the end of the step.
This process will then be repeated for 2, 3, etc., until all items are in bins or all bins are full. Example steps:
{ {{}, {}, {}} }
{ {{1}, {}, {}} }
{ {{1, 2}, {}, {}}, {{1}, {2}, {}} }
{ {{1, 2, 3}, {}, {}}, {{1, 2}, {3}, {}}, {{1, 3}, {2}, {}}, {{1}, {2, 3}, {}}, {{1}, {2}, {3}} }
{ {{1, 2, 3}, {4}, {}}, {{1, 2, 4}, {3}, {}}, {{1, 2}, {3, 4}, {}}, {{1, 2}, {3}, {4}}, {{1, 3, 4}, {2}, {}}, {{1, 3}, {2, 4}, {}}, {{1, 3}, {2}, {4}}, {{1, 4}, {2, 3}, {}}, {{1}, {2, 3, 4}, {}}, {{1}, {2, 3}, {4}}, {{1, 4}, {2}, {3}}, {{1}, {2, 4}, {3}}, {{1}, {2}, {3, 4}} }
I need to generate a random walk based on the DNA sequence of a virus, given its base pair sequence of 2k base pairs. The sequence looks like "ATGCGTCGTAACGT". The path should turn right for an A, left for a T, go upwards for a G and downwards for a C.
How can I use either Matlab, Mathematica or SPSS for this purpose?
I did not previously know of Mark McClure's blog about Chaos Game representation of gene sequences, but it reminded me of an article by Jose Manuel Gutiérrez (The Mathematica Journal Vol 9 Issue 2), which also gives a chaos game algorithm for an IFS using (the four bases of) DNA sequences. A detailed description may be found here (the original article).
The method may be used to produce plots such as the following. Just for the hell of it, I've included (in the RHS panels) the plots generated with the corresponding complementary DNA strand (cDNA).
Mouse Mitochondrial DNA (LHS) and its
complementary strand (cDNA) (RHS).
These plots were generated from GenBank Identifier gi|342520. The sequence contains 16295 bases.
(One of the examples used by Jose Manuel Gutiérrez. If anyone is interested, plots for the human equivalent may be generated from gi|1262342).
Human Beta Globin Region (LHS) and its cDNA (RHS)
Generated from gi|455025| (the example
used my Mark McClure). The sequence contains 73308 bases
There are pretty interesting plots! The (sometimes) fractal nature of such plots is known, but the symmetry obvious in the LHS vs RHS (cDNA) versions was very surprising (at least to me).
The nice thing is that such plots for any DNA sequence may be very easily generated by directly importing the sequence (from, say, Genbank), and then using the power of Mma.
All you need it the accession number! ('Unknown' nucleotides such as "R" may need to be zapped) (I am using Mma v7).
The Original Implimenation (slightly modified) (by Jose Manuel Gutiérrez)
Important Update
On the advise of Mark McClure, I have changed Point/#Orbit[s, Union[s]] to Point#Orbit[s, Union[s]].
This speeds things up very considerably. See Mark's comment below.
Orbit[s_List, {a_, b_, c_, d_}] :=
OrbitMap[s /. {a -> {0, 0}, b -> {0, 1}, c -> {1, 0},
d -> {1, 1}}];
OrbitMap =
Compile[{{m, _Real, 2}}, FoldList[(#1 + #2)/2 &, {0, 0}, m]];
IFSPlot[s_List] :=
Show[Graphics[{Hue[{2/3, 1, 1, .5}], AbsolutePointSize[2.5],
Point # Orbit[s, Union[s]]}], AspectRatio -> Automatic,
PlotRange -> {{0, 1}, {0, 1}},
GridLines -> {Range[0, 1, 1/2^3], Range[0, 1, 1/2^3]}]
This gives a blue plot. For green, change Hue[] to Hue[{1/3,1,1,.5}]
The following code now generates the first plot (for mouse mitochondrial DNA)
IFSPlot[Flatten#
Characters#
Rest#Import[
"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=\
nucleotide&id=342520&rettype=fasta&retmode=text", "Data"]]
To get a cDNA plot I used the follow transformation rules (and also changed the Hue setting)
IFSPlot[ .... "Data"] /. {"A" -> "T", "T" -> "A", "G" -> "C",
"C" -> "G"}]
Thanks to Sjoerd C. de Vries and telefunkenvf14 for help in directly importing sequences from the NCBI site.
Splitting things up a bit, for the sake of clarity.
Import a Sequence
mouseMitoFasta=Import["http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=342520&rettype=fasta&retmode=text","Data"];
The method given for importing sequences in the original Mathematica J. article is dated.
A nice check
First#mouseMitoFasta
Output:
{>gi|342520|gb|J01420.1|MUSMTCG Mouse mitochondrion, complete genome}
Generation of the list of bases
mouseMitoBases=Flatten#Characters#Rest#mouseMitoFasta
Some more checks
{Length#mouseMitoBases, Union#mouseMitoBases,Tally#mouseMitoBases}
Output:
{16295,{A,C,G,T},{{G,2011},{T,4680},{A,5628},{C,3976}}}
The second set of plots was generated in a similar manner from gi|455025. Note that the sequence is long!
{73308,{A,C,G,T},{{G,14785},{A,22068},{T,22309},{C,14146}}}
One final example (containing 265922 bp), also showing fascinating 'fractal' symmetry. (These were generated with AbsolutePointSize[1] in IFSPlot).
The first line of the fasta file:
{>gi|328530803|gb|AFBL01000008.1| Actinomyces sp. oral taxon 170 str. F0386 A_spOraltaxon170F0386-1.0_Cont9.1, whole genome shotgun sequence}
The corresponding cDNA plot is again shown in blue on RHS
Finally, Mark's method also gives very beautiful plots (for example with gi|328530803), and may be downloaded as a notebook.
Not that I really understand the "graph" you want, but here is one literal interpretation.
None of the following code in necessarily in a final form. I want to know if this is right before I try to refine anything.
rls = {"A" -> {1, 0}, "T" -> {-1, 0}, "G" -> {0, 1}, "C" -> {0, -1}};
Prepend[Characters#"ATGCGTCGTAACGT" /. rls, {0, 0}];
Graphics[Arrow /# Partition[Accumulate#%, 2, 1]]
Prepend[Characters#"TCGAGTCGTGCTCA" /. rls, {0, 0}];
Graphics[Arrow /# Partition[Accumulate#%, 2, 1]]
3D Options
i = 0;
Prepend[Characters#"ATGCGTCGTAACGT" /. rls, {0, 0}];
Graphics[{Hue[i++/Length#%], Arrow##} & /#
Partition[Accumulate#%, 2, 1]]
i = 0;
Prepend[Characters#"ATGCGTCGTAACGT" /.
rls /. {x_, y_} :> {x, y, 0.3}, {0, 0, 0}];
Graphics3D[{Hue[i++/Length#%], Arrow##} & /#
Partition[Accumulate#%, 2, 1]]
Now that I know what you want, here is a packaged version of the first function:
genePlot[s_String] :=
Module[{rls},
rls =
{"A" -> { 1, 0},
"T" -> {-1, 0},
"G" -> {0, 1},
"C" -> {0, -1}};
Graphics[Arrow /# Partition[#, 2, 1]] & #
Accumulate # Prepend[Characters[s] /. rls, {0, 0}]
]
Use it like this:
genePlot["ATGCGTCGTAACGT"]
It sounds like you might be talking about CGR, or the so called Chaos Game Representation of a gene sequence described in the 1990 paper "Chaos game representation of gene structure" by Joel Jefferey. Here's an implementation in Mathematica:
cgrPic[s_String] := Module[
{},
chars = StringCases[s, "G"|"A"|"T"|"C"];
f[x_, "A"] := x/2;
f[x_, "T"] := x/2 + {1/2, 0};
f[x_, "G"] := x/2 + {1/2, 1/2};
f[x_, "C"] := x/2 + {0, 1/2};
pts = FoldList[f, {0.5, 0.5}, chars];
ListPlot[pts, AspectRatio -> Automatic]]
Here's how to apply it to a gene sequence taken from Mathematica's GenomeData command:
cgrPic[GenomeData["FAT4", "FullSequence"]]
You might also try something like this...
RandomDNAWalk[seq_, path_] :=
RandomDNAWalk[StringDrop[seq, 1],
Join[path, getNextTurn[StringTake[seq, 1]]]];
RandomDNAWalk["", path_] := Accumulate[path];
getNextTurn["A"] := {{1, 0}};
getNextTurn["T"] := {{-1, 0}};
getNextTurn["G"] := {{0, 1}};
getNextTurn["C"] := {{0, -1}};
ListLinePlot[
RandomDNAWalk[
StringJoin[RandomChoice[{"A", "T", "C", "G"}, 2000]], {{0, 0}}]]
Assuming that the sequence S has been mapped already*) to integer array then the actual computation of movements is straightforward based on rules R:
R =
1 -1 0 0
0 0 1 -1
S =
1 2 3 4 3 2 4 3 2 1 1 4 3 2
T= cumsum(R(:, S), 2)
T =
1 0 0 0 0 -1 -1 -1 -2 -1 0 0 0 -1
0 0 1 0 1 1 0 1 1 1 1 0 1 1
*) You need to elaborate more on the actual sequence. Is it represented as single string, or perhaps as cell array, or something else?
Edit:
Assuming your sequence is represented as string, then you'll map it to integer sequence S like:
r= zeros(1, 84);
r(double("ATGC"))= [1 2 3 4];
S= r(double("ATGCGTCGTAACGT"))
And to plot it:
plot([0 T(1, :)], [0 T(2, :)], linespec)
where linespec is the desired line specification.
This question seems to have been well answered already, but I thought I'd add that what you are describing has been previously published under the banner of DNA walks among a collection of numerical representation methods for DNA sequences, which are discussed in our preprint.
It turns out that DNA walks aren't very useful in practice, yet permit intuitive visualisation. I don't have it to hand, but I'd imagine my colleague would be more than happy to provide the Matlab code used to generate the below figure.