Showing posts with label optimization. Show all posts
Showing posts with label optimization. Show all posts

Monday, February 26, 2018

tf.keras.optimizers.Adam and other optimizers with minimization

Leave a Comment

I want to use the tf.contrib.keras to play around with it. However, there is something I don't understand. The classes from tf.train have a function minimize that you use for the optimization of your function. However, this minimize function does not exists for the classes in tf.contrib.keras.optimizers. Let's say we have the following code:

# tensorflow tf.train.AdamOptimizer(learning_rate=0.001) updateModel = trainer.minimize(loss)  # keras wrapper trainer=tf.contrib.keras.optimizers.Adam() updateModel = trainer.minimize(loss) # ERROR because minimize function does not exists 

The keras wrapper wont work because there is no minimize function. I'm trying to look for an example or workaround using tf.keras with tensorflow, but I don't find anything that helps me with that.

P.S. Here I'm using tf.contrib.keras.optimizers.Adam as a dummy example, but I would like to use other optimizers from the same package.

2 Answers

Answers 1

This caused because of differences between keras and tensorflow APIs. In keras optimizer is a function provided during model compilation which is used for a gradient descent optimization:

model.compile(optimizer='adam', ...) model.fit(..) <- optimiziation performed using Adam algorithm 

In tensorflow - you may use it in a custom manner as you presented.

Answers 2

Your confusion is caused by the fact that tf.contrib.keras API is not exactly tensorflow and isn't meant to be used like core tensorflow1.

If you look at the source code, the classes from tf.contrib.keras.optimizers are almost identical to ones from keras.optimizers. E.g., the first Optimizer and the second Optimizer, the first SGD and the second SGD, and so on. Keras is being gradually incorporated in tensorflow, but right now it's more like another project bundled together with tensorflow and can't be easily used with the arbitrary tensorflow graph. Instead, keras optimizers should be used with keras layers.

