<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Scienco.org &#187; Math</title>
	<atom:link href="http://www.scienco.org/tag/math/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.scienco.org</link>
	<description>Life&#039;s too short to be unenthusiastic</description>
	<lastBuildDate>Thu, 07 Jul 2011 13:47:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
	<atom:link rel="next" href="http://www.scienco.org/tag/math/feed/?page=2" />

		<item>
		<title>Java: Power set and set partitioning using bitwise operations</title>
		<link>http://www.scienco.org/2011/java-power-set-and-set-partitioning-using-bitwise-operations/</link>
		<comments>http://www.scienco.org/2011/java-power-set-and-set-partitioning-using-bitwise-operations/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 18:32:56 +0000</pubDate>
		<dc:creator>Mikkel Meyer Andersen</dc:creator>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.scienco.org/?p=281</guid>
		<description><![CDATA[To tasks are quite common, especially writing math programs: Get a power set Partition a set into two in all possible ways These two operations are of course interesting for Set&#60;T&#62; and cousins, but from a mathematical point of view, it is sufficient to solve this for index sets, i.e. sets {0, 1, ..., n [...]]]></description>
			<content:encoded><![CDATA[<p>To tasks are quite common, especially writing math programs:</p>
<ul>
<li>Get a <a title="Power set" href="http://en.wikipedia.org/wiki/Power_set">power set</a></li>
<li><a title="Partition of a set" href="http://en.wikipedia.org/wiki/Partition_of_a_set">Partition a set</a> into two in all possible ways</li>
</ul>
<p>These two operations are of course interesting for Set&lt;T&gt; and cousins, but from a mathematical point of view, it is sufficient to solve this for index sets, i.e. sets {0, 1, ..., n - 1}. For List&lt;T&gt; and cousins (allowing duplicates), it can be a slightly different story depending on your view on the duplicates. So the rest of this post deals with index sets of size n, i.e. {0, 1, ..., n - 1}.</p>
<p>Especially for power sets, numerous implementations use strings. That I do not fancy. I tried to find implementations not using strings but merely used bitwise operations (which is also what the string using implementation does but they bring strings into the picture, maybe because it makes the programming a bit easier).</p>
<p>If you use some of this code in commercial software, you have to contact me first and make an agreement of usage. If your use is not commercial, feel free to use the code as long as you don't take credit for it yourself.</p>
<p>My implementations of the operations is shown below. Please contact me for questions or comments.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Get the power set of {0, 1, ..., n}.
 * 
 * @param n the upper bound in the index set {0, 1, ..., n} to get the power set of
 * @return the powerset including the empty set and the set itself as the first and last element, respectively
 * @author Mikkel Meyer Andersen, scienco [at] mikl [dot] dk
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> getPowerset<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> n<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>n <span style="color: #339933;">&lt;=</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalArgumentException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;n must be be at least 1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// stop at (2^n) - 1, so calculate 2^n</span>
    <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> stop <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span> <span style="color: #339933;">&lt;&lt;</span> n<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">int</span> i0 <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span>, i1<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> powerset <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span>stop<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Starting at i = 0 gives an empty first pair, so start at i = 1</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> stop<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> i<span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> k <span style="color: #339933;">=</span> i<span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000066; font-weight: bold;">int</span> size <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// First calculate size of the array needed</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> r <span style="color: #339933;">=</span> n <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> r <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #339933;">--</span>r<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>j <span style="color: #339933;">&amp;</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                size<span style="color: #339933;">++;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            j <span style="color: #339933;">&gt;&gt;&gt;=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        i1 <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> set <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span>size<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> r <span style="color: #339933;">=</span> n <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> r <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #339933;">--</span>r<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>k <span style="color: #339933;">&amp;</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                set<span style="color: #009900;">&#91;</span>i1<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> r<span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            k <span style="color: #339933;">&gt;&gt;&gt;=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        powerset<span style="color: #009900;">&#91;</span>i0<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> set<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">return</span> powerset<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Partition an index set {0, 1, ..., n} into two parts A and B such that A
 * union B is the whole set and A and B are disjoint. If you use this in
 * commercial software, do contact me first. If not, feel free to use this
 * code as long as you don't take credit for it yourself.
 * 
 * @param n the upper bound in the index set {0, 1, ..., n} to get pairs of
 * @return the pairs
 * @author Mikkel Meyer Andersen, scienco [at] mikl [dot] dk
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> getPairs<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> n<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>n <span style="color: #339933;">&lt;=</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalArgumentException</span><span style="color: #009900;">&#40;</span>
                                           <span style="color: #0000ff;">&quot;n must be be at least 2 (it takes at least two elements to create a pair)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// stop at 2^(n-1) - 1, so calculate 2^(n-1)</span>
    <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> stop <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span> <span style="color: #339933;">&lt;&lt;</span> <span style="color: #009900;">&#40;</span>n <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">int</span> i0 <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span>, i1, i2<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> pairs <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span>stop <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Starting at i = 0 gives an empty first pair, so start at i = 1</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> stop<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> i<span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> k <span style="color: #339933;">=</span> i<span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000066; font-weight: bold;">int</span> size <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// First calculate size of the array needed</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> r <span style="color: #339933;">=</span> n <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> r <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #339933;">--</span>r<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>j <span style="color: #339933;">&amp;</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                size<span style="color: #339933;">++;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            j <span style="color: #339933;">&gt;&gt;&gt;=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        i1 <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
        i2 <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> set1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span>size<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> set2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span>n <span style="color: #339933;">-</span> size<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> r <span style="color: #339933;">=</span> n <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> r <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #339933;">--</span>r<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>k <span style="color: #339933;">&amp;</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                set1<span style="color: #009900;">&#91;</span>i1<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> r<span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                set2<span style="color: #009900;">&#91;</span>i2<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> r<span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            k <span style="color: #339933;">&gt;&gt;&gt;=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        pairs<span style="color: #009900;">&#91;</span>i0<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#123;</span>
            set1, set2
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">return</span> pairs<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Formats the power set of {0, 1, ..., n} obtained by {@link getPowerset}
 * in a nicely looking string.
 * 
 * @param powerset the powerset to format nicely
 * @author Mikkel Meyer Andersen, scienco [at] mikl [dot] dk
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399;">String</span> powersetToString<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> powerset<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    StringBuilder sb <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StringBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> powerset.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> set <span style="color: #339933;">=</span> powerset<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> set.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>j<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span>set<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>j <span style="color: #339933;">&lt;</span> set.<span style="color: #006633;">length</span> <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;, &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">&lt;</span> powerset.<span style="color: #006633;">length</span> <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">return</span> sb.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Formats the different pairs partitioning the index set of {0, 1, ..., n}
 * obtained by {@link getPairs} in a nicely looking string.
 * 
 * @param pairs the pairs to format nicely
 * @author Mikkel Meyer Andersen, scienco [at] mikl [dot] dk
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399;">String</span> pairsToString<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> pairs<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    StringBuilder sb <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StringBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> pairs.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> set1 <span style="color: #339933;">=</span> pairs<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> set2 <span style="color: #339933;">=</span> pairs<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
        sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;(&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> set1.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>j<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span>set1<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>j <span style="color: #339933;">&lt;</span> set1.<span style="color: #006633;">length</span> <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;, &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;), (&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> set2.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>j<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span>set2<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>j <span style="color: #339933;">&lt;</span> set2.<span style="color: #006633;">length</span> <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;, &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">&lt;</span> pairs.<span style="color: #006633;">length</span> <span style="color: #339933;">-</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">return</span> sb.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The usage is exemplified with the following example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> pairs <span style="color: #339933;">=</span> Utils.<span style="color: #006633;">getPairs</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">4</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>Utils.<span style="color: #006633;">pairsToString</span><span style="color: #009900;">&#40;</span>pairs<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> powerset <span style="color: #339933;">=</span> Utils.<span style="color: #006633;">getPowerset</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">4</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>Utils.<span style="color: #006633;">powersetToString</span><span style="color: #009900;">&#40;</span>powerset<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The output is:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">(3), (2, 1, 0)
(2), (3, 1, 0)
(3, 2), (1, 0)
(1), (3, 2, 0)
(3, 1), (2, 0)
(2, 1), (3, 0)
(3, 2, 1), (0)
&nbsp;
3
2
3, 2
1
3, 1
2, 1
3, 2, 1
0
3, 0
2, 0
3, 2, 0
1, 0
3, 1, 0
2, 1, 0
3, 2, 1, 0</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.scienco.org/2011/java-power-set-and-set-partitioning-using-bitwise-operations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>qqmultinorm.R version 1.1 - more intelligent plot size</title>
		<link>http://www.scienco.org/2009/qqmultinorm-r-version-1-1-more-intelligent-plot-size/</link>
		<comments>http://www.scienco.org/2009/qqmultinorm-r-version-1-1-more-intelligent-plot-size/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 07:20:47 +0000</pubDate>
		<dc:creator>Mikkel Meyer Andersen</dc:creator>
				<category><![CDATA[R]]></category>
		<category><![CDATA[Statistics]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://www.scienco.org/?p=229</guid>
		<description><![CDATA[I've updated the qqmultinorm.R script a bit so that it's now capable of picking a more optimal plot size (less unused space). The idea refers to deciding the sides (dimensions) of a rectangle if the areal (number of plots) is known i.e., optimising the dimensions of a rectangle given the areal. We want the perimeter [...]]]></description>
			<content:encoded><![CDATA[<p>I've updated the qqmultinorm.R script a bit so that it's now capable of picking a more optimal plot size (less unused space).</p>
<p>The idea refers to deciding the sides (dimensions) of a rectangle if the areal (number of plots) is known i.e., optimising the dimensions of a rectangle given the areal. We want the perimeter as small as possible (for better viewing), preferably wider than longer if square isn't possible. A given number n is factorised in to numbers within a given error. For example if the allowed error is 2, then 7 gets factorised in (1,7), (2, 4), (4, 2), and (7, 1) (here redundant factorisation is included). Although 2*4 = 8, but abs(7-8) = 1 <= 2, so it's acceptable. Actually the default error is 10% of the input areal.</p>
<p>The way the proper factorisations is chosen, is by ordering the pairs by ascending the difference of the components i.e, how much the width and height differs. And then ordered ascending by height so that the plot gets wide screen-like instead of poster-like.</p>
<p>The new script is a follows (only find.optimal.mfrow.size(...) and a bit logic in qqmultinorm(...) added):</p>

<div class="wp_syntax"><div class="code"><pre class="r" style="font-family:monospace;"># File name: qqmultinorm.R
# Version: 1.1
# Last updated: 2009-08-28
#
# This R-code is made by:
# Mikkel Meyer Andersen, Denmark
# mikl [funny-a] math [.] aau [.] dk or 
# mikl [funny-a] mikl [.] dk
#
# Licence: GPLv2
#
# Feel free to use it, but if you do I'll like to hear about it (just for fun).
# If you make corrections, please submit them back so others can enjoy them as well.
&nbsp;
qqchisq &lt;- function(y, main, df=2, continuity.correction = 0.5)
{
  n &lt;- length(y)
  y &lt;- sort(y)
  c &lt;- numeric(n)
&nbsp;
  for (i in 1:n)
    c[i] &lt;- qchisq((i-continuity.correction)/n, df=df)
&nbsp;
  plot(c, y, xlab=&quot;Theoretical Quantiles&quot;, ylab=&quot;Sample Quantiles&quot;, main=main)
  lines(c(c[1], c[n]), c(c[1], c[n]), type=&quot;l&quot;)
}
&nbsp;
dec2bin &lt;- function(x)
{
  if (!is.vector(x) || length(x) != 1 || x &lt; 0)
    stop(&quot;x must be a non-negative integer&quot;)
&nbsp;
  N &lt;- length(x)
  ndigits &lt;- floor(log2(x)) + 1
  bin &lt;- numeric(ndigits)
&nbsp;
  for (i in (ndigits-1):0)
  {
    tmp &lt;- 2^i
&nbsp;
    if (x %/% tmp &gt;= 1)
    {
      bin[i+1] &lt;- 1
      x &lt;- x - tmp
    }
  }
&nbsp;
  return(rev(bin))
}
&nbsp;
# Returns the power set without the empty set
power.set &lt;- function(v)
{
  n &lt;- length(v)  
  N &lt;- 2^n - 1
  ps &lt;- vector(&quot;list&quot;, N)
&nbsp;
  for (i in 1:(N-1))
  {
    Nbin &lt;- dec2bin(i)
    Nbin &lt;- c(numeric(n-length(Nbin)), Nbin)
    Nbin &lt;- rev(Nbin)
    ps[[i]] &lt;- v[which(Nbin == 1)]
  }
&nbsp;
  ps[[N]] &lt;- v
&nbsp;
  return(ps)
}
&nbsp;
# Input: n
#  - here the number of plots
# Returns c(h, w)
#  - the optimal choice of rows and cols to use in in mfrow
find.optimal.mfrow.size &lt;- function(n)
{  
  w0 &lt;- ceiling(sqrt(n))
&nbsp;
  # The area can at max contain of 10% unused space
  max.error &lt;- round(n*0.1)
&nbsp;
  n.minus.error &lt;- n - max.error
  n.plus.error &lt;- n + max.error
&nbsp;
  # If n is a square, fine!
  if (w0^2 == n)
    return(c(w0, w0))
&nbsp;
  # Col 1 and 2: w and h
  # Col 3: The difference between w and h: this should be as small as possible
  candidates &lt;- matrix(ncol=3)
&nbsp;
  for (w in w0:1)  
  {    
    h &lt;- ceiling(n / w)
    n0 &lt;- w*h
&nbsp;
    # Because of ceiling we know that n0 &gt;= n
    if (n0 &lt;= n.plus.error)
      candidates &lt;- rbind(candidates, c(h, w, abs(w-h)))
  }
&nbsp;
  # First row is NA
  candidates &lt;- candidates[-1,]
&nbsp;
  # Uups, something went wront - well, don't panic
  if (nrow(candidates) == 0)
    return(c(w0, w0))
&nbsp;
  # First order by abs(w-h) and then by h to get a widescreen-look 
  # instead of a poster-look
  candidates &lt;- candidates[order(candidates[,3], candidates[,1]), ]
&nbsp;
  return(candidates[1, c(1,2)])
}
&nbsp;
# dataset: variables in columns and observations as rows
# subset.min.size, subset.max.size: inclusive limits
# filename: if specified, the plot are saved as a png file with this filename
qqmultinorm &lt;- function(dataset, subset.min.size = 1, subset.max.size = 4, filename = NULL, use.optimale.size = F)
{
  p &lt;- ncol(dataset)
  n &lt;- nrow(dataset)
&nbsp;
  if (subset.min.size &lt; 1) stop(&quot;subset.min.size &lt; 1&quot;)
  if (subset.min.size &gt; p) stop(&quot;subset.min.size &gt; p&quot;)
  if (subset.max.size &lt; 1) stop(&quot;subset.max.size &lt; 1&quot;)
  if (subset.max.size &gt; p) stop(&quot;subset.max.size &gt; p&quot;)
  if (subset.min.size &gt; subset.max.size) stop(&quot;subset.min.size &gt; subset.max.size&quot;)
&nbsp;
  if (is.null(colnames(dataset)))
    colnames(dataset) &lt;- 1:p
&nbsp;
  # We have p variables. If all is to be checked against each other,
  # then we have a power-set with 2^p subsets (including the empty set)
&nbsp;
  # Here we get subset containing indexes of the variables to include
  # Note that power.set doesn't include the empty set.
  subsets &lt;- power.set(1:p)
  subsets.len &lt;- length(subsets)
&nbsp;
  # To get the plots with the fewest variables first, we do a litte trick:
  # While we find out which plots to include, we build a list
  # where each element of a list is the index of the subset,
  # and the index of the element is the size of the subset.
  # (The +1 is because the limits are includesive!)
  s.included &lt;- vector(&quot;list&quot;, subset.max.size - subset.min.size + 1)
&nbsp;
  plots &lt;- 0
&nbsp;
  for (i in 1:subsets.len)
  {
    s &lt;- subsets[[i]]
    s.len &lt;- length(s)
&nbsp;
    if (s.len &gt;= subset.min.size &amp;&amp; s.len &lt;= subset.max.size)
    {
      plots &lt;- plots + 1
      s.included[[s.len - subset.min.size + 1]] &lt;- c(s.included[[s.len - subset.min.size + 1]], i)
    }
  }
&nbsp;
  # Now it's possible to build the subset index vector; 
  # we disregard the size of each subset; no more need to know it.
  s.indexes &lt;- c()
&nbsp;
  for (s in s.included)
  {
    s.indexes &lt;- c(s.indexes, s)
  }
&nbsp;
  # We want the best view  
  plot.per.row &lt;- ceiling(plots^(1/2))
  plot.per.column &lt;- ceiling(plots^(1/2))
&nbsp;
  if (use.optimale.size)
  {
    mfrow.parameters &lt;- find.optimal.mfrow.size(plots)
    plot.per.row &lt;- mfrow.parameters[1]
    plot.per.column &lt;- mfrow.parameters[2]
  }
&nbsp;
  plot.width &lt;- 300
  plot.height &lt;- 200
&nbsp;
  if (!is.null(filename))
    png(file=paste(filename, &quot;.png&quot;, sep=&quot;&quot;), bg=&quot;white&quot;, width = plot.per.row * plot.width, height = plot.per.column * plot.height)
&nbsp;
  par(mfrow = c(plot.per.row, plot.per.column))  
&nbsp;
  # There's no need to calculate a whole lot several times:
  ybar &lt;- as.vector(colMeans(dataset))
&nbsp;
  S &lt;- as.matrix(var(dataset))
&nbsp;
  current &lt;- 1  
  for (i in s.indexes)
  {
    s &lt;- subsets[[i]]
    s.len &lt;- length(s)
&nbsp;
    if (s.len &gt; subset.max.size)
      next
&nbsp;
    cat(&quot;Processing subset no.&quot;, current, &quot;out of&quot;, plots, &quot;\n&quot;)
&nbsp;
    # Container for our values
    squared.dist &lt;- numeric(n)
&nbsp;
    # qr.solve(A) = A^(-1)  
    Sinv &lt;- qr.solve(S[s,s])
&nbsp;
    # Then calculate the squared distance for each datapoint
    for (i in 1:n)
    {
      c &lt;- dataset[i,s] - ybar[s]
      squared.dist[i] &lt;- t(c) %*% Sinv %*% c
    }
&nbsp;
    # Finding the order statistic
    squared.dist &lt;- sort(squared.dist)
&nbsp;
    qqchisq(squared.dist, paste(colnames(dataset)[s], collapse=&quot;, &quot;), s.len)
&nbsp;
    current &lt;- current + 1
  }
&nbsp;
  if (!is.null(filename))
    dev.off()
}
&nbsp;
# Example:
A &lt;- matrix(rnorm(2000, mean=3, sd=2), ncol=8)
qqmultinorm(A, 2, 2, &quot;multinorm-optimal.size&quot;, use.optimale.size = T)
qqmultinorm(A, 2, 2, &quot;multinorm&quot;, use.optimale.size = F)</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.scienco.org/2009/qqmultinorm-r-version-1-1-more-intelligent-plot-size/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>qqmultinorm.R - evaluating the normality of a sample</title>
		<link>http://www.scienco.org/2009/qqmultinorm-r-evaluating-the-normality-of-a-sample/</link>
		<comments>http://www.scienco.org/2009/qqmultinorm-r-evaluating-the-normality-of-a-sample/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 11:44:00 +0000</pubDate>
		<dc:creator>Mikkel Meyer Andersen</dc:creator>
				<category><![CDATA[R]]></category>
		<category><![CDATA[Statistics]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://www.scienco.org/?p=225</guid>
		<description><![CDATA[I wrote a R-script that can be used to evaluate for multivariate normality of a sample. It's a kind of generalisation to the qqnorm, but this one just uses sums of the squared statistical distance which is then chi squared distributed with degrees of freedom equalling the number of squared statistical distance summed. The useful [...]]]></description>
			<content:encoded><![CDATA[<p>I wrote a R-script that can be used to evaluate for multivariate normality of a sample. It's a kind of generalisation to the qqnorm, but this one just uses sums of the squared statistical distance which is then chi squared distributed with degrees of freedom equalling the number of squared statistical distance summed.</p>
<p>The useful thing about this script, is that it's able to plot all possible combinations of the variables. It's possible to specify the minimum number of variables to compare and the maximum number of variables to compare. All possible combinations are found by calculating the power set (using binary representation through the decimal to binary conversion, dec2bin, because if a set has k elements, then its power set has 2^k elements, and the binary representation of the numbers from 1 to 2^k are then used to pick out the subsets in the power set).</p>
<p>Please notice that it's possible to specify a filename so that the plots are written to a png file. This is by far the easiest thing - and only possibility - if there's more than a few plots.</p>
<p>I haven't wrote a lot of documentation besides this, but feel free to ask if in doubt of anything!</p>

<div class="wp_syntax"><div class="code"><pre class="r" style="font-family:monospace;"># File name: qqmultinorm.R
#
# This R-code is made by:
# Mikkel Meyer Andersen, Denmark
# mikl [funny-a] math [.] aau [.] dk or 
# mikl [funny-a] mikl [.] dk
#
# Licence: GPLv2
#
# Feel free to use it, but if you do I'll like to hear about it (just for fun).
# If you make corrections, please submit them back so others can enjoy them as well.
&nbsp;
qqchisq &lt;- function(y, main, df=2, continuity.correction = 0.5)
{
  n &lt;- length(y)
  y &lt;- sort(y)
  c &lt;- numeric(n)
&nbsp;
  for (i in 1:n)
    c[i] &lt;- qchisq((i-continuity.correction)/n, df=df)
&nbsp;
  plot(c, y, xlab=&quot;Theoretical Quantiles&quot;, ylab=&quot;Sample Quantiles&quot;, main=main)
  lines(c(c[1], c[n]), c(c[1], c[n]), type=&quot;l&quot;)
}
&nbsp;
dec2bin &lt;- function(x)
{
  if (!is.vector(x) || length(x) != 1 || x &lt; 0)
    stop(&quot;x must be a non-negative integer&quot;)
&nbsp;
  N &lt;- length(x)
  ndigits &lt;- floor(log2(x)) + 1
  bin &lt;- numeric(ndigits)
&nbsp;
  for (i in (ndigits-1):0)
  {
    tmp &lt;- 2^i
&nbsp;
    if (x %/% tmp &gt;= 1)
    {
      bin[i+1] &lt;- 1
      x &lt;- x - tmp
    }
  }
&nbsp;
  return(rev(bin))
}
&nbsp;
# Returns the power set without the empty set
power.set &lt;- function(v)
{
  n &lt;- length(v)  
  N &lt;- 2^n - 1
  ps &lt;- vector(&quot;list&quot;, N)
&nbsp;
  for (i in 1:(N-1))
  {
    Nbin &lt;- dec2bin(i)
    Nbin &lt;- c(numeric(n-length(Nbin)), Nbin)
    Nbin &lt;- rev(Nbin)
    ps[[i]] &lt;- v[which(Nbin == 1)]
  }
&nbsp;
  ps[[N]] &lt;- v
&nbsp;
  return(ps)
}
&nbsp;
# dataset: variables in columns and observations as rows
# subset.min.size, subset.max.size: inclusive limits
# filename: if specified, the plot are saved as a png file with this filename
qqmultinorm &lt;- function(dataset, subset.min.size = 1, subset.max.size = 4, filename = NULL)
{
  p &lt;- ncol(dataset)
  n &lt;- nrow(dataset)
&nbsp;
  if (subset.min.size &lt; 1) stop(&quot;subset.min.size &lt; 1&quot;)
  if (subset.min.size &gt; p) stop(&quot;subset.min.size &gt; p&quot;)
  if (subset.max.size &lt; 1) stop(&quot;subset.max.size &lt; 1&quot;)
  if (subset.max.size &gt; p) stop(&quot;subset.max.size &gt; p&quot;)
  if (subset.min.size &gt; subset.max.size) stop(&quot;subset.min.size &gt; subset.max.size&quot;)
&nbsp;
  if (is.null(colnames(dataset)))
    colnames(dataset) &lt;- 1:p
&nbsp;
  # We have p variables. If all is to be checked against each other,
  # then we have a power-set with 2^p subsets (including the empty set)
&nbsp;
  # Here we get subset containing indexes of the variables to include
  # Note that power.set doesn't include the empty set.
  subsets &lt;- power.set(1:p)
  subsets.len &lt;- length(subsets)
&nbsp;
  # To get the plots with the fewest variables first, we do a litte trick:
  # While we find out which plots to include, we build a list
  # where each element of a list is the index of the subset,
  # and the index of the element is the size of the subset.
  # (The +1 is because the limits are includesive!)
  s.included &lt;- vector(&quot;list&quot;, subset.max.size - subset.min.size + 1)
&nbsp;
  plots &lt;- 0
&nbsp;
  for (i in 1:subsets.len)
  {
    s &lt;- subsets[[i]]
    s.len &lt;- length(s)
&nbsp;
    if (s.len &gt;= subset.min.size &amp;&amp; s.len &lt;= subset.max.size)
    {
      plots &lt;- plots + 1
      s.included[[s.len - subset.min.size + 1]] &lt;- c(s.included[[s.len - subset.min.size + 1]], i)
    }
  }
&nbsp;
  # Now it's possible to build the subset index vector; 
  # we disregard the size of each subset; no more need to know it.
  s.indexes &lt;- c()
&nbsp;
  for (s in s.included)
  {
    s.indexes &lt;- c(s.indexes, s)
  }
&nbsp;
  # We want a squared view
  plot.per.row &lt;- ceiling(plots^(1/2))
  plot.per.column &lt;- ceiling(plots^(1/2))
  plot.width &lt;- 200
  plot.height &lt;- 200
&nbsp;
  if (!is.null(filename))
    png(file=paste(filename, &quot;.png&quot;, sep=&quot;&quot;), bg=&quot;white&quot;, width = plot.per.row * plot.width, height = plot.per.column * plot.height)
&nbsp;
  par(mfrow = c(plot.per.row, plot.per.column))  
&nbsp;
  # There's no need to calculate a whole lot several times:
  ybar &lt;- as.vector(colMeans(dataset))
&nbsp;
  S &lt;- as.matrix(var(dataset))
&nbsp;
  current &lt;- 1  
  for (i in s.indexes)
  {
    s &lt;- subsets[[i]]
    s.len &lt;- length(s)
&nbsp;
    if (s.len &gt; subset.max.size)
      next
&nbsp;
    cat(&quot;Processing subset no.&quot;, current, &quot;out of&quot;, plots, &quot;\n&quot;)
&nbsp;
    # Container for our values
    squared.dist &lt;- numeric(n)
&nbsp;
    # qr.solve(A) = A^(-1)  
    Sinv &lt;- qr.solve(S[s,s])
&nbsp;
    # Then calculate the squared distance for each datapoint
    for (i in 1:n)
    {
      c &lt;- dataset[i,s] - ybar[s]
      squared.dist[i] &lt;- t(c) %*% Sinv %*% c
    }
&nbsp;
    # Finding the order statistic
    squared.dist &lt;- sort(squared.dist)
&nbsp;
    qqchisq(squared.dist, paste(colnames(dataset)[s], collapse=&quot;, &quot;), s.len)
&nbsp;
    current &lt;- current + 1
  }
&nbsp;
  if (!is.null(filename))
    dev.off()
}
&nbsp;
# Example:
A &lt;- matrix(rnorm(2000, mean=3, sd=2), ncol=8)
qqmultinorm(A, 1, 3, &quot;multinorm-1-3&quot;)
#qqmultinorm(A, 4, 4, &quot;multinorm-4&quot;)
#qqmultinorm(A, 5, 5, &quot;multinorm-5&quot;)
#qqmultinorm(A, 6, 8, &quot;multinorm-6-8&quot;)</pre></div></div>

<div id="attachment_227" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.scienco.org/wp-content/multinorm-1-3.png"><img src="http://www.scienco.org/wp-content/multinorm-1-3-300x300.png" alt="multinorm-1-3" title="multinorm-1-3" width="300" height="300" class="size-medium wp-image-227" /></a><p class="wp-caption-text">multinorm-1-3</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.scienco.org/2009/qqmultinorm-r-evaluating-the-normality-of-a-sample/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simulation and Quantiles for the Scaled Inverse Chi-Square Distribution</title>
		<link>http://www.scienco.org/2008/simulation-and-quantiles-for-the-scaled-inverse-chi-square-distribution/</link>
		<comments>http://www.scienco.org/2008/simulation-and-quantiles-for-the-scaled-inverse-chi-square-distribution/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 19:20:27 +0000</pubDate>
		<dc:creator>Mikkel Meyer Andersen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[Statistics]]></category>

		<guid isPermaLink="false">http://www.scienco.org/?p=207</guid>
		<description><![CDATA[Although R supports a lot of different probability distributions, it does not support the scaled inverse chi-square distribution - well, not directly. But it can of course be implemented. Let . Because of how the scaled inverse chi-square distribution is defined, it's possible to simulate from it in R as follows (checking the arguments is [...]]]></description>
			<content:encoded><![CDATA[<p>Although R supports a lot of different probability distributions, it does not support the scaled inverse chi-square distribution - well, not directly. But it can of course be implemented.<span id="more-207"></span></p>
<p>Let <span class='MathJax_Preview'><img src='http://www.scienco.org/wp-content/plugins/latex/cache/tex_fec9a43f9b77606c9ef588ede1aebde6.gif' style=' padding-bottom:2px;' class='tex' alt="X \sim S \chi_\nu^{-2}" /></span>. Because of how the scaled inverse chi-square distribution is defined, it's possible to simulate from it in R as follows (checking the arguments is not included in the following code):</p>
<pre>
rinvchisq <- function(n, df, scale)
{
  return(scale * (1 / rchisq(n, df)))
}
</pre>
<p>When we're able to simulate from the distribution, we're able to find quantiles. But we can actually find those directly by using the definition of quantiles and the chi-squared distribution. Assume that we want to find the $\alpha$-quantile $x_\alpha$. Notice that with informal notation, the following holds:<br />
<p style='text-align:center;'><span class='MathJax_Preview'><img src='http://www.scienco.org/wp-content/plugins/latex/cache/tex_d0b1ad82bddb3ea64fbd2a6473a50284.gif' style='' class='tex' alt="<br />
\alpha =<br />
P\left (X \leq x_\alpha\right ) =<br />
P\left (S \chi_\nu^{-2} \leq x_\alpha\right ) =<br />
P\left (\chi_\nu^2 \geq \frac{S}{x_\alpha}\right ) =<br />
1 - P\left (\chi_\nu^2 \leq \frac{S}{x_\alpha}\right ) ,<br />
" /></span></p><br />
and hence<br />
<p style='text-align:center;'><span class='MathJax_Preview'><img src='http://www.scienco.org/wp-content/plugins/latex/cache/tex_ceb9ae29e1cb2ae84cb17c3fb81ac287.gif' style='' class='tex' alt="P\left (\chi_\nu^2 \leq \frac{S}{x_\alpha}\right ) = 1 - \alpha." /></span></p></p>
<p>If <span class='MathJax_Preview'><img src='http://www.scienco.org/wp-content/plugins/latex/cache/tex_38269120e225e8b3905398158bc60b43.gif' style=' padding-bottom:2px;' class='tex' alt="Y \sim \chi_\nu^2" /></span>, then <span class='MathJax_Preview'><img src='http://www.scienco.org/wp-content/plugins/latex/cache/tex_098d83cdddcc2fb53089b5a0e882d5d2.gif' style=' padding-bottom:2px;' class='tex' alt="\frac{S}{x_\alpha}" /></span> is the <span class='MathJax_Preview'><img src='http://www.scienco.org/wp-content/plugins/latex/cache/tex_378df00d12056b404d7d02aef9d8650b.gif' style=' padding-bottom:2px;' class='tex' alt="1-\alpha" /></span>-quantile <span class='MathJax_Preview'><img src='http://www.scienco.org/wp-content/plugins/latex/cache/tex_3ac1fc536899bee8d658a8dec3dd380a.gif' style=' padding-bottom:2px;' class='tex' alt="y_{1-\alpha}" /></span> for <span class='MathJax_Preview'><img src='http://www.scienco.org/wp-content/plugins/latex/cache/tex_57cec4137b614c87cb4e24a3d003a3e0.gif' style=' padding-bottom:2px;' class='tex' alt="Y" /></span>. All together we now have:<br />
<p style='text-align:center;'><span class='MathJax_Preview'><img src='http://www.scienco.org/wp-content/plugins/latex/cache/tex_77d143a1a24990164df885cbe0250db5.gif' style='' class='tex' alt="x_\alpha = \frac{S}{y_{1-\alpha}}." /></span></p></p>
<p>Because of this, we can implement the following in R (checking the arguments is still not included in the following code):</p>
<pre>
qinvchisq <- function(p, df, scale)
{
  return(scale / qchisq(1 - p, df))
}
</pre>
<p>Checking the functions can be done like this:</p>
<pre>
invchisqcheck <- function(p, n, df, scale)
{
  cat("Check of rinvchisq and qinvchisq...\n")
  cat("Quantiles:", p, "\n")
  cat("Simulated with rinvchisq:\n")
  cat(quantile(rinvchisq(simulations, df, scale), quantiles), "\n")
  cat("Calculated with qinvchisq:\n")
  cat(qinvchisq(quantiles, df, scale), "\n")
}

invchisqcheck(c(0.025, 0.975), 100000, 10, 1)
invchisqcheck(c(0.025, 0.975), 100000, 11, 68)
</pre>
<p>For further information, please refer to <a href="http://en.wikipedia.org/wiki/Scale-inverse-chi-square_distribution">http://en.wikipedia.org/wiki/Scale-inverse-chi-square_distribution</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.scienco.org/2008/simulation-and-quantiles-for-the-scaled-inverse-chi-square-distribution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

