Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Thursday, September 13, 2018

Why, when passing an array element to a function through a ParamArray, does a varpointer arrive in the function?

Leave a Comment

I have noticed an oddity in VBA when using ParamArray and passing array elements through it. In some cases it is not the value of the array element that arrives in a function, but the var pointer. (Excel 2016, 32-bit).

After some plodding I found that the definition of the function as a variant array - in combination with a parameter list combined with a ParamArray - seems to be where the unexpected behaviour originates, but I can't see any feasible reasons why this would be so.

The behaviour reverts to normal when:
1) the variable r is removed in the function declarations
2) b is declared with Dim b()
3) the function returns a Variant, rather than a Variant()

I appreciate that it's a rather esoteric question, and it appears to be controllable for in various ways, but is there an explanation out there that elucidates this behaviour?

Sub Variantarraybug()    Dim b: b = [{1, 2, 3}]     Debug.Print farray1(2, b(1))(0)    Debug.Print Application.WorksheetFunction.Sum(farray1(2, b(1)))    Debug.Print Join(farray1(2, b(1)), " ")     Debug.Print farray2(2, b(1))(0)    Debug.Print Application.WorksheetFunction.Sum(farray2(2, b(1)))    Debug.Print Join(farray2(2, b(1)), " ")    Debug.Print  VarPtr(b(1)), VarPtr(b(2)) End Sub  Function farray1(r, ParamArray plop()) As Variant    farray1 = Array(plop(0), 3) End Function Function farray2(r, ParamArray plop()) As Variant()    farray2 = Array(plop(0), 5) End Function 

Result in the debug window:

 1    4   1 3    1    6   358808368 5    358808368     358808384  

Note 1: My understanding is that the VarPtr function returns the memory location of the start address of the memory required by that variable. Here it is used only to demonstrate that the unexpected number (358808368) that was seen by the farray2 function, is in fact the address of that element.