So you can either stick to the all-tensorflow API and use tf.train.AdamOptimizer (like you do right now) or to all-keras API and use Adam (see Marcin's answer). I don't see any value in mixing the two.


1 At least in TF 1.x. Keras might be integrated more with TF in the future versions.

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

Sunday, February 4, 2018

How to find unused classes in my HTML?

Leave a Comment

There are lots of tools for finding unused CSS rules in stylesheets, such as Chrome Audits and the Dust-Me Selectors add-on for Firefox (unfortunately not compatible with Firefox Quantum).

But what about the other way around?

How do I find classes that are in my HTML, that do not exist in my stylesheets?

4 Answers

Answers 1

This may be helpful: https://code.google.com/p/find-unused-classes/ . According to the description:

It shows classes that exist in css selectors and do not exist on html page and like-verse.

As Jim said, be warned that some classes may be unused by your stylesheets but still used in JavaScript.

Answers 2

HTML Inspector from https://github.com/philipwalton/html-inspector has this as one of its features:

  • Unused Classes: Sometimes you'll remove a CSS rule from your stylesheet but forget to remove the class from the HTML. The "unused-classes" rule compares all the class selectors in the CSS to the classes in the HTML and reports any that aren't being used.

    Classes that are in the HTML as JavaScript hooks can be ignored via a whitelist. By default, any class prefixed with js-, language-, or supports- is whitelisted. More information on the rationale behind this rule can be found here.

In its FAQ you will find a bookmarklet.

There is also grunt-unclassify but that project seems dead.

Answers 3

This is a partial answer on how to get the class names in html

var classesEvery = []; var elementsEvery = document.querySelectorAll('*'); for (var i = 0; i < elementsEvery.length; i++) {   var classes = elementsEvery[i].className.toString().split(/\s+/);   for (var j = 0; j < classes.length; j++) {     var thisClass = classes[j];     if (thisClass && classeEvery.indexOf(thisClass) === -1)       classeEvery.push(thisClass);   } } 

One can get the Class names in the html file using this Javascript code. For getting all classes used in CSS, try list-selectors. Still thinking on how to get class names used in Javascript angularJS. Added a working snippet with random HTML classes to test the js.

var classesEvery = [];  var elementsEvery = document.querySelectorAll('*');  for (var i = 0; i < elementsEvery.length; i++) {    var classes = elementsEvery[i].className.toString().split(/\s+/);    for (var j = 0; j < classes.length; j++) {      var thisClass = classes[j];      if (thisClass && classesEvery.indexOf(thisClass) === -1)        classesEvery.push(thisClass);    }  }  console.log(classesEvery);
.hidden {    display: none;  }
<!-- Some random HTML code. -->  <div ng-controller="HomeController" class="container hidden">      <span>Simple Notifications:</span>    <div class="rows">      <div class="col-md-2"><button class="btn btn-primary" href ng-click="simple()">Simple notification</button></div>      <div class="col-md-2"><button class="btn btn-warning" href ng-click="warning()">Warning notification</button></div>      <div class="col-md-2"><button class="btn btn-success" href ng-click="success()">Success notification</button></div>      <div class="col-md-2"><button class="btn btn-danger" href ng-click="error()">Error notification</button></div>      <div class="col-md-2"><button class="btn btn-grimace" href ng-click="wait()">Wait notification</button></div>      <div class="col-md-2"><button class="btn btn-primary" href ng-click="pop()">Link to other page</button></div>    </div>    <hr/>    <span>Addding Option from Script:</span>    <div class="rows">      <div class="col-md-6">        <Span>With CLose button</span>        <button class="btn btn-primary" href ng-click="close()">Close Button </button>      </div>      <div class="col-md-6">        <Span>Fade after 1 Sec</span>        <button class="btn btn-primary" href ng-click="timeout()">Html notification</button>      </div>    </div>    <br/>    <hr/>    <span>Custom Notification and Body output type:</span>    <div class="rows">      <div class="col-md-3"><button class="btn btn-primary" href ng-click="Custom_temp()">Custom template</button></div>      <div class="col-md-3"><button class="btn btn-primary" href ng-click="trusted_html()">Trusted HTML</button></div>      <div class="col-md-3"><button class="btn btn-primary" href ng-click="default_temp()">Default Template</button></div>      <div class="col-md-3"><button class="btn btn-primary" href ng-click="file_custom_temp()">Including file from Folder</button></div>    </div>    <script type="text/ng-template" id="myTemplate.html">      <div class="Custom_temp_html">        <p>Notice, custom temlate is not in the list</p>      </div>    </script>  </div>

Answers 4

The tool grunt-unclassify looks promising too, altough its use doesn't seem straightforward:

https://medium.com/@mariusc23/remove-unused-css-classes-in-html-bbb856da8bdf#.55u0uokfb

Read More

Wednesday, November 1, 2017

Mysql, SELECT only available companies and exclude the rest of the companies by one or more datetime ranges ( when they do not work )

Leave a Comment

I need to improve the search engine of my project.

The general idea: it's a system where clients can find easy available cleaning companies.

  1. Table "clients" - general table with all clients
  2. Table "companies" - general table with all cleaning companies
  3. Table "calendar" - here all companies can specify one or many different DATETIME ranges when they DO NOT take client requests

Here are the mysql tables

http://sqlfiddle.com/#!9/5c7034/1

The system has almost ~ 10000 clients and ~ 500 companies.

By default, all companies are always available for client requests. That's why we are using this calendar, where the companies can disable ( put date time ranges in future as 'not working' ) and the clients wont be able to make request if a company already specified that their services are closed on the choose date time period by the client.

If a client wants cleaning services on 2017-10-24 12:00:00 ( for 2 hours ) 1. he choose date : 2017-10-24 and start time 12:00:00 2. he specifies duration : 2 hours 3. the system must find all companies which are available between 2017-10-24 12:00:00 and 2017-10-24 14:00:00.

AS you can see the example data in table "calendar" now, the only available result should be Company 2, because they are working on the date choosen by the client ( 2017-10-24 12:00:00 ) .

My problem is that I'm forced to:

  1. To find all companies who cannot take the client request between 2017-10-24 12:00:00 and 2017-10-24 14:00:00

  2. To use the result of the first query with NOT IN where clause and finally to find the available companies.

 SELECT     * FROM     companies WHERE     companies.company_id NOT IN (      **SELECT         calendar.company_id     FROM         calendar     WHERE         calendar.not_available_from = '2017-10-24 12:00:00'     OR         calendar.not_available_from = '2017-10-24 14:00:00'** ); 

So, is there a better way to find these available companies ?

All of the companies right now are constantly modifying their closed( not working ) datetime ranges in future and this table calendar is huge, but without this table I cannot exclude the companies who cannot handle client requests.

Any advice about the current logic is very welcome.

Obligatory things to keep: all companies are always available by default for the clients and that's why they need manually to keep up to date when they do not want to work.

Everything else can be modified ...

Thanks!

4 Answers

Answers 1

If I understand correctly, you can do:

SELECT c.* FROM companies c WHERE NOT EXISTS (SELECT 1                   FROM calendar ca                   WHERE ca.company_id = c.company_id AND                         ca.not_available_to >= '2017-10-24 12:00:00' AND                         ca.not_available_from <= '2017-10-24 14:00:00'                  ); 

This is the correct way to implement an overlap. The above assumes that the end points are inclusive. So if a not-available period ends at 2017-10-24 12:00:00, then then the company would be filtered out. Change <= to < and >= to > for exclusive ranges.

For performance, you want an index on calendar(company_id, not_available_to, not_available_from).

Answers 2

You may use an outer join and then check for the NULL values like this

select cs.company_id,         cs.company_name from companies cs left join calendar cr on cr.company_id = cs.company_id AND                          cr.not_available_to >= '2017-10-24 12:00:00' AND                          cr.not_available_from <= '2017-10-24 14:00:00' where cr.company_id is null 

As mentioned by Gordon the following index is necessary on calendar table for reasonable performance:

create index ix_calendar_company_notavailable on        calendar(company_id, not_available_to, not_available_from) 

The InnoDB already has a clustered index on companies.company_id since it is a primary key, therefore, the query should be quite fast.

Answers 3

--To find all companies who cannot take the client request between  --2017-10-24 12:00:00 and 2017-10-24 14:00:00 SELECT *   FROM #companies  WHERE company_id          NOT IN ( --overlap of start time/end time with                   --availability and 'not working'                  SELECT company_id                    FROM #calendar                   WHERE not_available_from <= '2017-10-24 14:00:00' --@endtime                     AND not_available_to >= '2017-10-24 12:00:00'   --@starttime                     AND type = 'not working'                ) 

The above selects the company names that do not have an unavailability overlapping the start and endtime where the record type is 'not working'. I put 'not working' because I notice in the sqlfiddle you are putting client requests in the same table and putting a record type 'client request'.

Anyway...

In your question you ask if there's a different way to do it other than NOT IN. You could do NOT EXISTS equivalent, but the Actual Execution Plan is identical hence performance is identical.

Answers 4

Try using between on dates when you can and notice that it gets different results too.

SELECT     * FROM     companies WHERE     companies.company_id NOT IN (      SELECT         calendar.company_id     FROM         calendar     WHERE         calendar.not_available_from BETWEEN '2017-10-24 12:00:00' AND '2017-10-24 12:00:00'     OR         calendar.not_available_from BETWEEN '2017-10-24 14:00:00' AND '2017-10-24 14:00:00' ); 

This thread linked below has a good explanation of why using between is good, and is generally informative. Aside from what they say and they example they give, MySQL and SQL-Server (to my knowledge) will also handle date formats much better if you use between.

Why use the BETWEEN operator when we can do without it?

Read More

Saturday, July 22, 2017

optimization - stepping may behave oddly : iOS/Unity

Leave a Comment

I am trying to integrate unity to iOS application. I have followed this tutorial http://www.agnosticdev.com/blog-entry/swift/integrating-unity-and-vuforia-ios-swift-project

Now after integrating when i start my app it crashes and show this error on console : was compiled with optimization - stepping may behave oddly; variables may not be available.

Crash : Crash log

I have tried googling this and found these links :

  1. APPNAME was compiled with optimization - stepping may behave oddly; variables may not be available
  2. 'Project Name' was compiled with optimization - stepping may behave oddly; variables may not be available
  3. Xcode target compiled with optimization
  4. Xcode: Cannot set optimization level for debug

and nothing changed.

I have changed optimization level of both project and pod. I have also added this line to pod file : project 'MyProject', 'Debug - local'=>:debug, 'Debug - staging'=>:debug, 'Debug - PRODUCTION'=>:debug ( before target 'projectname' do)

Also I have unchecked Strip Engine Code in unity.

What can i do to overcome this error ? Any help would be appreciated, thanks.

0 Answers

Read More

Monday, April 10, 2017

Maximize objective function in R

Leave a Comment

I would like to find max value (response) given the size of difference (independent variables).

Here is some data:

 x <- "A B C   1  0.63 0.67 0.61  2  0.62 0.64 0.60  3  0.64 0.65 0.59  4  0.70 0.70 0.63  5  0.71 0.73 0.68  6  0.70 0.75 0.69  7  0.71 0.75 0.70  8  0.74 0.76 0.71  9  0.79 0.81 0.74 10 0.80 0.83 0.76 11 0.82 0.84 0.78 12 0.82 0.84 0.80 13 0.83 0.85 0.81 14 0.81 0.88 0.80 15 0.78 0.84 0.77 16 0.75 0.79 0.74 17 0.73 0.77 0.72 18 0.72 0.75 0.71 19 0.73 0.75 0.71 20 0.73 0.75 0.71 21 0.74 0.76 0.72 22 0.72 0.76 0.71 23 0.71 0.74 0.69 24 0.73 0.75 0.70 25 0.78 0.79 0.71 26 0.82 0.84 0.77 27 0.80 0.84 0.78 28 0.77 0.81 0.76 29 0.79 0.81 0.75 30 0.83 0.84 0.78 31 0.86 0.87 0.82 32 0.85 0.87 0.83 33 0.83 0.84 0.82 34 0.78 0.85 0.77 35 0.74 0.80 0.72 36 0.72 0.76 0.71 37 0.74 0.77 0.70 38 0.75 0.75 0.70 39 0.78 0.81 0.72 40 0.78 0.82 0.75"   # Or generate it like this x <- data.frame(   A = c(0.63, 0.62, 0.64, 0.7, 0.71, 0.7, 0.71, 0.74, 0.79, 0.8, 0.82, 0.82, 0.83, 0.81, 0.78, 0.75, 0.73, 0.72, 0.73, 0.73, 0.74, 0.72, 0.71, 0.73, 0.78, 0.82, 0.8, 0.77, 0.79, 0.83, 0.86, 0.85, 0.83, 0.78, 0.74, 0.72, 0.74, 0.75, 0.78, 0.78),   B = c(0.67, 0.64, 0.65, 0.7, 0.73, 0.75, 0.75, 0.76, 0.81, 0.83, 0.84, 0.84, 0.85, 0.88, 0.84, 0.79, 0.77, 0.75, 0.75, 0.75, 0.76, 0.76, 0.74, 0.75, 0.79, 0.84, 0.84, 0.81, 0.81, 0.84, 0.87, 0.87, 0.84, 0.85, 0.8, 0.76, 0.77, 0.75, 0.81, 0.82),   C = c(0.61, 0.6, 0.59, 0.63, 0.68, 0.69, 0.7, 0.71, 0.74, 0.76, 0.78, 0.8, 0.81, 0.8, 0.77, 0.74, 0.72, 0.71, 0.71, 0.71, 0.72, 0.71, 0.69, 0.7, 0.71, 0.77, 0.78, 0.76, 0.75, 0.78, 0.82, 0.83, 0.82, 0.77, 0.72, 0.71, 0.7, 0.7, 0.72, 0.75)) 

And here some adjustment:

data <- read.table(text=x, header = TRUE)  data$diff_AC <- with(data, (A-C)) data$diff_AB <- with(data, (A-B))  with(data, plot(A~1, col=1)) with(data, points(B~1, col=2)) with(data, points(C~1, col=3)) 

Calculate return:

data$retA <- with(data, as.numeric(c(0,diff(A))/lag(A,1))) 

Now using optim find the size of difference of A vs B and A vs C at which the return of A (retA) is highest given all data of A.

This should be done separately for negative return and positive return.

I have tried this, but I'm not sure how to bring in the return A part into optim.

max.rss <- function(data, par) { with(data, -sum((par[1] * (B - A) + (C - A))^2)) } result <- optim(par = 0, max.rss, data = data, method = "Brent", lower = 0, upper = 1)  

EDIT:

So the question is at which level (the size of difference) diff_AB and diff_AC should be so that the retA (return of series A) is highest (maximised) and what is the difference size diff_AB and diff_AC at which the retA is at its minimum (the highest negative rate).

with(data, plot(retA ~ diff_AB, ylim=c(-0.1,0.1), xlim=c(-.1,.1))) with(data, points(retA ~ diff_AC, col="red3")) 

EDIT2:

It's very likely that the question is not well defined, or with current explanation it does not necessarily makes sense.

Any proposition towards analysis/modeling the underlying dynamics is welcome!

EDIT 3:

Here is possible solution somewhat based on existing answer:

data$rank_min <- with(data, ave(retA, diff_AB, FUN=function(x) rank(x, ties.method="min"))) data$rank_max <- with(data, ave(retA, diff_AB, FUN=function(x) rank(x, ties.method="max")))  with(data, data[rank_min==min(rank_min), ]) with(data, data[rank_max==max(rank_max), ]) 

or (but I'm not sure whether this is fully correct)

diff_binAB <- with(data, unique(diff_AB)) mse <- numeric(length(diff_binAB))  for(i in 1:length(diff_binAB)){ pwise <- with(data, lm(retA ~ diff_AB*(diff_AB < diff_binAB[i]) + diff_AB*(diff_AB >= diff_binAB[i]))) mse[i] <- summary(pwise)[6] }  mse <- as.numeric(mse) mse   diff_binAB[which(mse==min(mse))] # -0.07 

1 Answers

Answers 1

If you don't want to rely on a single observation (like with data[which.max(retA), ]) you can either use 10% quantiles :

with(data, summary(diff_AB[retA < quantile(data$retA, 0.1)])) with(data, summary(diff_AC[retA < quantile(data$retA, 0.1)]))  with(data, summary(diff_AB[retA > quantile(data$retA, 0.9)])) with(data, summary(diff_AC[retA > quantile(data$retA, 0.9)])) 

or estimate a model of the dependence

m1 <- with(data, lm(retA~diff_AC+diff_AB)) summary(m1)  m2 <- with(data, lm(retA ~ I(diff_AC+diff_AB))) summary(m2) 

But you might want to account for the autocorrelation of your time-series residuals:

plot(m2$residuals, type = "l") 

linear model

For example, let's assume it is an AR(1) process:

library(astsa)  m3 <- with(data, sarima(retA, 1,0,0, xreg=cbind(diff_AB, diff_AC))) 

linear model with AR(1) errors

and then predict retA based on this model.

Read More

Tuesday, January 31, 2017

What are the rules to order the keywords in a MySQL boolean search?

Leave a Comment

When I change the order of the keywords in a boolean search, I get the same result but very different performance results.

The profiling on MySQL 5.6.33 with a MyISAM table, ft_min_word_len=2 and description_index as a FULLTEXT index on title and description returns this:

# Query 1 SELECT id FROM archive, topic WHERE topic.type=0 AND archive.status=2 AND MATCH(title, description) AGAINST ('+house* +tz*' IN BOOLEAN MODE) AND archive.topicId = topic.id ORDER BY archive.featured DESC, archive.submissionDate DESC LIMIT 0,20 

Result:

Total count: 12 Key_read_requests: 2384607 Creating sort index: 7.950430 sec (!) Duration: 8.851252 sec 

# Query 2 SELECT id FROM archive, topic WHERE topic.type=0 AND archive.status=2 AND MATCH(title, description) AGAINST ('+tz* +house*' IN BOOLEAN MODE) AND archive.topicId = topic.id ORDER BY archive.featured DESC, archive.submissionDate DESC LIMIT 0,20 

Result:

Total count: 12 Key_read_requests: 415 Creating sort index: 0.003449 Duration: 0.004054 sec 

Total records per keyword:

tz*: 135092 tz: 25596 house*: 12 

Explain is the same for both queries:

id | select_type | Table   | Type     | Key               | Key len | Ref             | Rows | Extra 1  | SIMPLE      | archive | fulltext | description_index | 0       |                 | 1    | Using where; Using filesort 1  | SIMPLE      | topic   | eq_ref   | PRIMARY           | 3       | archive.topicId | 1    | Using where 

Only Key_read_requests and Creating sort index are different between the 2 queries.

It seems that:

  1. the order of the keyword order is a critical performance factor
  2. the keywords are used in reverse order
  3. having the most discriminating keyword at the end improves the performance.

Questions:

  • What is the reason of this big performance difference?
  • What are the rules/best practices? (I could not find anything in the documentation of mysql).

2 Answers

Answers 1

Edit after OP comment:
I'm not sure about the exact query plan when resolving this query.
Sometimes one operation is more expensive than another therefore doing the less expensive operation first can sort out many rows that then don't have to go through the more expensive operation which leads to a reduced running time.
(In your example one of the matching-operations could be more expensive than the other which increases and reduces running time by changing the order of the strings to match against).

Answers 2

Did you run both queries against a fresh started instance? Its possible you are just gaining perfomance plus due to filled caches on the second run.

Read More

Tuesday, September 20, 2016

R: optimization based on historical data

Leave a Comment

I have a matrix of monthly returns and a vector of forecasts. I want to minimize my risk for a given level of return (based on the forecast). The forecasts are just the anticipated % change in value of the asset. The risk is based on the 5th percentile of the vector that is the result of passing a given portfolio through the monthly returns:

library(nloptr) library(ggplot2)  #load csv files balances<-as.matrix(t(c(-3300000, 2000000, -7700000, 5500000, -4000000, 1000000))) forecast<-as.matrix(t(c(-0.000768006, 0.000635124, 0.001526249, -0.008919934, 0.000152549, 0.001271481))) mReturns<-read.csv(file="C:/Users/Desktop/mReturns.csv", header=TRUE, sep=",", row.names=1)  mReturns<-round(mReturns, digits=8) forecast<-round(forecast, digits=8)  colnames(balances)<-letters[1:ncol(balances)] colnames(forecast)<-letters[1:ncol(forecast)] colnames(mReturns)<-letters[1:ncol(forecast)]  #Minimize Variance: fn <- function(H) {     X<-balances * (1 - H)     Y<-t(t(mReturns) * as.vector(X))     return(quantile(rowSums(Y), .05, na.rm=TRUE)) }  fn2 <- function(H) {     return(-fn(H)) }  #For a given forecast: target<-0 eqn <- function(H) {     X <- balances * (H)     return(sum(X * forecast) - target) }  loops<-6 n<-length(balances)  # Initialize a matrix to contain allocation and statistics eff<-matrix(nrow=2+loops, ncol=n+3) colnames(eff) <- c(colnames(balances), "Target", "Variance", "Forecast")  #Find the forecast for the 100% strategy pars <-rep(1, n) eff[1,1:n]<-pars eff[1,n+2]<-fn(pars) eff[1,n+3]<-eqn(pars)  #Find the strategy that maximizes forecast pars2<-rep(0,n) pars2[which(balances*forecast>=0)]<-1 eff[2,1:n]<-pars2 eff[2,n+2]<-fn(pars2) eff[2,n+3]<-eqn(pars2)  #Constrain the values in H lH<-rep(0, ncol(balances)) uH<-rep(1,ncol(balances))  pars2<-rep(1, n)  #initial guess is all 1's  increment = (eff[2,n+3]-eff[1,n+3])/(loops+1) for (i in 1:loops) {     target<-c(eff[2,n+3]-(i)*increment)  #target forecast     sol <- auglag(pars, fn=fn2, gr=NULL, heq=eqn, lower=lH, upper=uH, nl.info = FALSE, control = list(xtol_rel = 1e-8, maxeval = 20000))     targetHolder<-target     target<-0     eff[i+2,]<-c(sol$par, targetHolder, fn(sol$par), eqn(sol$par)) }  #Random Portfolios set.seed(10) randoms<-matrix(runif(10000*ncol(balances)), ncol=ncol(balances)) dots<-cbind(apply(randoms, 1, fn), apply(randoms, 1, eqn))  #graph x11() eff<-as.data.frame(eff) dots<-as.data.frame(dots)  ggplot() +     geom_point(data=dots, aes(V1, V2),size=3, color=rgb(115,150,0,max=255)) +     geom_line(data=eff, aes(Variance, Forecast), size=1, color=rgb(187,8,38, max=255)) +     geom_hline(yintercept = 0) + geom_vline(xintercept = 0) +     ggtitle("Frontier") +     labs(x="Variance", y="Forecast") +     theme_bw() +     scale_x_continuous(labels = comma) +     scale_y_continuous(labels = comma) +     geom_point(data=eff, aes(Variance, Forecast),size=3, color=rgb(187,8,38,max=255)) 

monthly returns (this is the best set I can get for illustrating the problem):

                    AAA           BBB           CCC           DDD           EEE           FFF 10/1/2006 -0.0273758311 -0.0173219254 -0.0092231793 -0.0138312574 -0.0124329157 -0.0124668848 11/1/2006  0.0386007238  0.0195502377  0.0097401588  0.0115189105 -0.0125419543  0.0065488401 12/1/2006  0.0180668473  0.0380363598  0.0137722146 -0.0103839765 -0.0110926718  0.0454652348 1/1/2007   0.0006337939 -0.0111542926 -0.0301578502  0.0142295446 -0.0180118359 -0.0101971958 2/1/2007  -0.0193818090  0.0038791343 -0.0147327469  0.0171395937 -0.0106915572 -0.0135595788 3/1/2007   0.0136933213 -0.0042708969  0.0272062488 -0.0086841626  0.0051172709  0.0125940716 4/1/2007   0.0304574997  0.0047998366 -0.0017821783  0.0288433537  0.0160311962  0.0127407857 5/1/2007   0.0233737324  0.0157028153 -0.0170184226  0.0122388783  0.0387973703  0.0187209825 6/1/2007   0.0067673716 -0.0081553009 -0.0182637526  0.0680350676  0.0472285071 -0.0113937077 7/1/2007   0.0195654783  0.0132667474 -0.0086871710 -0.0124935191 -0.0042241618  0.0068406573 8/1/2007   0.0076524606  0.0118484592  0.0353900671  0.0249734320  0.0087112958  0.0093050735 9/1/2007  -0.0435798575 -0.0075768758  0.0275545857 -0.0407258270  0.0004736651 -0.0027072510 10/1/2007  0.0924749572  0.0130880968  0.0002592090  0.0845218362  0.0644348088  0.0440939105 11/1/2007  0.0201274740  0.0179104478  0.0093311906  0.0350746684  0.0427970555  0.0136322114 12/1/2007 -0.0305820454 -0.0114417576  0.0308341887 -0.0249386286 -0.0477620911  0.0144194107 1/1/2008  -0.0093848937 -0.0339930944 -0.0036721437  0.0069662916  0.0061454765 -0.0028018861 2/1/2008   0.0321881064 -0.0107229158  0.0484552051  0.0198235360 -0.0027127500  0.0143914474 3/1/2008   0.0294150171  0.0122131189  0.0265085560  0.0323534622  0.0075926301  0.0254695311 4/1/2008  -0.0254592330 -0.0066361671  0.0185567006 -0.0307842234 -0.0328013313  0.0286580144 5/1/2008   0.0291005291 -0.0005567083 -0.0247055516  0.0492000484  0.0012745099 -0.0089663123 6/1/2008   0.0239931448  0.0037978529 -0.0103297983  0.0218807620  0.0267767258  0.0051699625 7/1/2008  -0.0010460251  0.0063562528 -0.0057476747  0.0181476849 -0.0281745247  0.0153658223 8/1/2008  -0.0270157068 -0.0099754374 -0.0146689710  0.0243589740 -0.0048676019 -0.0145000950 9/1/2008  -0.0848041326 -0.0878987342 -0.0039763301 -0.0543735223 -0.0370300926 -0.0608455410 10/1/2008 -0.0740827846 -0.0175974242  0.0228906428 -0.1397058821  0.0037639971 -0.0415954026 11/1/2008 -0.1518923038 -0.0915974459  0.0736264752 -0.1118110238 -0.1235463915 -0.0915839817 12/1/2008 -0.0413297394 -0.0741477980  0.0566584579 -0.0762846012 -0.0286790030 -0.0090366179 1/1/2009   0.1018431740 -0.0138403655  0.0268870859  0.0098509388  0.0231128587  0.1137102530 2/1/2009  -0.0962574426 -0.0094018259  0.0092303638 -0.0036590625 -0.0077260893 -0.0877180491 3/1/2009   0.0023529412 -0.0152682256 -0.0784996236 -0.0266487893 -0.0365901429 -0.0112385858 4/1/2009   0.0943661972  0.0104763235 -0.0096417819  0.0496085860  0.0129365079  0.0457810403 5/1/2009   0.0447590448  0.0313104783 -0.0059523944  0.0459061643  0.0631117103  0.0018114575 6/1/2009   0.1088146729  0.1020038871  0.0261932537  0.1138436318  0.0838591685  0.0667520530 7/1/2009  -0.0019750648  0.0021285653 -0.0007242318  0.0099870620 -0.0487995829 -0.0012006498 8/1/2009   0.0338899196  0.0142614395  0.0209125845  0.0361374737  0.0668151452  0.0081318060 9/1/2009  -0.0118435220 -0.0330880153  0.0189410175 -0.0253958301 -0.0240898396 -0.0023146525 10/1/2009  0.0529055690 -0.0126856436  0.0369378363  0.0711407143  0.0187286653  0.0225674916 11/1/2009  0.0344946533  0.0312127860 -0.0053280313  0.0144219837 -0.0008296452  0.0119628738 12/1/2009  0.0281204846  0.0096031119  0.0393401412  0.0235369340  0.0368954311  0.0245940621 1/1/2010  -0.0291891892 -0.0276924929 -0.0683577530 -0.0136428779 -0.0062689978 -0.0501956104 2/1/2010  -0.0073496659 -0.0119497245  0.0268182226 -0.0560575728 -0.0073543270 -0.0274364703 3/1/2010   0.0106573929 -0.0605965660  0.0166050081  0.0279786409  0.0184367195 -0.0266312540 4/1/2010   0.0224220224  0.0200787139 -0.0499893623  0.0188144624  0.0325203247  0.0021386431 5/1/2010   0.0034741070 -0.0011770861 -0.0003196447  0.0144877542 -0.0091364566 -0.0217087350 6/1/2010  -0.1007248729 -0.0407882676  0.0318856314 -0.0586643576 -0.0355315523 -0.0801113284 7/1/2010   0.0146775746  0.0359019862  0.0382420201  0.0316565244 -0.0039637605  0.0243683048 8/1/2010   0.0720891629  0.0337352573  0.0130681681  0.0206279554  0.0290375846  0.0419094755 9/1/2010   0.0082946251 -0.0149149085  0.0240407343  0.0050973650 -0.0191465044 -0.0186178363 10/1/2010  0.0665789185  0.0238757684  0.0146598812  0.0333195239  0.0295184853  0.0766648450 11/1/2010  0.0151172357  0.0133973711  0.0336604101 -0.0078097478  0.0044326247  0.0073961279 12/1/2010 -0.0190456894 -0.0257545523 -0.0437106512 -0.0011144347 -0.0017699119 -0.0542719355 1/1/2011   0.0568005783 -0.0007040901  0.0378451737  0.0262445077  0.0190380763  0.0186467768 2/1/2011  -0.0119222124  0.0339482449 -0.0028272754 -0.0018625333  0.0074702196  0.0332486551 3/1/2011   0.0022747503  0.0077437740 -0.0062301897  0.0003004991  0.0162084538 -0.0037602140 4/1/2011   0.0249654628 -0.0095899674 -0.0261717073  0.0354075923  0.0120431890  0.0333889816 5/1/2011   0.0562241263  0.0369933586  0.0353491621  0.0200583972  0.0191514125  0.0400365245 6/1/2011  -0.0325403336 -0.0223259711  0.0029648152 -0.0117927481 -0.0328489560 -0.0323495644 7/1/2011   0.0146975692 -0.0159177176  0.0014845420  0.0245501284  0.0195096504  0.0138190955 8/1/2011   0.0186629526  0.0138111236  0.0468851189 -0.0064491408  0.0015673977 -0.0190004131 9/1/2011  -0.0226961991 -0.0071796760  0.0036396795 -0.0330925481 -0.0203705594  0.0006315789 10/1/2011 -0.0988621526 -0.0367760677 -0.0016869980 -0.1381365404 -0.0698847952 -0.0611543587 11/1/2011  0.0690333264  0.0234214579 -0.0167155471  0.0770244711  0.0293022346  0.0236049899 12/1/2011 -0.0082292574 -0.0162392626  0.0086228941 -0.0306649633  0.0064108885 -0.0176603663 1/1/2012  -0.0034166341 -0.0093690249  0.0102717068 -0.0357295909 -0.0072456670 -0.0371443429 2/1/2012   0.0485845822  0.0187222544  0.0093176468  0.0763997010  0.0227318248  0.0154309081 3/1/2012   0.0097150864  0.0077680940 -0.0606509309  0.0117255850  0.0132927441  0.0113973102 4/1/2012  -0.0428346748  0.0031960895 -0.0211174021 -0.0616378357 -0.0132171821  0.0024040267 5/1/2012  -0.0011598685  0.0133058471  0.0347109283 -0.0427081690  0.0134970570 -0.0079442404 6/1/2012  -0.0612541126 -0.0528943962  0.0265316552 -0.0646046778 -0.0534101827 -0.0606632923 7/1/2012   0.0553551180  0.0223914600 -0.0221831931  0.0152781926  0.0240015740  0.0187389416 8/1/2012   0.0217815980 -0.0108868657  0.0172106230 -0.0170718584  0.0109387431 -0.0348938186 9/1/2012  -0.0132874486  0.0212409887  0.0006377956  0.0066476282  0.0195680830  0.0289570552 10/1/2012  0.0037783375  0.0166393546  0.0051289010  0.0019735538  0.0040720757  0.0245647508 11/1/2012  0.0038606312  0.0000000000 -0.0265851526 -0.0022644484 -0.0142498744  0.0042675357 12/1/2012  0.0025959042 -0.0072535648 -0.0286130154 -0.0489700375  0.0021118266  0.0033222591 1/1/2013  -0.0031645570  0.0147380254 -0.0486735937  0.0411386231  0.0010066431  0.0167873094 2/1/2013   0.0011544012 -0.0342174903 -0.0654305847  0.0319919529 -0.0031108877  0.0330202969 3/1/2013  -0.0196021908 -0.0417383547 -0.0087616625  0.0041925528 -0.0295091542 -0.0453079179 4/1/2013   0.0215622856  0.0127011571  0.0038614299 -0.0203384796  0.0098347756 -0.0132852096 5/1/2013  -0.0138156001  0.0214065270 -0.0427148166  0.0097436671  0.0084300305  0.0257607596 6/1/2013  -0.0688782956 -0.0229508197 -0.0304629093 -0.0652935412 -0.0281445781 -0.0137329287 7/1/2013  -0.0347926027  0.0012501645  0.0079269110 -0.0394347242 -0.0116223686  0.0050003846 8/1/2013  -0.0338817926 -0.0063744496  0.0012055870 -0.0326360551  0.0145950131  0.0109461115 9/1/2013  -0.0026890756  0.0253968254  0.0139553083 -0.0340809061 -0.0181266017  0.0011357613 10/1/2013  0.0558364229  0.0445691434  0.0017347621  0.0762463339  0.0208292961  0.0229919831 11/1/2013  0.0042562247 -0.0166100648 -0.0067903218 -0.0165498253 -0.0094049904 -0.0028833358 12/1/2013 -0.0349650350  0.0277533593 -0.0368020343 -0.0351883563 -0.0182777460  0.0077111292 1/1/2014  -0.0243741765  0.0120967742 -0.0266983220 -0.0110494902 -0.0028184893  0.0126554337 2/1/2014  -0.0146297547 -0.0076663045  0.0314581713 -0.0210129322 -0.0434938896 -0.0201264259 3/1/2014   0.0191868433  0.0186142709  0.0023576343  0.0292198115  0.0057845269  0.0234317070 4/1/2014   0.0361945316 -0.0068677217 -0.0178485935  0.0364295499  0.0036284465 -0.0006520794 5/1/2014   0.0029198659  0.0158147925  0.0128994503  0.0132598662  0.0062066454  0.0055825419 6/1/2014   0.0038818201 -0.0081690641  0.0055025913 -0.0041043938  0.0101419878 -0.0169430425 7/1/2014   0.0200859291  0.0235750522  0.0023639137  0.0179844668  0.0201279157  0.0032269894 8/1/2014  -0.0194798357 -0.0191836735 -0.0105253101 -0.0247154181 -0.0260168559 -0.0184223993 9/1/2014   0.0021477663 -0.0126627430 -0.0166746378  0.0052540178  0.0041394531 -0.0222685633 10/1/2014 -0.0636519503 -0.0254094412 -0.0416934585 -0.0947966609 -0.0261578426 -0.0384673979 11/1/2014  0.0068665599 -0.0118003213 -0.0305377641  0.0013318247 -0.0091425528 -0.0077636061 12/1/2014 -0.0348942942 -0.0165676774 -0.0513513556 -0.0323739586 -0.0055609505 -0.0043912176 1/1/2015  -0.0362737016 -0.0091544819 -0.0111909311 -0.0364614693 -0.0242873130 -0.0293504411 2/1/2015  -0.0514481242 -0.0337482356  0.0191506171 -0.0094300950 -0.0880458693 -0.0671678784 3/1/2015   0.0059263077  0.0250996016 -0.0178885567 -0.0557158943  0.0173391939 -0.0084137809 4/1/2015  -0.0266393443 -0.0398367664 -0.0010855227 -0.1022781142 -0.0083987014 -0.0386745266 5/1/2015   0.0330263158  0.0219253862 -0.0032458554  0.0498921894  0.0379965466  0.0405091517 6/1/2015  -0.0312062158  0.0034988117 -0.0370281860 -0.0485734132 -0.0289889795 -0.0242878828 7/1/2015   0.0051275309  0.0273666206  0.0129901792  0.0060967874 -0.0054011118  0.0115310698 8/1/2015  -0.0440810988  0.0003201639 -0.0058116534 -0.0795580758 -0.0382705683 -0.0062426491 9/1/2015  -0.0395457033 -0.0203559083  0.0378654941 -0.0749722897 -0.0126706388  0.0301347414 10/1/2015  0.0015671748 -0.0113042342 -0.0046693964 -0.0775158974 -0.0006783238 -0.0106053911 11/1/2015  0.0153627312  0.0196285771 -0.0057204213  0.0398620240  0.0143730891 -0.0168825368 12/1/2015  0.0259176240 -0.0224267565 -0.0183120461  0.0007267065 -0.0208114991 -0.0338906051 1/1/2016  -0.0027311211 -0.0222782124  0.0192451285 -0.0272167213 -0.0358715265  0.0209724443 2/1/2016  -0.0258797754 -0.0212260952 -0.0036366319 -0.0007064285 -0.0066676232  0.0029476787 3/1/2016   0.0085746416 -0.0333264048  0.0612226330  0.0074985366  0.0401193145 -0.0018368846 4/1/2016   0.0699651568  0.0197104358  0.0207718249  0.1070122134  0.0306663595  0.0481229297 5/1/2016  -0.0096391820  0.0270612216  0.0487323576  0.0343442572  0.0362376556  0.0052673163 6/1/2016  -0.0455083520 -0.0134136326 -0.0277524101 -0.0460086088 -0.0399143600 -0.0229674264 7/1/2016   0.0332093151 -0.0797031077  0.0684744419  0.1128105301  0.0128562573 -0.0046478370 8/1/2016   0.0050680181 -0.0066329992  0.0012697102 -0.0089113465 -0.0161536118  0.0024245690 9/1/2016   0.0019904459  0.0067531679 -0.0081372403  0.0025174229  0.0016026871  0.003045776 

As you can see, the red line is not the most efficient set of solutions: enter image description here

3 Answers

Answers 1

I would go with quantile spline regression (package fields). Here I did the model to fit 10% of the points (just to run it faster for the example).

library(fields) dots <- dots[base::sample(NROW(dots), 1000), ] fit90 = qsreg(x=dots$V1, y=dots$V2, alpha=0.95, lam=1E7) plot(x=dots$V1, y=dots$V2, main=("alpha=95%")) points(x=dots$V1, y=fitted(fit90), col="red") 

Then you can tweek the parameters to choose the threshold that suits you (90%, 95%, 99% of the limit of your points) and then play with the lambda argument to get the smoothing you want (it goes fro 0 to infinite..)

enter image description here

Answers 2

One thing that will help with the visualization is to show opacity. By adding an alpha to your aesthetics you will see the data in depth better.

For example:

ggplot() +     geom_point(data=dots, aes(V1, V2),size=3, color=rgb(115,150,0,max=255), alpha=0.05) +     geom_line(data=eff, aes(Variance, Forecast), size=1, color=rgb(187,8,38, max=255)) +     geom_hline(yintercept = 0) + geom_vline(xintercept = 0) +     ggtitle("Frontier") +     labs(x="Variance", y="Forecast") +     theme_bw() +     scale_x_continuous(labels = comma) +     scale_y_continuous(labels = comma) +     geom_point(data=eff, aes(Variance, Forecast),size=3, color=rgb(187,8,38,max=255)) 

This provides: enter image description here

Now your optimization looks a lot better.

Answers 3

I don't have a high enough score to comment, but it looks like you need a mean-variance optimisation function. (That said, there are difficulties in this approach: see a paper that I wrote for more details.)

Anyway, you could try the portfolio.optim function from the package tseries. Here's an example of the code:

portfolio.optim(x, pm = mean(x), riskless = FALSE, shorts = FALSE, rf = 0.0, reslow = NULL, reshigh = NULL, covmat = cov(x), ...) 

To give you some more background, you may find these slides useful.

I hope that helps you.

Read More

Sunday, August 14, 2016

Optimizing SELECT query performance

Leave a Comment

I have a SELECT statement that runs really slow, it's holding back our night process.

The query is: (Please don't comment about the implicit join syntax, this is automatically generated by Informatica that runs this code) :

SELECT *   FROM STG_DIM_CRM_CASES,V_CRM_CASE_ID_EXISTS_IN_DWH,stg_scd_customers_key  WHERE STG_DIM_CRM_CASES.CRM_CASE_ID = V_CRM_CASE_ID_EXISTS_IN_DWH.CASE_ID(+)    AND STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    and STG_DIM_CRM_CASES.Case_Create_Date between  stg_scd_customers_key.start_date(+) and  stg_scd_customers_key.end_date(+) 

edit: The actual query selects only account_number,start_date,end_date and one other column which is not indexed.

Tables info :

STG_DIM_CRM_CASES

Index - (Account_Number,Case_Create_Date) size - 270k records. 

stg_scd_customers_key

Index - Account_Number,Start_Date,End_Date Partitioned - End_Date Size - 500 million records. 

V_CRM_CASE_ID_EXISTS_IN_DWH(View) -

select  t.case_id from crm_ps_rc_case t, dim_crm_cases x where t.case_id=x.crm_case_id; 

dim_crm_cases -

Indexed - (crm_case_id) Size - 100 million . 

crm_ps_rc_case -

Size - 270k records 

Edit - If it wasn't clear, the view returns 270k records .

The query without the join to stg_scd is taking seconds, looks like it is the part that causing the performance issues, the view runs in seconds too although it is being joined to a 100 Million records table. Right now the query is taking somewhere between 12 to 30 minutes, depends how busy our sources are.

Here is the EXECUTION PLAN :

6   |   0 | SELECT STATEMENT                |                             |  3278K|  1297M|   559K  (4)| 02:10:37 |       |       |        |      |            | 7   |   1 |  PX COORDINATOR                 |                             |       |       |            |          |       |       |        |      |            | 8   |   2 |   PX SEND QC (RANDOM)           | :TQ10003                    |  3278K|  1297M|   559K  (4)| 02:10:37 |       |       |  Q1,03 | P->S | QC (RAND)  | 9   |*  3 |    HASH JOIN OUTER              |                             |  3278K|  1297M|   559K  (4)| 02:10:37 |       |       |  Q1,03 | PCWP |            | 10  |   4 |     PX RECEIVE                  |                             | 29188 |    10M| 50662   (5)| 00:11:50 |       |       |  Q1,03 | PCWP |            | 11  |   5 |      PX SEND HASH               | :TQ10002                    | 29188 |    10M| 50662   (5)| 00:11:50 |       |       |  Q1,02 | P->P | HASH       | 12  |*  6 |       HASH JOIN RIGHT OUTER     |                             | 29188 |    10M| 50662   (5)| 00:11:50 |       |       |  Q1,02 | PCWP |            | 13  |   7 |        BUFFER SORT              |                             |       |       |            |          |       |       |  Q1,02 | PCWC |            | 14  |   8 |         PX RECEIVE              |                             | 29188 |   370K| 50575   (5)| 00:11:49 |       |       |  Q1,02 | PCWP |            | 15  |   9 |          PX SEND BROADCAST      | :TQ10000                    | 29188 |   370K| 50575   (5)| 00:11:49 |       |       |        | S->P | BROADCAST  | 16  |  10 |           VIEW                  | V_CRM_CASE_ID_EXISTS_IN_DWH | 29188 |   370K| 50575   (5)| 00:11:49 |       |       |        |      |            | 17  |* 11 |            HASH JOIN            |                             | 29188 |   399K| 50575   (5)| 00:11:49 |       |       |        |      |            | 18  |  12 |             TABLE ACCESS FULL   | CRM_PS_RC_CASE              | 29188 |   199K|   570   (1)| 00:00:08 |       |       |        |      |            | 19  |  13 |             INDEX FAST FULL SCAN| DIM_CRM_CASES$1PK           |   103M|   692M| 48894   (3)| 00:11:25 |       |       |        |      |            | 20  |  14 |        PX BLOCK ITERATOR        |                             | 29188 |    10M|    87   (2)| 00:00:02 |       |       |  Q1,02 | PCWC |            | 21  |  15 |         TABLE ACCESS FULL       | STG_DIM_CRM_CASES           | 29188 |    10M|    87   (2)| 00:00:02 |       |       |  Q1,02 | PCWP |            | 22  |  16 |     BUFFER SORT                 |                             |       |       |            |          |       |       |  Q1,03 | PCWC |            | 23  |  17 |      PX RECEIVE                 |                             |   515M|    14G|   507K  (3)| 01:58:28 |       |       |  Q1,03 | PCWP |            | 24  |  18 |       PX SEND HASH              | :TQ10001                    |   515M|    14G|   507K  (3)| 01:58:28 |       |       |        | S->P | HASH       | 25  |  19 |        PARTITION RANGE ALL      |                             |   515M|    14G|   507K  (3)| 01:58:28 |     1 |  2982 |        |      |            | 26  |  20 |         TABLE ACCESS FULL       | STG_SCD_CUSTOMERS_KEY       |   515M|    14G|   507K  (3)| 01:58:28 |     1 |  2982 |        |      |            | 27  ------------------------------------------------------------------------------------------------------------------------------------------------------------ 28    29  Predicate Information (identified by operation id): 30  --------------------------------------------------- 31    32     3 - access("STG_DIM_CRM_CASES"."ACCOUNT_NUMBER"="STG_SCD_CUSTOMERS_KEY"."ACCOUNT_NUMBER"(+)) 33         filter("STG_DIM_CRM_CASES"."CASE_CREATE_DATE">="STG_SCD_CUSTOMERS_KEY"."START_DATE"(+) AND  34                "STG_DIM_CRM_CASES"."CASE_CREATE_DATE"<="STG_SCD_CUSTOMERS_KEY"."END_DATE"(+)) 35     6 - access("STG_DIM_CRM_CASES"."CRM_CASE_ID"="V_CRM_CASE_ID_EXISTS_IN_DWH"."CASE_ID"(+)) 36    11 - access("T"."CASE_ID"="X"."CRM_CASE_ID") 

Notes: Adding indexes may be an issue, depends on the index. This is not the only place this tables are being used, so indexes may interfere with other commands(Inserts mostly) on these tables.

I've also tried adding a filter on stg_scd and excluding all the dates smaller than the minimum date in Table_Cases, but that didn't help because it filtered only 1 year of records.

Thanks in advance.

6 Answers

Answers 1

THEORY: What I believe to be happening is the engine is having to resolve the 100m+ records from view join to 500m records BEFORE it applies limiting criteria (thus it creates a cross join and even if it can use indexes that's alot of records to generate then parse. So even though you wrote it as an outer join, the engine isn't able to processes it that way (I don't know why)

So at a minimum 100m*500m = 50,000m that's a lot of data to generate and then parse/limit.

By eliminating the view, the engine may be better able to optimize and use the indexes thus eliminating the need for the 50,000m record join.

Areas where I would focus my time in troubleshooting:

  • Eliminate the view just to remove it as a potential overhead issue.
  • Recognize no tie between stg_scd_customers_key and V_CRM_CASE_ID_EXISTS_IN_DWH exists. This means the engine may be doing a cross join BEFORE the results of STG_DIM_CRM_CASES to stg_scd_customers_key have been resolved.

CONSIDER eliminating the view, or using an inline view

Eliminating the view:

SELECT *   FROM STG_DIM_CRM_CASES        ,crm_ps_rc_case t       ,dim_crm_cases x        ,stg_scd_customers_key  WHERE t.case_id=x.crm_case_id    AND STG_DIM_CRM_CASES.CRM_CASE_ID = t.CASE_ID(+)    AND STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    AND STG_DIM_CRM_CASES.Case_Create_Date         between  stg_scd_customers_key.start_date(+) and stg_scd_customers_key.end_date(+) 

using an inline view:

SELECT *   FROM STG_DIM_CRM_CASES    (select  t.case_id    from crm_ps_rc_case t, dim_crm_cases x    where t.case_id=x.crm_case_id) V_CRM_CASE_ID_EXISTS_IN_DWH       ,stg_scd_customers_key  WHERE STG_DIM_CRM_CASES.CRM_CASE_ID = V_CRM_CASE_ID_EXISTS_IN_DWH.CASE_ID(+)    AND STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    AND STG_DIM_CRM_CASES.Case_Create_Date         between  stg_scd_customers_key.start_date(+) and stg_scd_customers_key.end_date(+) 

As to why: - http://www.dba-oracle.com/art_hints_views.htm

While order of the where clause SHOULDN'T matter consider: On the off chase the engine is executing in the order listed, limiting the 500m down and then adding the supplemental data from the view would logically be faster.

SELECT *   FROM STG_DIM_CRM_CASES,stg_scd_customers_key,V_CRM_CASE_ID_EXISTS_IN_DWH  WHERE STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    and STG_DIM_CRM_CASES.Case_Create_Date between  stg_scd_customers_key.start_date(+) and  stg_scd_customers_key.end_date(+)    and STG_DIM_CRM_CASES.CRM_CASE_ID = V_CRM_CASE_ID_EXISTS_IN_DWH.CASE_ID(+) 

Answers 2

Your problem is that Oracle really only has two ways to get the rows it needs from stg_scd_customers_key. Either (A) it does a single FULL SCAN of that table and then filters out the rows it doesn't want or else (B) it does 270,000 index lookups, at 3 to maybe 5 logical I/Os each (depending on the height of your index), plus another 1 logical I/O to actually read the block from the table.

Given the multiblock read and other optimizations available with a FULL SCAN, and based on your table statistics, Oracle's optimizer is guessing that the FULL SCAN would be faster. And there's a good chance that it's right.

What you need to do is give Oracle a better option.

If you cannot use materialized views where you are, a good "poor man's" materialized view is something called a covering index. Now, that's not reasonable for your query, since you do a SELECT *. But do you really need every column from stg_scd_customers_key?

If you can pare down the list of columns you get from stg_scd_customers_key, you can create an index that (A) starts with account_number, start_date, and end_date and (B) includes all the other columns you need to select.

For example:

SELECT stg_im_crm_cases.*, V_CRM_CASE_ID_EXISTS_IN_DWH.*, stg_scd_customers_key.column_1, stg_scd_customers_key.column_2   FROM STG_DIM_CRM_CASES,V_CRM_CASE_ID_EXISTS_IN_DWH,stg_scd_customers_key  WHERE STG_DIM_CRM_CASES.CRM_CASE_ID = V_CRM_CASE_ID_EXISTS_IN_DWH.CASE_ID(+)    AND STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    and STG_DIM_CRM_CASES.Case_Create_Date between  stg_scd_customers_key.start_date(+) and  stg_scd_customers_key.end_date(+) 

If you could make that your query, and create an index on stg_scd_customers_key (account_number, start_date, end_date, column_1, column_2), then you will have given Oracle a better alternative. Now it can read the index alone, instead of the table.

With tables that big, there are no guarantees until you try it. But covering indexes are often just what the doctor ordered. (All the usual caveats about new indexes apply of course).

Answers 3

some considerations:

1) INDEX
crm_ps_rc_case has no index on case_id this is a problem, you are joining 270k <-> 100m with HASH JOIN (not good)

2) SELECTED COLUMNS
the view V_CRM_CASE_ID_EXISTS_IN_DWH selects t.case_id but it should select x.crm_case_id instead, at least, until you do not resolve indexing of t.case_id. This will spread HASH JOIN over all your execution plan.. (not good)

3) BETWEEN
range joining/filtering is always a problem, especially on large tables but you could restrict the problem adding conditions on range. let me explain, try to add these conditions to your WHERE clause:

AND stg_scd_customers_key.end_date =  (        SELECT min(r.end_date)        FROM stg_scd_customers_key r        WHERE  r.end_date >= STG_DIM_CRM_CASES.Case_Create_Date ) AND stg_scd_customers_key.start_date =  (        SELECT max(r.start_date)        FROM stg_scd_customers_key r        WHERE  r.start_date <= STG_DIM_CRM_CASES.Case_Create_Date ) 

yes, it will calculate 270k * 2 subqueries, but the final join will work on much less recs limiting IO operations (it should be better)

4) INDEX COLUMN ORDER
there are conflicting reports if it does, or if it does not matter, but in my experience.. it does. It could be only a minor improvement but you can try to modify the index on stg_scd_customers_key inverting the order of Start_Date and End_Date, in my experience I have found it more efficient for range filtering to have the upper bound before the lower bound in the index.

Answers 4

The problem is in scanning all partitions:

18 | PX SEND HASH | :TQ10001 | 515M| 14G| 507K (3)| 01:58:28 | | | | S->P | HASH | 25 | 19 | PARTITION RANGE ALL |
| 515M| 14G| 507K (3)| 01:58:28 | 1 | 2982 | |
| | 26 | 20 | TABLE ACCESS FULL | STG_SCD_CUSTOMERS_KEY | 515M| 14G|

It happens because you are using left join to this table. Can you select 1 partition using bind variable? What is partition key? I don't see hint for parallel but according to you plan it uses parallel. Is there parallel degree on any object level? Can you remove parallel and post explain plan without parallel please?

Answers 5

I think the problem is the view, which I suspect is completely executing and returning all rows before conditions are being applied.

The overall effect of the view is to add the column CASE_ID that is not null if CRM_CASE_ID is found in it, null otherwise. I've replaced the view with two direct joins and a CASE expression. By replacing the convenience of the view with logic, you can join directly to each table in it and so avoid one level of join depth.

Try running this version of the query:

SELECT   a.*, b.*, c.*,   CASE WHEN t.case_id is not null and X.case_id is not null then t.case_id END CASE_ID FROM STG_DIM_CRM_CASES a LEFT JOIN crm_ps_rc_case t   ON t.case_id = a.CRM_CASE_ID LEFT JOIN dim_crm_cases x   ON x.crm_case_id = a.CRM_CASE_ID LEFT JOIN V_CRM_CASE_ID_EXISTS_IN_DWH b   ON a.CRM_CASE_ID = b.CASE_ID LEFT JOIN stg_scd_customers_key c   ON a.account_number = c.account_number  and a.Case_Create_Date between c.start_date and  stg_scd_customers_key.end_date 

If you replace a.*, b.*, c.* with only the exact columns you actually need, you'll get a speed up because there's simply less data to return. If you also put indexes on looked-up keys plus all the columns you actually select (a covering index), you will speed it up considerably, because index-only access can be used.

You should verify there are indexes in all joined-to columns as a minimum.

Answers 6

I would consider creating a materialized view (with refresh fast on demand) for the join between Table_cases and stg_scd. I assume much of the work in the join is on rows that don't change from day to day.

Read More

Friday, April 15, 2016

Algorithms: Using maximum flow to calculate correct matrix values

Leave a Comment

I am given an matrix A with size N x M with N,M <= 100. Matrix A consists of integer values A(i,j) where i and j are 0 < i < M and 0 < j < N. I am also given the "correct" column sums and row sums of the matrix. The given values A(i,j) are "incorrect" (they do not match the "correct" sums) and therefore we are provided with corresponding "incorrectness" values B(i,j), where B(i,j) ranges from 0 to A(i,j).

The goal is to calculate the "correct" values C(i,j) in the matrix, where A(i,j) - C(i,j) =< B(i,j), the C(i,j) values must also match the given row and column sums. I think I have to use maximum flow, but my attempts have not worked. How can I achieve this?

1 Answers

Answers 1

I'll just give you an example here.

matrix A:  10 10 10  10 10 10  10 10 10  matrix B:   2  3  4   5  6  4   3  2  1  matrix A-B:   8  7  6   5  4  6   7  8  9 

So you have the formula A[i,j] - C[i,j] <= B[i,j]. You can transform it into A[i,j] - B[i,j] <= C[i,j] which means that B[i,j] is the smallest thing that you need to subtract from A[i,j] to get something smaller or equal to C[i,j]. From here you know that you need to add something to the entries in matrix A-B.

Let's now find what and where to add.

Let's assume you are given the following row and column sizes:

c1 = 20/20 c2 = 19/21 c3 = 21/24  r1 = 21/21 r2 = 15/17 r3 = 24/27 

Above I wrote things in the form of:

(current flow through column or row) / (goal flow through column or row). 

Now let's build a network:

network

Now note that the total sum of rows = total sum of columns. So you try to push 'given sum of entries' - 'current sum of entries' from 's' to 't'.

Now, let's assume that the nodes are enumerated from left to right by natural numbers. Now, when you push something from a second level node to a third level node, say, you push something from node i, to node j, you also add whatever you pushed to NewMatrix[i,j], where NewMatrix is the matrix A-B and you get the matrix you want.

Also note that in the beginning, in the matrix A-B, you had the smallest C[i,j] that you had to subtract from A[i,j] to get something smaller or equal to B[i,j], and now that you added something to that C[i,j] the inequality A[i,j]-C[i,j]<=B[i,j] still holds.

Read More