<?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>The ILNumerics Blog &#187; ILArray</title>
	<atom:link href="https://ilnumerics.net/blog/tag/ilarray/feed/" rel="self" type="application/rss+xml" />
	<link>https://ilnumerics.net/blog</link>
	<description>The Productivity Machine  &#124;  A fresh attempt for scientific computing  &#124;  http://ilnumerics.net</description>
	<lastBuildDate>Thu, 05 Dec 2024 09:09:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.41</generator>
	<item>
		<title>Uncommon data conversion with ILArray</title>
		<link>https://ilnumerics.net/blog/uncommon-data-conversion-with-ilarray/</link>
		<comments>https://ilnumerics.net/blog/uncommon-data-conversion-with-ilarray/#comments</comments>
		<pubDate>Tue, 07 Oct 2014 08:42:14 +0000</pubDate>
		<dc:creator><![CDATA[haymo]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[ILNumerics]]></category>
		<category><![CDATA[Usage]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[float]]></category>
		<category><![CDATA[ILArray]]></category>
		<category><![CDATA[pointer arithmetic]]></category>
		<category><![CDATA[unsafe]]></category>
		<category><![CDATA[ushort]]></category>

		<guid isPermaLink="false">http://ilnumerics.net/blog/?p=635</guid>
		<description><![CDATA[<p>ILNumerics Computing Engine supports the most common numeric data types out of the box: double, float, complex, fcomplex, byte, short, int, long, ulong If you need to convert from, let&#8217;s say ushort to float, you will not find any prepared conversion function in ILMath. Luckily, it is very easy to write your own: Here comes &#8230; <a href="https://ilnumerics.net/blog/uncommon-data-conversion-with-ilarray/" class="more-link">Continue reading <span class="screen-reader-text">Uncommon data conversion with ILArray</span> <span class="meta-nav">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://ilnumerics.net/blog/uncommon-data-conversion-with-ilarray/">Uncommon data conversion with ILArray</a> appeared first on <a rel="nofollow" href="https://ilnumerics.net/blog">The ILNumerics Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[<p>ILNumerics Computing Engine supports the most common numeric data types out of the box: double, float, complex, fcomplex, byte, short, int, long, ulong</p>
<p>If you need to convert from, let&#8217;s say ushort to float, you will not find any prepared conversion function in ILMath. Luckily, it is very easy to write your own:</p>
<p>Here comes a method which implements the conversion from ushort -&gt; float. A straight forward version first:</p>
<pre class="brush: csharp; title: ; notranslate">
        /// &lt;summary&gt;
        /// Convert ushort data to ILArray&amp;lt;float&gt;
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;A&quot;&gt;Input Array&lt;/param&gt;
        /// &lt;returns&gt;Array of the same size as A, single precision float elements&lt;/returns&gt;
        public static ILRetArray&lt;float&gt; UShort2Single(ILInArray&lt;ushort&gt; A) {
            using (ILScope.Enter(A)) {
                ILArray&lt;float&gt; ret = ILMath.zeros&lt;float&gt;(A.S);
                var retArr = ret.GetArrayForWrite();
                var AArr = A.GetArrayForRead();
                int c = 0;
                foreach (ushort a in A) {
                    retArr[c++] = a;
                }
                return ret;
            }
        }</pre>
<p><span id="more-635"></span>This method is used like that:</p>
<pre class="brush: csharp; title: ; notranslate">
            ushort[,] rawSensorData = new ushort[,] {{0,1,2},{3,4,5}};
            ILArray&lt;float&gt; converted = UShort2Single(rawSensorData);
            /*
             * &lt;Single&gt; [3,2]
             * [0]:          0          3
             * [1]:          1          4
             * [2]:          2          5
             */

            // continue working with 'converted' here...
</pre>
<p>The following method does the same but utilizes pointer arithmetic, hence it needs the /unsafe flag. Use this, if performance is critical and your data are sufficiently large:</p>
<pre class="brush: csharp; title: ; notranslate">
        /// &lt;summary&gt;
        /// Convert ushort data to ILArray&amp;lt;float&gt; (unsafe version)
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;A&quot;&gt;Input Array&lt;/param&gt;
        /// &lt;returns&gt;Array of the same size as A, single precision float elements&lt;/returns&gt;
        public unsafe static ILRetArray&lt;float&gt; UShort2SingleUnsafe(ILInArray&lt;ushort&gt; A) {
            using (ILScope.Enter(A)) {
                ILArray&lt;float&gt; ret = ILMath.zeros&lt;float&gt;(A.S);
                var retArr = ret.GetArrayForWrite();
                var AArr = A.GetArrayForRead();

                fixed (ushort* pAArr = AArr)
                fixed (float* pRetArr = retArr) {
                    ushort* pInWalk = pAArr;
                    ushort* pInEnd = pAArr + A.S.NumberOfElements;
                    float* pRetWalk = pRetArr;
                    while (pInWalk &lt; pInEnd) {
                        *(pRetWalk++) = /*implicit: (float)*/ (*(pInWalk++));
                    }
                }
                return ret;
            }
        }</pre>
<p>The post <a rel="nofollow" href="https://ilnumerics.net/blog/uncommon-data-conversion-with-ilarray/">Uncommon data conversion with ILArray</a> appeared first on <a rel="nofollow" href="https://ilnumerics.net/blog">The ILNumerics Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://ilnumerics.net/blog/uncommon-data-conversion-with-ilarray/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using ILArray as Class Attributes</title>
		<link>https://ilnumerics.net/blog/using-ilarray-as-class-attributes/</link>
		<comments>https://ilnumerics.net/blog/using-ilarray-as-class-attributes/#comments</comments>
		<pubDate>Thu, 07 Feb 2013 20:18:57 +0000</pubDate>
		<dc:creator><![CDATA[haymo]]></dc:creator>
				<category><![CDATA[Interesting/ useless]]></category>
		<category><![CDATA[Usage]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[function rule]]></category>
		<category><![CDATA[ILArray]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[Rules]]></category>
		<category><![CDATA[scope]]></category>
		<category><![CDATA[Specification]]></category>
		<category><![CDATA[usage]]></category>

		<guid isPermaLink="false">http://ilnumerics.net/blog/?p=293</guid>
		<description><![CDATA[<p>Update: Information in this article relates to older versions of ILNumerics. For version 5 and later updated information is found here: https://ilnumerics.net/ClassRules.html. A lot of people are confused about how to use ILArray as class member variables. The documentation is really sparse on this topic. So let&#8217;s get into it! Take the following naive approach: &#8230; <a href="https://ilnumerics.net/blog/using-ilarray-as-class-attributes/" class="more-link">Continue reading <span class="screen-reader-text">Using ILArray as Class Attributes</span> <span class="meta-nav">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://ilnumerics.net/blog/using-ilarray-as-class-attributes/">Using ILArray as Class Attributes</a> appeared first on <a rel="nofollow" href="https://ilnumerics.net/blog">The ILNumerics Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[<blockquote><p>Update: Information in this article relates to older versions of ILNumerics. For version 5 and later updated information is found here: <a title="Arrays in Classes" href="https://ilnumerics.net/ClassRules.html">https://ilnumerics.net/ClassRules.html</a>.</p></blockquote>
<p>A lot of people are confused about how to use ILArray as class member variables. The documentation is really sparse on this topic. So let&#8217;s get into it!</p>
<p>Take the following naive approach:</p>
<pre class="brush: csharp; title: ; notranslate">
class Test {

    ILArray&lt;double&gt; m_a;

    public Test() {
        using (ILScope.Enter()) {
            m_a = ILMath.rand(100, 100);
        }
    }

    public void Do() {
        System.Diagnostics.Debug.WriteLine(&quot;m_a:&quot; + m_a.ToString());
    }

}
</pre>
<p>If we run this:</p>
<pre class="brush: csharp; title: ; notranslate">
    Test t = new Test();
    t.Do();
</pre>
<p>&#8230; we get &#8230; an exception <img src="https://ilnumerics.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley" /> Why that?</p>
<h2>ILNumerics Arrays as Class Attributes</h2>
<p>We start with the rules and explain the reasons later.</p>
<ol>
<li>If an ILNumerics array is used as class member, it must be a local ILNumerics array: ILArray&lt;T&gt;</li>
<li>Initialization of those types must utilize a special function: ILMath.localMember&lt;T&gt;</li>
<li>Assignments to the local variable must utilize the .a property (.Assign() function in VB)</li>
<li>Classes with local array members should implement the IDisposable interface.</li>
<li>UPDATE: it is recommended to mark all ILArray local members as <code>readonly</code></li>
</ol>
<p>By applying the rules 1..3, the corrected example displays:</p>
<pre class="brush: csharp; title: ; notranslate">
class Test {

    ILArray&lt;double&gt; m_a = ILMath.localMember&lt;double&gt;();

    public Test() {
        using (ILScope.Enter()) {
            m_a.a = ILMath.rand(100,100);
        }
    }

    public void Do() {
        System.Diagnostics.Debug.WriteLine(&quot;m_a:&quot; + m_a.ToString());
    }

}
</pre>
<p>This time, we get, as expected:</p>
<pre class="brush: plain; title: ; notranslate">
m_a:&lt;Double&gt; [100,100]
   0,50272    0,21398    0,66289    0,75169    0,64011    0,68948    0,67187    0,32454    0,75637    0,07517    0,70919    0,71990    0,90485    0,79115    0,06920    0,21873    0,10221 ...
   0,73964    0,61959    0,60884    0,59152    0,27218    0,31629    0,97323    0,61203    0,31014    0,72146    0,55119    0,43210    0,13197    0,41965    0,48213    0,39704    0,68682 ...
   0,41224    0,47684    0,33983    0,16917    0,11035    0,19571    0,28410    0,70209    0,36965    0,84124    0,13361    0,39570    0,56504    0,94230    0,70813    0,24816    0,86502 ...
   0,85803    0,13391    0,87444    0,77514    0,78207    0,42969    0,16267    0,19860    0,32069    0,41191    0,19634    0,14786    0,13823    0,55875    0,87828    0,98742    0,04404 ...
   0,70365    0,52921    0,22790    0,34812    0,44606    0,96938    0,05116    0,84701    0,89024    0,73485    0,67458    0,26132    0,73829    0,10154    0,26001    0,60780    0,01866 ...
...
</pre>
<p>If you came to this post while looking for a short solution to an actual problem, you may stop reading here. The scheme will work out fine, if the rules above are blindly followed. However, for the interested user, we&#8217;ll dive into the dirty details next.</p>
<h2>Some unimportant Details</h2>
<p>Now, let&#8217;s inspect the reasons behind. They are somehow complex and most users can silently ignore them. But here they are:</p>
<p>The first rule is easy. Why should one use anything else than a local array? So lets step to rule two:</p>
<ul>
<li>Initialization of those types must utilize a special function: ILMath.localMember&lt;T&gt;</li>
</ul>
<p>A fundamental mechanism of the ILNumerics memory management is related to the associated livetime of certain array types. All functions return temporary arrays (ILRetArray&lt;T&gt;) which do only live for exactly one use. After the first use, they get disposed off automatically. In order to make use of such arrays <em>multiple</em> times, one needs to <em>assign</em> them to a local variable. This is the place, where they get converted and the underlying storage is taken for the local, persistent array variable.</p>
<p>At the same time, we need to make sure, the array is <em>released</em> after the current ILNumerics scope (using (ILScope.Enter())) { &#8230; }) was left. Thereforem the conversion to a local array is used. During the conversion, since we know, there is going to be a new array out there, we track the new array for later disposal in the current scope.</p>
<p>If the scope is left, it does exactly what it promises: it disposes off all arrays created since its creation. Now, local array members require a different behavior. They commonly live for the livetime of the class &#8211; not of the current ILNumerics scope. In order to prevent the local array to get cleaned up after the scope in the constructor body was left, we need something else.</p>
<p>The ILMath.localMember() function is the only exception to the rule. It is the only function, which does not return a temporary array, but a local array. In fact, the function is more than simple. All it does, is to create a new ILArray&lt;T&gt; and return that. Since bothe types of both sides of the assignment match, no conversion is necessary and the new array is not registered in the current scope, hence it is not disposed off &#8211; just what we need!</p>
<p>What, if we <em>have</em> to assign the return value from any function to the local array? Here, the next rule jumps in:</p>
<ul>
<li>Assignments to the local variable must utilize the .a property (.Assign() function in VB)</li>
</ul>
<p>Assigning to a local array <em>directly</em> would activate the disposal mechanism described above. Hence, in order to prevent this for a longer living class attribute, one needs to assign to the variable via the .a property. In Visual Basic, the .Assign() function does the same. This will prevent the array from getting registered into the scope.</p>
<h2>Example ILNumerics Array Utilization Class</h2>
<p>Now, that we archieved to prevent our local array attribute from getting disposed off magically, we &#8211; for the sake of completeness &#8211; should make sure, it gets disposed <em>somewhere</em>. The recommended way of disposing off things in .NET is &#8230; the <a href="http://msdn.microsoft.com/en-us/library/System.IDisposable.aspx" target="_blank">IDisposal</a> interface. In fact, for most scenarios, IDisposal is not necessary. The array would freed, once the application is shut down. But we recommend implementing IDisposable, since it makes a lot of things more consistent and error safe. However, we provide the IDisposable interface for convenience reasons only &#8211; we do not rely on it like we would for the disposal of unmanaged ressources. Therefore, a simplified version is sufficient here and we can omit the finalizer method for the class.</p>
<p>Here comes the full test class example, having all rules implemented:</p>
<pre class="brush: csharp; title: ; notranslate">
class Test : IDisposable {
    // declare local array attribute as ILArray&lt;T&gt;,
    // initialize with ILMath.localMember&lt;T&gt;()!
    readonly ILArray&lt;double&gt; m_a = ILMath.localMember&lt;double&gt;();

    public Test() {
        using (ILScope.Enter()) {
            // assign via .a property only!
            m_a.a = ILMath.rand(100,100);
        }
    }

    public void Do() {
        // assign via .a property only!
        m_a.a = m_a + 2; 

        System.Diagnostics.Debug.WriteLine(&quot;m_a:&quot; + m_a.ToString());
    }

    #region IDisposable Members
    // implement IDisposable for the class for transparent
    // clean up by the user of the class. This is for con-
    // venience only. No harm is done by ommitting the
    // call to Dispose().
    public void Dispose() {
        // simplified disposal pattern: we allow
        // calling dispose multiple times or not at all.
        if (!ILMath.isnull(m_a)) {
            m_a.Dispose();
        }
    }

    #endregion
}
</pre>
<p>For the user of your class, this brings one big advantage: she can &#8211; without knowing the details &#8211; clean up its storage easily.</p>
<pre class="brush: csharp; title: ; notranslate">
    using (Test t = new Test()) {
        t.Do();
    }
</pre>
<p>@UPDATE: by declaring your ILArray members as <code>readonly</code> one gains the convenience that the compiler will prevent you from accidentally assigning to the member somewhere in the code. The other rules must still be fullfilled. But by only using <code>readonly ILArray&lt;T&gt;</code> the rest is almost automatically.</p>
<h2>ILArray, Properties and Lazy Initialization</h2>
<p>@UPDATE2: Another common usage pattern for local class attributes is to delay the initialization to the first use. Let&#8217;s say, an attribute requires costly computations but is not needed always. One would usually create a property and compute the attribute value only in the get accessor:</p>
<pre class="brush: csharp; title: ; notranslate">
class Class {

    // attribute, initialization is done in the property get accessor
    Tuple&lt;int&gt; m_a;

    public Tuple&lt;int&gt; A {
        get {
            if (m_a == null) {
                m_a = Tuple.Create(1);  // your costly initialization here
            }
            return m_a;
        }
        set { m_a = value }
    }
}
</pre>
<p>How does this scheme go along with ILNumerics&#8217; ILArray? Pretty well:</p>
<pre class="brush: csharp; title: ; notranslate">
class Class1 : ILMath, IDisposable {

    readonly ILArray&lt;double&gt; m_a = localMember&lt;double&gt;();

    public ILRetArray&lt;double&gt; A {
        get {
            if (isempty(m_a)) {
                m_a.a = rand(1000, 2000); // your costly initialization here
            }
            return m_a; // this will only return a lazy copy to the caller!
        }
        set {
            m_a.a = value;
        }
    }

    public void Dispose() {
        // ... common dispose implementation
    }
}
</pre>
<p>Instead of checking for null in the get accessor, we simply check for an empty array. Alternatively you may initialize the attribute with some marking value in the constructor. NaN, MinValue, 0 might be good candidates.</p>
<p>The post <a rel="nofollow" href="https://ilnumerics.net/blog/using-ilarray-as-class-attributes/">Using ILArray as Class Attributes</a> appeared first on <a rel="nofollow" href="https://ilnumerics.net/blog">The ILNumerics Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://ilnumerics.net/blog/using-ilarray-as-class-attributes/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
