{"id":2448,"date":"2015-04-29T10:12:15","date_gmt":"2015-04-29T14:12:15","guid":{"rendered":"http:\/\/blog.originlab.com\/?p=2448"},"modified":"2018-11-20T17:22:08","modified_gmt":"2018-11-20T22:22:08","slug":"script-to-find-best-fitting-model-for-each-data-in-each-group-and-create-summary-report","status":"publish","type":"post","link":"https:\/\/blog.originlab.com\/ja\/script-to-find-best-fitting-model-for-each-data-in-each-group-and-create-summary-report","title":{"rendered":"Script to Find Best Fitting Model for Each Data in Each Group and Create Summary Report"},"content":{"rendered":"<p>This post will show you how to write a analysis routine by Origin&#8217;s LabTalk script to find the best fitting model for each data in each group and create a summary report.<\/p>\n<p>If you want to walk through this step by step with me, please download this file: <a href=\"http:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/Sample.zip\" target=\"_blank\" rel=\"noopener\">Sample.xlsx\u00a0and Tutorial_Sample.ogs<\/a><\/p>\n<p>There are 5\u00a0columns in <strong>Sample.xlsx<\/strong>. The first column is GroupID, which contains 1, 2, &amp; 3. The second column is X data\u00a0and the rest 3 columns are Y data. So there are 3 * 3 = 9 Y datasets in all.<\/p>\n<p><a href=\"http:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/DOC-2393-sample.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2606\" src=\"http:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/DOC-2393-sample.png\" alt=\"DOC-2393-sample\" width=\"347\" height=\"251\" srcset=\"https:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/DOC-2393-sample.png 347w, https:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/DOC-2393-sample-300x217.png 300w\" sizes=\"auto, (max-width: 347px) 100vw, 347px\" \/><\/a><\/p>\n<p>There are 3 function candidates: <strong>ExpDec1<\/strong>,<strong> ExpDec2<\/strong> and <strong>ExpDec3<\/strong>. The goal is to find best fitting model\u00a0for each Y data in each group.<\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #0000ff;\">Run the script to\u00a0see the result<\/span><\/h3>\n<p>In Windows Explorer, copy <strong>Tutorial_Sample.ogs<\/strong> into your Origin&#8217;s <strong>User Files Folder<\/strong>. You can find Origin&#8217;s <strong>User Files folder<\/strong> by choosing\u00a0<strong>Start: All Programs: OriginLab: Origin 2015\/(the version you have): User Files Folder<\/strong>.<\/p>\n<p>In Origin, choose <strong>Window: Script Window<\/strong> menu to open the Script window. Run the following script<\/p>\n<pre class=\"\">run.section(Tutorial_Sample.ogs, main)\r\n<\/pre>\n<p>It will popup a dialog, asking you to select the data.\u00a0Select <strong>Sample.xlsx<\/strong>. Click OK. The script will run automatically and at the end, a Summary workbook is created to reportthe\u00a0best fitting function for each Y data in each group.<\/p>\n<p><a href=\"http:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/post2448_01.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-2647 size-full\" src=\"http:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/post2448_01.png\" alt=\"\" width=\"396\" height=\"228\" srcset=\"https:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/post2448_01.png 396w, https:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/post2448_01-300x173.png 300w\" sizes=\"auto, (max-width: 396px) 100vw, 396px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #0000ff;\">Review the Script behind the Scene<\/span><\/h3>\n<p>Now, let&#8217;s open the Tutorial_Sample.ogs to see how the script is written.<\/p>\n<p>Choose <strong>View: Code Builder<\/strong> menu to open the Code Builder. choose File: Open menu in Code Builder to open <strong>Tutorial_Sample.ogs<\/strong>\u00a0in your Origin User Files folder.<\/p>\n<p>Or in <strong>Code Builder<\/strong>, you can\u00a0choose <strong>File: New<\/strong> menu and create your own LabTalk Script File by following the steps below. See<a href=\"http:\/\/originlab.com\/doc\/LabTalk\/guide\/From-Files#Sections_in_an_OGS_FileSectionScript_Section\"> this page<\/a> for more information about creating and running ogs file<\/p>\n<p>Origin&#8217;s Labtalk script can be written into an ogs file with sections. Each section starts with section name in []. You can add [main] section at the beginning of the file to control the follow of the script.<\/p>\n<p>&nbsp;<\/p>\n<h4><span style=\"color: #0000ff;\">Import Excel File<\/span><\/h4>\n<p>Go to\u00a0\u00a0[ImportExcel] section. It opens a dialog for user to choose an Excel file and import it into Origin.<\/p>\n<pre class=\"lang:default decode:true\">[ImportExcel]\r\n    string FileName$; \/\/define a string variable FileName$\r\n    dlgfile fname:=FileName$ group:=\"*.xlsx; *.xls\";  \/\/ Open Browser to find an Excel file. Give the file name to FileName$\r\n    impExcel fname:=FileName$ subheader:=1 lname:=1 desig:=&lt;Unchanged&gt; options.names.FNameToSht:=0 options.names.FNameToBk:=0;  \/\/Import the Excel file\r\n    wks.col1.type = 2;  \/\/ Set 1st column as Disregard since it's just GroupID\r\n    wks.col2.type = 4;  \/\/ Set 2nd column as X<\/pre>\n<p>In [Main] section, \u00a0<span class=\"lang:default decode:true crayon-inline\">run.section(,ImportExcel);<\/span>\u00a0is used to call the [ImportExcel] section. See <a title=\"Run Section\" href=\"http:\/\/originlab.com\/doc\/LabTalk\/guide\/From-Files#Running_an_OGS_File\">this page<\/a> of how to run sections in ogs file.<\/p>\n<p>&nbsp;<\/p>\n<h4><span style=\"color: #0000ff;\">Add Filter to the Worksheet<\/span><\/h4>\n<p>We want to define a StringArray variable GroupList to hold group IDs. We will use it to set and change filter conditions. We define it in [main] section so that all later sections can have access to it,\u00a0according to <a href=\"http:\/\/www.originlab.com\/doc\/LabTalk\/guide\/Data-Types-and-vars#Scope_of_Variables\" target=\"_blank\" rel=\"noopener\">variable scope<\/a>.<\/p>\n<pre class=\"\">[Main]\r\n    run.section( , ImportExcel);\r\n    StringArray GroupList;<\/pre>\n<p>&nbsp;<\/p>\n<h4><span style=\"color: #0000ff;\">Get Unique Group IDs<\/span><\/h4>\n<p>We used the following script to get the unique groupIDs 1, 2, 3 into GroupList variable.<\/p>\n<p>Here, we can take advantage of a existing X-function <a href=\"http:\/\/www.originlab.com\/doc\/X-Function\/ref\/reducedup\" target=\"_blank\" rel=\"noopener\">reducedup<\/a>, with a dump Y data, since our groupID is numeric index number<\/p>\n<pre class=\"\">[GetGroupList]\r\n    range rr = col(1);   \/\/ Set a range variable pointing to the Group column\r\n    dataset dsX = rr;    \/\/ Setup a temporary loose dataset to hold groupIDs\r\n    dataset dsY = data(1,1,rr.getsize());  \/\/ Setup a temporary loose dataset with value 1\r\n    dataset dsX2, dsY2;  \/\/ Setup two extra datasets for result\r\n    reducedup iy:=(dsX, dsY) oy:=(dsX2, dsY2) xcount:=&lt;none&gt;;  \/\/ Reduce row by duplicated X values\r\n    GroupList.CopyFrom(dsX2);  \/\/ Get the clean ID list<\/pre>\n<p>&nbsp;<\/p>\n<h4><span style=\"color: #0000ff;\">Add Filter to 1st Column<\/span><\/h4>\n<p>Now we can go ahead to add the filter. Notice that although the groupID is numeric, we still want it be like categorical value.<\/p>\n<pre class=\"\">[AddFilter] \r\n    wks.col1.format = 2;  \/\/ Set the GroupID column to be text\r\n    wks.col1.filter = 1;  \/\/ Add filter to the column\r\n    wks.col1.filter$ = \"x=\"%(GroupList.GetAt(1)$)\"\";  \/\/ Set filter condition to be the first group in the list\r\n    wks.col1.filterenabled = 1;  \/\/ Enable the filter\r\n    wks.runfilter();  \/\/ Run the filter<\/pre>\n<p>Add the script to execute these above two sections to <span class=\"lang:default decode:true crayon-inline\">[Main]<\/span>\u00a0section.<\/p>\n<pre class=\"\">[Main]\r\n    run.section( , ImportExcel);\r\n    StringArray GroupList;\r\n    run.section( , GetGroupList);\r\n    run.section( , AddFilter);<\/pre>\n<p>&nbsp;<\/p>\n<h4><span style=\"color: #0000ff;\">Create Rank Model Analysis<\/span><\/h4>\n<p>The idea is to keep updating the input of the existing <a href=\"http:\/\/www.originlab.com\/doc\/X-Function\/ref\/funcRank\" target=\"_blank\" rel=\"noopener\">rank model<\/a> analysis and extract the result everytime, so we need to setup it first. You can use <a href=\"http:\/\/www.originlab.com\/doc\/LabTalk\/guide\/XFs-Overview#Generate_Script_from_Dialog_Settings\" target=\"_blank\" rel=\"noopener\"><strong>Generate Script<\/strong><\/a> method and no need to worry about those function index number.<\/p>\n<pre class=\"\">[CreateRankModel]\r\n    range rr = 3;     \/\/ Setup a range variable pointing to the first Y\r\n    funcRank -r 2 data:=rr funsel.category:=Exponential funsel.funclist:={20, 21, 22} adjrsq:=1 ssr:=1 rcs:=1;  \/\/ Rank Model Analysis\r\n    run -p au;        \/\/ Wait for it to calculate\r\n    page.active = 1;  \/\/ Go back to data sheet<\/pre>\n<p>Add script to execute this section to \u00a0<span class=\"lang:default decode:true crayon-inline\">[Main]<\/span> section.<\/p>\n<pre class=\"\">[Main]\r\n    run.section( , ImportExcel);\r\n    StringArray GroupList;\r\n    run.section( , GetGroupList);\r\n    run.section( , AddFilter);\r\n    run.section( , CreateRankModel);\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h4><span style=\"color: #0000ff;\">Loop through Groups and Y columns<\/span><\/h4>\n<p>Now it&#8217;s time to build a loop to go through all Y datasets in each group.<\/p>\n<pre class=\"\">[Main]\r\n\/\/ ... \r\nfor (int group = 1; group &lt;= GroupList.GetSize(); group++) {  \/\/ Loop through all groups\r\n     \/\/ Outer Loop: Do something 1\r\n     for (int col = 3; col &lt;= wks.ncols; col++) {  \/\/ Loop through all Ys\r\n         \/\/ Inner Loop: Do something2 2\r\n     };\r\n };<\/pre>\n<p>Set up a new section called <span class=\"lang:default decode:true crayon-inline \">[UpdateFilter]<\/span> and put it into the outside loop. Make two more sections <span class=\"lang:default decode:true crayon-inline\">[UpdateSourceCol]<\/span> and <span class=\"lang:default decode:true crayon-inline\">[UpdateSummary]<\/span>\u00a0and add to the inner loop.\u00a0Thus our analysis\u00a0routine in <span class=\"lang:default decode:true crayon-inline\">[Main]<\/span>\u00a0section would become:<\/p>\n<pre class=\"\">[main]\r\n    run.section( , ImportExcel);\r\n    StringArray GroupList;\r\n    run.section( , GetGroupList);\r\n    run.section( , AddFilter);\r\n    run.section( , CreateRankModel);\r\n    for (int group = 1; group &lt;= GroupList.GetSize(); group++) {\r\n        run.section( , UpdateFilter);\r\n        for (int col = 3; col &lt;= wks.ncols; col++) {\r\n            run.section( , UpdateSourceCol);\r\n            run.section( , UpdateSummary);\r\n        };\r\n };\r\n window -a Summary;  \/\/ Activate Summary sheet when finished.<\/pre>\n<p>&nbsp;<\/p>\n<h4><span style=\"color: #0000ff;\">Update Worksheet Filter Condition<\/span><\/h4>\n<p>In the outside loop, we need to update the worksheet filter every time.<\/p>\n<pre class=\"\">[UpdateFilter]\r\n    wks.col2.filter$ = \"x=\"%(GroupList.GetAt($(group))$)\"\";  \/\/ Change filter condition\r\n    wks.runfilter();  \/\/ Run the filter\r\n    run -p au;  \/\/ Wait for recalculating<\/pre>\n<p>&nbsp;<\/p>\n<h4><span style=\"color: #0000ff;\">Change Analysis Parameter<\/span><\/h4>\n<p>In the inner loop, we need to replace the input of rank model with current Y.<\/p>\n<pre class=\"\">[UpdateSourceCol]\r\n    run.section( , DeleteLastNLFit);  \/\/ Delete the previous NLFit, will talk about this in a sec.\r\n    range r1 = 2!1;  \/\/ Point to a result column that have green lock on it, in order to get the analysis setting tree\r\n    range r2 = $(col);  \/\/ Current Y\r\n    Tree tr;\r\n    op_change ir:=r1 tr:=tr op:=get;  \/\/ Get previous tree\r\n    tr.xfGetN.data.Range1.Y$ = %(r2.GetLayer()$)%(r2.name$);  \/\/ Update tree node\r\n    op_change ir:=r1 tr:=tr op:=run;  \/\/ Load the updated tree\r\n    run -p au;  \/\/ Wait for recalculating<\/pre>\n<p>Since every time the Rank Model analysis updates, a new NLFit calculation sheet will be added, we need to delete the previous fitting result before doing the updating, to avoid too many result sheets being added in the workbook.<\/p>\n<pre class=\"\">[DeleteLastNLFit]\r\n    for (int wp = page.nlayers; wp &gt; 2; wp--) {  \/\/ Loop through all sheet with index number bigger than 2\r\n       page.active = wp;  \/\/ Activate the worksheet\r\n       layer -duk;  \/\/ Delete it\r\n    };\r\n    page.active = 1;<\/pre>\n<p>&nbsp;<\/p>\n<h4><span style=\"color: #0000ff;\">Create and Update Summary Sheet<\/span><\/h4>\n<p>First we need to create a summary sheet if it does not exist yet.<\/p>\n<pre class=\"\">[CreateSummary]\r\n    range RawData = [%H]$(page.active)!;  \/\/ Point to the data sheet\r\n    string DataBookname$ = %H;  \/\/ Remember current workbook's name\r\n    newbook name:=\"Summary\" option:=lsname;  \/\/ New a workbook called \"Summary\"\r\n    wks.ncols = RawData.ncols - 1;  \/\/ Summary sheet will have one less column than in data sheet\r\n    wks.col1.lname$ = \"Group#\";  \/\/ Set longname label row over\r\n    wks.col2.lname$ = \"Y1\";\r\n    wks.col3.lname$ = \"Y2\";\r\n    wks.col4.lname$ = \"Y3\";\r\n    GroupList.CopyTo(wcol(1));   \/\/ Assign the 1st column with group name list\r\n    window -a %(DataBookname$);  \/\/ Go back to data sheet<\/pre>\n<p>Then in <span class=\"lang:default decode:true crayon-inline\">[UpdateSummary]<\/span>\u00a0section, check the existence of <strong>Summary<\/strong> book first, if not, call the above section.<\/p>\n<pre class=\"\">\u00a0[UpdateSummary]\r\n    if (exist(Summary, 2) != 2) {  \/\/ If no Summary existing\r\n        run.section( , CreateSummary)\r\n    };\r\n \r\n    range rR2 = [%H]2!5;    \/\/ The column with adj. R-square values\r\n    range rName = [%H]2!1;  \/\/ The column with function names\r\n    int pos = list(max(rR2),rR2);  \/\/ Find the function with highest R^2 value\r\n    if (pos != 0) {  \/\/ It is possible that none of the models converges\r\n        string Name$ = rName[$(pos)]$;\r\n        %(Summary, $(col - 1), $(group)) = \"%(Name$)\";  \/\/ Put function name into summary sheet\r\n    }\r\n    else {\r\n        %(Summary, $(col - 1), $(group)) = \"None\";    \/\/ If no luck, then put &lt;none&gt;\r\n    };\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>This post will show you how to write a analysis &hellip; <\/p>","protected":false},"author":14,"featured_media":2647,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_hide_featured_image":false,"_jetpack_featured_image_duplicate_dismissed":0,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[103,4],"tags":[],"class_list":["post-2448","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-programming-labtalk","category-data-analysis"],"jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p7DvU2-Du","jetpack_likes_enabled":true,"jetpack_featured_media_url":"https:\/\/blog.originlab.com\/wp-content\/uploads\/2015\/04\/post2448_01.png","post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/posts\/2448","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/comments?post=2448"}],"version-history":[{"count":50,"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/posts\/2448\/revisions"}],"predecessor-version":[{"id":10055,"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/posts\/2448\/revisions\/10055"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/media\/2647"}],"wp:attachment":[{"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/media?parent=2448"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/categories?post=2448"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.originlab.com\/ja\/wp-json\/wp\/v2\/tags?post=2448"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}