Note 2: This happens independent of how you generate the array (e.g. b=array(1,2,3), b=[1,2,3], etc.) and how b is declared (b, b(1 to 3), etc.). However, if you declare b with Dim b(), the unexpected behaviour disappears. (You can't print VarPtr(b) in that case, as VarPtr cannot accept array variables.)

0 Answers

Read More

Monday, February 19, 2018

Javascript performance optimization

Leave a Comment

I created the following js function

function csvDecode(csvRecordsList) {     var cel;     var chk;     var chkACB;     var chkAF;     var chkAMR;     var chkAN;     var csvField;     var csvFieldLen;     var csvFieldsList;     var csvRow;     var csvRowLen = csvRecordsList.length;     var frag = document.createDocumentFragment();     var injectFragInTbody = function () {tblbody.replaceChild(frag, tblbody.firstElementChild);};     var isFirstRec;     var len;     var newEmbtyRow;     var objCells;     var parReEx = new RegExp(myCsvParag, 'ig');     var tblbody;     var tblCount = 0;     var tgtTblBodyID;      for (csvRow = 0; csvRow < csvRowLen; csvRow++)     {         if (csvRecordsList[csvRow].startsWith(myTBodySep))         {             if (frag.childElementCount > 0)             {                 injectFragInTbody();             }             tgtTblBodyID = csvRecordsList[csvRow].split(myTBodySep)[1];             newEmbtyRow = getNewEmptyRow(tgtTblBodyID);             objCells = newEmbtyRow.cells;             len = newEmbtyRow.querySelectorAll('input')[0].parentNode.cellIndex; // Finds the cell index where is placed the first input (Check-box or button)              tblbody = getElById(tgtTblBodyID);             chkAF = toBool(tblbody.dataset.acceptfiles);             chkACB = toBool(tblbody.dataset.acceptcheckboxes) ;             chkAN = toBool(tblbody.dataset.acceptmultiplerows) ;             tblCount++;             continue;         }          csvRecordsList[csvRow] = csvRecordsList[csvRow].replace(parReEx, myInnerHTMLParag); // Replaces all the paragraph symbols ¶ used into the db.csv file with the tag <br> needed into the HTML content of table cells, this way will be possible to use line breaks into table cells         csvFieldsList = csvRecordsList[csvRow].split(myEndOfFld);          csvFieldLen = csvFieldsList.length;         for (csvField = 0; csvField < csvFieldLen; csvField++)         {             cel = chkAN ? csvField + 1 : csvField;             if (chkAF && cel === 1) {objCells[cel].innerHTML =  makeFileLink(csvFieldsList[csvField]);}              else if (chkACB && cel === len) {objCells[cel].firstChild.checked = toBool(csvFieldsList[csvField]);}             else {objCells[cel].innerHTML = csvFieldsList[csvField];}         }         frag.appendChild(newEmbtyRow.cloneNode(true));     }     injectFragInTbody();      var recNum = getElById(tgtTblBodyID).childElementCount;     customizeHtmlTitle();     return csvRow - tblCount + ' (di cui '+ recNum + ' record di documenti)'; } 

More than 90% of records could contain file names that have to be processed by the following makeFileLink function:

function makeFileLink(fname) {     return ['<a href="', dirDocSan, fname, '" target="', previewWinName, '" title="Apri il file allegato: ', fname, '" >', fname, '</a>'].join(''); } 

It aims to decode a record list from a special type of *.db.csv file (= a comma-separated values where commas are replaced by another symbol I hard-coded into the var myEndOfFld). (This special type of *.db.csv is created by another function I wrote and it is just a "text" file).

The record list to decode and append to HTML tables is passed to the function with its lone parameter: (csvRecordsList).

Into the csv file is hosted data coming from more HTML tables.

Tables are different for number of rows and columns and for some other contained data type (which could be filenames, numbers, string, dates, checkbox values).

Some tables could be just 1 row, others accept more rows.

A row of data has the following basic structure:

data field content 1|data field content 2|data field content 3|etc... 

Once decoded by my algorithm it will be rendered correctly into the HTML td element even if into a field there are more paragraphs. In fact the tag
will be added where is needed by the code:

csvRecordsList[csvRow].replace(par, myInnerHTMLParag) 

that replaces all the char I choose to represent the paragraph symbol I have hard-coded into the variable myCsvParag.

Isn't possible to know at programming time the number of records to load in each table nor the number of records loaded from the CSV file, nor the number of fields of each record or what table field is going to contain data or will be empty: in the same record some fields could contain data others could be empty. Everything has to be discovered at runtime.

Into the special csv file each table is separated from the next by a row witch contains just a string with the following pattern: myTBodySep = tablebodyid where myTBodySep = "targettbodydatatable" that is just a hard coded string of my choice. tablebodyid is just a placeholder that contains a string representing the id of the target table tbody element to insert new record in, for example: tBodyDataCars, tBodyDataAnimals... etc.

So when the first for loop finds into the csvRecordsList a string staring with the string into the variable myTBodySep it gets the tablebodyid from the same row: this will be the new tbodyid that has to be targeted for injecting next records in it

Each table is archived into the CSV file

The first for loop scan the csv record list from the file and the second for loop prepare what is needed to compile the targeted table with data.

The above code works well but it is a little bit slow: in fact to load into the HTML tables about 300 records from the CSV file it takes a bit more of 2.5 seconds on a computer with 2 GB ram and Pentium core 2 4300 dual-core at 1800 MHz but if I comment the row that update the DOM the function needs less than 0.1 sec. So IMHO the bottle neck is the fragment and DOM manipulating part of the code.

My aim and hope is to optimize the speed of the above code without losing functionalities.

Notice that I'm targeting just modern browsers and I don't care about others and non standards-compliant browsers... I feel sorry for them...

Any suggestions? Thanks in advance.

Edit 16-02.2018

I don't know if it is useful but lastly I've noticed that if data is loaded from browser sessionstorage the load and rendering time is more or less halved. But strangely it is the exact same function that loads data from both file and sessionstorage. I don't understand why of this different behavior considering that the data is exactly the same and in both cases is passed to a variable handled by the function itself before starting checking performance timing.

Edit 18.02.2018

  1. Number of rows is variable depending on the target table: from 1 to 1000 (could be even more in particular cases)
  2. Number of columns depending on the target table: from 10 to 18-20

3 Answers

Answers 1

In fact, DOM manipulations are way slower than simple innerHTML update.

I've made a simple benchmark for you.

Lets make a table 300x300 and fill 90000 cells with 'A'. There are two functions.

The first one is a simplified variant of your code which uses DOM methods:

var table = document.querySelector('table tbody');  var cells_in_row = 300, rows_total = 300;    var start = performance.now();  fill_table_1();  console.log('using DOM methods: ' + (performance.now() - start).toFixed(2) + 'ms');    table.innerHTML = '<tbody></tbody>';      function fill_table_1() {    var frag = document.createDocumentFragment();      var injectFragInTbody = function() {      table.replaceChild(frag, table.firstElementChild)    }      var getNewEmptyRow = function() {      var row = table.firstElementChild;      if (!row) {        row = table.insertRow(0);        for (var c = 0; c < cells_in_row; c++) row.insertCell(c);      }      return row.cloneNode(true);    }      for (var r = 0; r < rows_total; r++) {      var new_row = getNewEmptyRow();      var cells = new_row.cells;      for (var c = 0; c < cells_in_row; c++) cells[c].innerHTML = 'A';      frag.appendChild(new_row.cloneNode(true));    }    injectFragInTbody();    return false;  }
<table><tbody></tbody></table>

The second one prepares html string and put it into the table's innerHTML:

var table = document.querySelector('table tbody');  var cells_in_row = 300, rows_total = 300;    var start = performance.now();  fill_table_2();  console.log('setting innerHTML: ' + (performance.now() - start).toFixed(2) + 'ms');    table.innerHTML = '<tbody></tbody>';    function fill_table_2() {// setting innerHTML    var html = '';    for (var r = 0; r < rows_total; r++) {      html += '<tr>';      for (var c = 0; c < cells_in_row; c++) html += '<td>A</td>';      html += '</tr>';    }    table.innerHTML = html;    return false;  }
<table><tbody></tbody></table>

I believe you'll come to some conclusions.

Answers 2

I've got two thoughts for you.

1: If you want to know which parts of your code are (relatively) slow you can do very simple performance testing using the technique described here. I didn't read all of the code sample you gave but you can add those performance tests yourself and check out which operations take more time.

2: What I know of JavaScript and the browser is that changing the DOM is an expensive operation, you don't want to change the DOM too many times. What you can do instead is build up a set of changes and then apply all those changes with one DOM change. This may make your code less nice, but that's often the tradeoff you have when you want to have high performance.

Let me know how this works out for you.

Answers 3

You should start by refactoring your code in multiples functions to make it a bit more readable. Make sure that you are separating DOM manipulation functions from data processing functions. Ideally, create a class and get those variables out of your function, this way you can access them with this.

Then, you should execute each function processing data in a web worker, so you're sure that your UI won't get blocked by the process. You won't be able to access this in a web worker so you will have to limit it to pure "input/output" operations.

Good luck!

Read More

Monday, January 15, 2018

How do you implement __str__ for a function?

Leave a Comment

Given a function foo:

def foo(x):      pass 

Printing its representation by invoking str or repr gives you something boring like this:

str(foo) '<function foo at 0x119e0c8c8>' 

I'd like to know if it is possible to override a function's __str__ method to print something else. Essentially, I'd like to do:

str(foo) "I'm foo!' 

Now, I understand that the description of a function should come from __doc__ which is the function's docstring. However, this is merely an experiment.

In attempting to figure out a solution to this problem, I came across implementing __str__ for classes: How to define a __str__ method for a class?

This approach involved defining a metaclass with an __str__ method, and then attempting to assign the __metaclass__ hook in the actual class.

I wondered whether the same could be done to the class function, so here's what I tried -

In [355]: foo.__class__ Out[355]: function  In [356]: class fancyfunction(type):      ...:     def __str__(self):      ...:         return self.__name__      ...:       In [357]: foo.__class__.__metaclass__ = fancyfunction --------------------------------------------------------------------------- TypeError                                 Traceback (most recent call last) 

I figured it wouldn't work, but it was worth a shot!

So, what's the best way to implement __str__ for a function?

2 Answers

Answers 1

A function in Python is just a callable object. Using def to define function is one way to create such an object. But there is actually nothing stopping you from creating a callable type and creating an instance of it to get a function.

So the following two things are basically equal:

def foo ():     print('hello world')   class FooFunction:     def __call__ (self):         print('hello world')  foo = FooFunction() 

Except that the last one obviously allows us to set the function type’s special methods, like __str__ and __repr__.

class FooFunction:     def __call__ (self):         print('hello world')      def __str__ (self):         return 'Foo function'  foo = FooFunction() print(foo) # Foo function 

But creating a type just for this becomes a bit tedious and it also makes it more difficult to understand what the function does: After all, the def syntax allows us to just define the function body. So we want to keep it that way!

Luckily, Python has this great feature called decorators which we can use here. We can create a function decorator that will wrap any function inside a custom type which calls a custom function for the __str__. That could look like this:

def with_str (str_func):     def wrapper (f):         class FuncType:             def __call__ (self, *args, **kwargs):                 # call the original function                 return f(*args, **kwargs)             def __str__ (self):                 # call the custom __str__ function                 return str_func()          # decorate with functool.wraps to make the resulting function appear like f         return functools.wraps(f)(FuncType())     return wrapper 

We can then use that to add a __str__ function to any function by simply decorating it. That would look like this:

def foo_str ():     return 'This is the __str__ for the foo function'  @with_str(foo_str) def foo ():     print('hello world') 
>>> str(foo) 'This is the __str__ for the foo function' >>> foo() hello world 

Obviously, doing this has some limitations and drawbacks since you cannot exactly reproduce what def would do for a new function inside that decorator.

For example, using the inspect module to look at the arguments will not work properly: For the callable type, it will include the self argument and when using the generic decorator, it will only be able to report the details of wrapper. However, there might be some solutions, for example discussed in this question, that will allow you to restore some of the functionality.

But that usually means you are investing a lot of effort just to get a __str__ work on a function object which will probably very rarely be used. So you should think about whether you actually need a __str__ implementation for your functions, and what kind of operations you will do on those functions then.

Answers 2

If you find yourself wrapping functions, it's useful to look at functools.partial. It's primarily for binding arguments of course, but that's optional. It's also a class that wraps functions, removing the boilerplate of doing so from scratch.

from functools import partial  class foo(partial):     def __str__(self):         return "I'm foo!"  @foo def foo():     pass  assert foo() is None assert str(foo) == "I'm foo!" 
Read More

Monday, April 18, 2016

`qr.qy()` function in R

Leave a Comment

I can't find documentation as to the exact operation of this function. I have a QR factorization of a matrix X:

X = matrix(c(1,1,1,1,-1.5,-0.5,0.5,1.5,2.25,0.25,0.25, 2.25,-3.275,-0.125,0.125,3.375),  nrow=4, byrow=F)       [,1] [,2] [,3]   [,4] [1,]    1 -1.5 2.25 -3.375 [2,]    1 -0.5 0.25 -0.125 [3,]    1  0.5 0.25  0.125 [4,]    1  1.5 2.25  3.375 

The function qr(X) yields a list:

$qr (rounding output)      [,1]       [,2]          [,3]          [,4] [1,] -2.0          0          -2.5             0 [2,]  0.5     -2.236             0        -4.583 [3,]  0.5      0.447             2             0  [4,]  0.5      0.894        -0.929        -1.341  $rank [1] 4  $qraux [1] 1.500000 1.000000 1.368524 1.341641  $pivot [1] 1 2 3 4  attr(,"class") [1] "qr" 

I select the diagonal elements of qr(X)$qr, which I name z:

z = qr(X)$qr z = Q * (row(Q) == col(Q))       [,1]      [,2] [,3]      [,4] [1,]   -2  0.000000    0  0.000000 [2,]    0 -2.236068    0  0.000000 [3,]    0  0.000000    2  0.000000 [4,]    0  0.000000    0 -1.341641 

So far, so good. Now the next call I don't understand:

(raw = qr.qy(qr(X), z))       [,1] [,2] [,3] [,4] [1,]    1 -1.5    1 -0.3 [2,]    1 -0.5   -1  0.9 [3,]    1  0.5   -1 -0.9 [4,]    1  1.5    1  0.3 

MAKING SOME PROGRESS:

So, thanks to the answer and some reading, I think that the object qr(X)$qr contains R completely in the upper triangle:

     [,1]       [,2]          [,3]          [,4] [1,] -2.0          0          -2.5             0 [2,]          -2.236             0        -4.583 [3,]                             2             0  [4,]                                      -1.341 

The lower triangle of qr(X)$qr contains information about Q:

     [,1]       [,2]          [,3]          [,4] [1,]                                             [2,]  0.5                                        [3,]  0.5      0.447                              [4,]  0.5      0.894        -0.929       

Somehow calling qr.Q(qr(X)) returns Q using internally the function qr.qy() with qr() and a diagonal matrix of 1's as inputs.

But how is this operation carried out? How is the rest of the right upper corner of Q get filled? I think it makes use of $qraux, but how does it get to:

     [,1]       [,2] [,3]       [,4] [1,] -0.5  0.6708204  0.5  0.2236068 [2,] -0.5  0.2236068 -0.5 -0.6708204 [3,] -0.5 -0.2236068 -0.5  0.6708204 [4,] -0.5 -0.6708204  0.5 -0.2236068 

In short, How does qr.qy() work specifically?

I just found this: "qy.qr(): return the results of the matrix multiplications: Q %*% y, where Q is the order-nrow(x) orthogonal (or unitary) transformation represented by qr."

1 Answers

Answers 1

The matrix Q from a QR decomposition is only implicit in the return value of the function qr. The list element qr is a compact representation of the Q matrix; it is contained in the lower triangular part of list element qr and in the vector qraux. The upper triangular matrix R of a QR decomposition is the upper triangular part of the list element qr in the return value.

The R function qr.qy after some intermediate steps eventually calls the Lapack subroutine dormqr, which does NOT generate the Q matrix explicitly. It uses the information contained in list elements qr and qraux. See http://www.netlib.org/lapack/explore-html/da/d82/dormqr_8f.html .

So qr.qy does NOT transform the compact form of Q into the actual Q. It uses the compact form to compute Q %*% z.

The R function qr.Q (which you have done) uses qr.qy with a diagonal matrix with 1's on the diagonals to generate Q.

Why is it done like this? For efficiency reasons.

With the following code you can check this:

library(rbenchmark)  benchmark(qr.qy(XQR,z), {Q <- qr.Q(qr(X)); Q %*% z},  { Q %*% z},           replications=10000,            columns=c("test","replications","elapsed","relative")  ) 

with output

                                     test replications elapsed relative 3                           {    Q %*% z}        10000   0.022    1.000 2       {    Q <- qr.Q(qr(X));   Q %*% z}        10000   0.486   22.091 1                           qr.qy(XQR, z)        10000   0.152    6.909 

Lesson: only generate Q if you really need it in explicit form and if you need to generate it many times with different input matrices. If Q is fixed and doesn't change then you can use Q %*% z.

Read More